New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

doc-snippets

Package Overview
Dependencies
Maintainers
2
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

doc-snippets - npm Package Compare versions

Comparing version 0.3.0 to 0.4.0-pre.0

build/lib/defaults/defaultDocSnippetsConfig.d.ts

79

build/cli.js

@@ -38,2 +38,5 @@ "use strict";

};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -43,2 +46,4 @@ exports.run = void 0;

var commander_1 = require("commander");
var fs_1 = __importDefault(require("fs"));
var defaults_1 = require("./lib/defaults");
var run = function (argv) { return __awaiter(void 0, void 0, void 0, function () {

@@ -51,21 +56,27 @@ return __generator(this, function (_a) {

.command("combine")
.description("Extracts snippets from the snippets directory and outputs a copy of the documentation directory with snippets injected into it")
.argument("<snippetsDir>", "The snippets directory")
.argument("<docsDir>", "The documentation directory")
.argument("<outputDir>", "The output directory")
.option("-i, --ignore <paths...>", "Ignore specified paths")
.option("-e, --exts <exts...>", "Extensions to parse")
.action(function (snippetsDir, docsDir, outputDir, _a) {
var ignore = _a.ignore, exts = _a.exts;
return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, (0, combine_1.combineDocsAndSnippets)(snippetsDir, docsDir, outputDir, exts, ignore)];
case 1:
_b.sent();
return [2 /*return*/];
}
});
.description("Extract snippets and output documentation files with snippets injected.")
.option("-c --config <path>", "Path to configuration file (default: './package.json')")
.option("-o --output-dir <path>", "Combined documentation output directory")
.option("--extract-dir <path>", "The base directory within which to search for snippets")
.option("--extract-include <paths...>", "Include specified paths or glob patterns in snippet extraction")
.option("--extract-ignore <paths...>", "Ignore specified paths or glob patterns in snippet extraction")
.option("--inject-dir <path>", "The base directory within which to search for injectable files")
.option("--inject-include <paths...>", "Include specified paths or glob patterns in snippet injection")
.option("--inject-ignore <paths...>", "Ignore specified paths or glob patterns in snippet injection")
.action(function (options) { return __awaiter(void 0, void 0, void 0, function () {
var configFilePath, config;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
configFilePath = (_a = options.config) !== null && _a !== void 0 ? _a : "./package.json";
config = parseDocSnippetsConfig(configFilePath);
applyCommandOptionsToConfig(options, config);
return [4 /*yield*/, (0, combine_1.combineDocsAndSnippets)(config)];
case 1:
_b.sent();
return [2 /*return*/];
}
});
});
}); });
return [4 /*yield*/, commander_1.program.parseAsync(argv)];

@@ -79,2 +90,34 @@ case 1:

exports.run = run;
function parseDocSnippetsConfig(configFilePath) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
var configFileContents = fs_1.default.readFileSync(configFilePath, {
encoding: "utf-8",
});
var configJson = JSON.parse(configFileContents);
var config = configJson["doc-snippets"];
var resultConfig = {
extract: {
dir: (_b = (_a = config.extract) === null || _a === void 0 ? void 0 : _a.dir) !== null && _b !== void 0 ? _b : defaults_1.defaultDocSnippetsConfig.extract.dir,
ignore: (_d = (_c = config.extract) === null || _c === void 0 ? void 0 : _c.ignore) !== null && _d !== void 0 ? _d : defaults_1.defaultDocSnippetsConfig.extract.ignore,
include: (_f = (_e = config.extract) === null || _e === void 0 ? void 0 : _e.include) !== null && _f !== void 0 ? _f : defaults_1.defaultDocSnippetsConfig.extract.include,
},
inject: {
dir: (_h = (_g = config.inject) === null || _g === void 0 ? void 0 : _g.dir) !== null && _h !== void 0 ? _h : defaults_1.defaultDocSnippetsConfig.inject.dir,
ignore: (_k = (_j = config.inject) === null || _j === void 0 ? void 0 : _j.ignore) !== null && _k !== void 0 ? _k : defaults_1.defaultDocSnippetsConfig.inject.ignore,
include: (_m = (_l = config.inject) === null || _l === void 0 ? void 0 : _l.include) !== null && _m !== void 0 ? _m : defaults_1.defaultDocSnippetsConfig.inject.include,
},
outputDir: (_o = config.outputDir) !== null && _o !== void 0 ? _o : defaults_1.defaultDocSnippetsConfig.outputDir,
};
return resultConfig;
}
function applyCommandOptionsToConfig(options, config) {
var _a, _b, _c, _d, _e, _f, _g;
config.extract.dir = (_a = options.extractDir) !== null && _a !== void 0 ? _a : config.extract.dir;
config.extract.include = (_b = options.extractInclude) !== null && _b !== void 0 ? _b : config.extract.include;
config.extract.ignore = (_c = options.extractIgnore) !== null && _c !== void 0 ? _c : config.extract.ignore;
config.inject.dir = (_d = options.extractDir) !== null && _d !== void 0 ? _d : config.inject.dir;
config.inject.include = (_e = options.extractInclude) !== null && _e !== void 0 ? _e : config.inject.include;
config.inject.ignore = (_f = options.extractIgnore) !== null && _f !== void 0 ? _f : config.inject.ignore;
config.outputDir = (_g = options.outputDir) !== null && _g !== void 0 ? _g : config.outputDir;
}
//# sourceMappingURL=cli.js.map

@@ -1,1 +0,2 @@

export declare function combineDocsAndSnippets(snippetsDir: string, docsDir: string, outputDir: string, parseExts?: string[], ignorePaths?: string[]): Promise<void>;
import { DocSnippetsConfig } from "./types";
export declare function combineDocsAndSnippets(config: DocSnippetsConfig): Promise<void>;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

@@ -61,2 +38,13 @@ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -69,27 +57,81 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

var inject_1 = require("./inject");
var fse = __importStar(require("fs-extra"));
var fs_1 = __importDefault(require("fs"));
function combineDocsAndSnippets(snippetsDir, docsDir, outputDir, parseExts, ignorePaths) {
var path_1 = __importDefault(require("path"));
var utils_1 = require("./utils");
function combineDocsAndSnippets(config) {
return __awaiter(this, void 0, void 0, function () {
var snippets;
return __generator(this, function (_a) {
switch (_a.label) {
var snippets, injectableFiles, injectableFiles_1, injectableFiles_1_1, file, srcFilePath, dstFilePath, e_1_1, injectableFiles_2, injectableFiles_2_1, file, filePath, e_2_1;
var e_1, _a, e_2, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
console.log("- Copy ".concat(docsDir, " to ").concat(outputDir));
if (!fs_1.default.existsSync(outputDir)) {
fs_1.default.mkdirSync(outputDir);
}
fse.copySync(docsDir, outputDir, { overwrite: true });
console.log("- Extract Snippets");
return [4 /*yield*/, (0, extract_1.extractSnippets)(snippetsDir, {
parseExts: parseExts,
ignorePaths: ignorePaths,
})];
return [4 /*yield*/, (0, extract_1.extractSnippets)(config.extract)];
case 1:
snippets = _a.sent();
console.log("- Inject Snippets");
return [4 /*yield*/, (0, inject_1.injectSnippets)(snippets, outputDir)];
snippets = _c.sent();
console.log("- Copy files from ".concat(config.inject.dir, " to ").concat(config.outputDir));
if (!fs_1.default.existsSync(config.outputDir)) {
fs_1.default.mkdirSync(config.outputDir);
}
injectableFiles = (0, utils_1.searchFiles)(config.inject);
_c.label = 2;
case 2:
_a.sent();
console.log("Successfully combined documentation and snippets into ".concat(outputDir));
_c.trys.push([2, 7, 8, 9]);
injectableFiles_1 = __values(injectableFiles), injectableFiles_1_1 = injectableFiles_1.next();
_c.label = 3;
case 3:
if (!!injectableFiles_1_1.done) return [3 /*break*/, 6];
file = injectableFiles_1_1.value;
srcFilePath = path_1.default.join(config.inject.dir, file);
dstFilePath = path_1.default.join(config.outputDir, file);
console.log("- Copy ".concat(srcFilePath, " to ").concat(dstFilePath));
return [4 /*yield*/, fs_1.default.promises.cp(srcFilePath, dstFilePath, { recursive: true })];
case 4:
_c.sent();
_c.label = 5;
case 5:
injectableFiles_1_1 = injectableFiles_1.next();
return [3 /*break*/, 3];
case 6: return [3 /*break*/, 9];
case 7:
e_1_1 = _c.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 9];
case 8:
try {
if (injectableFiles_1_1 && !injectableFiles_1_1.done && (_a = injectableFiles_1.return)) _a.call(injectableFiles_1);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 9:
console.log("- Inject snippets");
_c.label = 10;
case 10:
_c.trys.push([10, 15, 16, 17]);
injectableFiles_2 = __values(injectableFiles), injectableFiles_2_1 = injectableFiles_2.next();
_c.label = 11;
case 11:
if (!!injectableFiles_2_1.done) return [3 /*break*/, 14];
file = injectableFiles_2_1.value;
filePath = path_1.default.join(config.outputDir, file);
return [4 /*yield*/, (0, inject_1.injectSnippetsIntoFile)(snippets, filePath)];
case 12:
_c.sent();
_c.label = 13;
case 13:
injectableFiles_2_1 = injectableFiles_2.next();
return [3 /*break*/, 11];
case 14: return [3 /*break*/, 17];
case 15:
e_2_1 = _c.sent();
e_2 = { error: e_2_1 };
return [3 /*break*/, 17];
case 16:
try {
if (injectableFiles_2_1 && !injectableFiles_2_1.done && (_b = injectableFiles_2.return)) _b.call(injectableFiles_2);
}
finally { if (e_2) throw e_2.error; }
return [7 /*endfinally*/];
case 17:
console.log("Successfully combined documentation and snippets into ".concat(config.outputDir));
return [2 /*return*/];

@@ -96,0 +138,0 @@ }

@@ -1,2 +0,1 @@

export * from "./defaultIgnorePaths";
export * from "./defaultParseExts";
export * from './defaultDocSnippetsConfig';

@@ -17,4 +17,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./defaultIgnorePaths"), exports);
__exportStar(require("./defaultParseExts"), exports);
__exportStar(require("./defaultDocSnippetsConfig"), exports);
//# sourceMappingURL=index.js.map

@@ -1,18 +0,3 @@

/**
* @typedef ExtractSnippetsOptions
* @type {object}
* @property {string[]} [parseExts] A list of file extensions which will be parsed for Snippets
* @property {string[]} [ignorePaths] A list of paths in `gitignore` format which will be ignored when parsing
*/
declare type ExtractSnippetsOptions = {
parseExts?: string[];
ignorePaths?: string[];
};
/**
* Extract snippets from all files within a directory
* @param {string} dir The directory to search and extract snippets from
* @param {ExtractSnippetsOptions} options Extraction options
* @returns {Record<string, string>} A Record containing all extracted Snippets
*/
export declare function extractSnippets(dir: string, options?: ExtractSnippetsOptions): Promise<Record<string, string>>;
export {};
import { SearchOptions } from "./types";
export declare function extractSnippets(options: SearchOptions): Promise<Record<string, string>>;
export declare function extractSnippetsFromFile(snippets: Record<string, string>, filePath: string): Promise<void>;

@@ -53,34 +53,27 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSnippets = void 0;
var defaults_1 = require("./defaults");
exports.extractSnippetsFromFile = exports.extractSnippets = void 0;
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var fs_1 = __importDefault(require("fs"));
var ignore_1 = __importDefault(require("ignore"));
/**
* Extract snippets from all files within a directory
* @param {string} dir The directory to search and extract snippets from
* @param {ExtractSnippetsOptions} options Extraction options
* @returns {Record<string, string>} A Record containing all extracted Snippets
*/
function extractSnippets(dir, options) {
var _a;
var utils_1 = require("./utils");
function extractSnippets(options) {
return __awaiter(this, void 0, void 0, function () {
var snippets, ignoreInstance, exts;
var snippets, filePaths, filePaths_1, filePaths_1_1, filePath;
var e_1, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
snippets = {};
ignoreInstance = (0, ignore_1.default)();
if (options === null || options === void 0 ? void 0 : options.ignorePaths) {
ignoreInstance.add(options.ignorePaths);
}
else {
ignoreInstance.add(defaults_1.defaultIgnorePaths);
}
exts = (_a = options === null || options === void 0 ? void 0 : options.parseExts) !== null && _a !== void 0 ? _a : defaults_1.defaultParseExts;
return [4 /*yield*/, searchAndExtractSnippetsFromDir(snippets, dir, exts, ignoreInstance)];
case 1:
_b.sent();
return [2 /*return*/, snippets];
snippets = {};
filePaths = (0, utils_1.searchFiles)(options);
try {
for (filePaths_1 = __values(filePaths), filePaths_1_1 = filePaths_1.next(); !filePaths_1_1.done; filePaths_1_1 = filePaths_1.next()) {
filePath = filePaths_1_1.value;
extractSnippetsFromFile(snippets, path_1.default.join(options.dir, filePath));
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (filePaths_1_1 && !filePaths_1_1.done && (_a = filePaths_1.return)) _a.call(filePaths_1);
}
finally { if (e_1) throw e_1.error; }
}
return [2 /*return*/, snippets];
});

@@ -90,74 +83,5 @@ });

exports.extractSnippets = extractSnippets;
function searchAndExtractSnippetsFromDir(snippets, dir, exts, ignoreInstance) {
return __awaiter(this, void 0, void 0, function () {
var dirents, match, dirents_1, dirents_1_1, dirent, direntPath, e_1_1;
var e_1, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
dirents = fs_1.default.readdirSync(dir, { withFileTypes: true });
match = function (str, tests) {
var e_2, _a;
try {
for (var tests_1 = __values(tests), tests_1_1 = tests_1.next(); !tests_1_1.done; tests_1_1 = tests_1.next()) {
var test = tests_1_1.value;
if (str.indexOf(test) > -1) {
return true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (tests_1_1 && !tests_1_1.done && (_a = tests_1.return)) _a.call(tests_1);
}
finally { if (e_2) throw e_2.error; }
}
return false;
};
_b.label = 1;
case 1:
_b.trys.push([1, 8, 9, 10]);
dirents_1 = __values(dirents), dirents_1_1 = dirents_1.next();
_b.label = 2;
case 2:
if (!!dirents_1_1.done) return [3 /*break*/, 7];
dirent = dirents_1_1.value;
direntPath = path_1.default.join(dir, dirent.name);
if (ignoreInstance.test(direntPath).ignored) {
return [3 /*break*/, 6];
}
if (!(dirent.isFile() && match(dirent.name, exts))) return [3 /*break*/, 4];
return [4 /*yield*/, extractSnippetsFromFile(snippets, direntPath)];
case 3:
_b.sent();
return [3 /*break*/, 6];
case 4:
if (!dirent.isDirectory()) return [3 /*break*/, 6];
return [4 /*yield*/, searchAndExtractSnippetsFromDir(snippets, direntPath, exts, ignoreInstance)];
case 5:
_b.sent();
_b.label = 6;
case 6:
dirents_1_1 = dirents_1.next();
return [3 /*break*/, 2];
case 7: return [3 /*break*/, 10];
case 8:
e_1_1 = _b.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 10];
case 9:
try {
if (dirents_1_1 && !dirents_1_1.done && (_a = dirents_1.return)) _a.call(dirents_1);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 10: return [2 /*return*/];
}
});
});
}
function extractSnippetsFromFile(snippets, filePath) {
return __awaiter(this, void 0, void 0, function () {
var contents, index, start, end, startIdx, nameStartIdx, nameEndIdx, name, snippetStartIdx, snippetEndIdx, snippet;
var contents, index, start, end, startIdx, nameStartIdx, lineEndIdx, nameEndIdx, name, snippetStartIdx, snippetEndIdx, snippet;
return __generator(this, function (_a) {

@@ -175,5 +99,9 @@ contents = fs_1.default.readFileSync(filePath, "utf-8");

nameStartIdx = startIdx + start.length;
nameEndIdx = contents.indexOf("\n", nameStartIdx);
name = contents.substr(nameStartIdx, nameEndIdx - nameStartIdx);
snippetStartIdx = nameEndIdx + 1;
lineEndIdx = contents.indexOf("\n", nameStartIdx);
nameEndIdx = contents.indexOf(" ", nameStartIdx);
if (nameEndIdx < 0 || nameEndIdx > lineEndIdx) {
nameEndIdx = lineEndIdx;
}
name = contents.substring(nameStartIdx, nameEndIdx);
snippetStartIdx = lineEndIdx + 1;
snippetEndIdx = contents.indexOf(end, snippetStartIdx);

@@ -184,3 +112,3 @@ // Walk back from the $end until we hit the first \n

}
snippet = contents.substr(snippetStartIdx, snippetEndIdx - snippetStartIdx);
snippet = contents.substring(snippetStartIdx, snippetEndIdx);
console.log("- Extract Snippet", name);

@@ -197,2 +125,3 @@ if (snippets[name]) {

}
exports.extractSnippetsFromFile = extractSnippetsFromFile;
//# sourceMappingURL=extract.js.map

@@ -1,7 +0,1 @@

/**
* Inject snippets into .md files within a directory
* @param {Record<string, string>} snippets - The snippets to inject
* @param {string} dir - The directory containing .md files
* @returns
*/
export declare function injectSnippets(snippets: Record<string, string>, dir: string): Promise<void>;
export declare function injectSnippetsIntoFile(snippets: Record<string, string>, filePath: string): Promise<void>;

@@ -38,13 +38,2 @@ "use strict";

};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -54,81 +43,6 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

Object.defineProperty(exports, "__esModule", { value: true });
exports.injectSnippets = void 0;
var path_1 = __importDefault(require("path"));
exports.injectSnippetsIntoFile = void 0;
var fs_1 = __importDefault(require("fs"));
/**
* Inject snippets into .md files within a directory
* @param {Record<string, string>} snippets - The snippets to inject
* @param {string} dir - The directory containing .md files
* @returns
*/
function injectSnippets(snippets, dir) {
function injectSnippetsIntoFile(snippets, filePath) {
return __awaiter(this, void 0, void 0, function () {
var dirents, exts, matchExt, dirents_1, dirents_1_1, dirent, direntPath, e_1_1;
var e_1, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
dirents = fs_1.default.readdirSync(dir, { withFileTypes: true });
exts = ["md"];
matchExt = function (filename) {
var e_2, _a;
try {
for (var exts_1 = __values(exts), exts_1_1 = exts_1.next(); !exts_1_1.done; exts_1_1 = exts_1.next()) {
var ext = exts_1_1.value;
if (filename.indexOf(".".concat(ext)) > -1) {
return true;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (exts_1_1 && !exts_1_1.done && (_a = exts_1.return)) _a.call(exts_1);
}
finally { if (e_2) throw e_2.error; }
}
return false;
};
_b.label = 1;
case 1:
_b.trys.push([1, 8, 9, 10]);
dirents_1 = __values(dirents), dirents_1_1 = dirents_1.next();
_b.label = 2;
case 2:
if (!!dirents_1_1.done) return [3 /*break*/, 7];
dirent = dirents_1_1.value;
direntPath = path_1.default.join(dir, dirent.name);
if (!(dirent.isFile() && matchExt(dirent.name))) return [3 /*break*/, 4];
return [4 /*yield*/, injectSnippetIntoFile(snippets, direntPath)];
case 3:
_b.sent();
return [3 /*break*/, 6];
case 4:
if (!dirent.isDirectory()) return [3 /*break*/, 6];
return [4 /*yield*/, injectSnippets(snippets, direntPath)];
case 5:
_b.sent();
_b.label = 6;
case 6:
dirents_1_1 = dirents_1.next();
return [3 /*break*/, 2];
case 7: return [3 /*break*/, 10];
case 8:
e_1_1 = _b.sent();
e_1 = { error: e_1_1 };
return [3 /*break*/, 10];
case 9:
try {
if (dirents_1_1 && !dirents_1_1.done && (_a = dirents_1.return)) _a.call(dirents_1);
}
finally { if (e_1) throw e_1.error; }
return [7 /*endfinally*/];
case 10: return [2 /*return*/];
}
});
});
}
exports.injectSnippets = injectSnippets;
function injectSnippetIntoFile(snippets, filePath) {
return __awaiter(this, void 0, void 0, function () {
var contents, modified, index, marker, markerIdx, nameStartIdx, nameEndIdx, name;

@@ -148,3 +62,3 @@ return __generator(this, function (_a) {

nameEndIdx = contents.indexOf("\n", nameStartIdx);
name = contents.substr(nameStartIdx, nameEndIdx - nameStartIdx);
name = contents.substring(nameStartIdx, nameEndIdx);
if (!snippets[name]) {

@@ -165,2 +79,3 @@ throw Error("Unknown Snippet: ".concat(name, " in ").concat(filePath));

}
exports.injectSnippetsIntoFile = injectSnippetsIntoFile;
//# sourceMappingURL=inject.js.map
{
"name": "doc-snippets",
"version": "0.3.0",
"version": "0.4.0-pre.0",
"description": "Extract and inject snippets from code into markdown files",

@@ -33,3 +33,6 @@ "author": {

"lint": "yarn eslint .",
"lint:fix": "yarn eslint --fix ."
"lint:fix": "yarn eslint --fix .",
"publish:npm": "yarn publish --access public --non-interactive --verbose",
"publish:pre:npm": "yarn publish --access public --non-interactive --verbose --tag pre",
"version:apply": "yarn version --new-version $(cat VERSION) --no-git-tag-version"
},

@@ -52,5 +55,4 @@ "devDependencies": {

"commander": "^9.4.1",
"fs-extra": "^10.1.0",
"ignore": "^5.2.1"
"glob": "^8.0.3"
}
}
# doc-snippets
`doc-snippets` is a simple tool that allows you to extract and inject snippets from code into markdown files.

@@ -7,2 +8,3 @@

Using NPM:
```bash

@@ -13,2 +15,3 @@ npm install --save-dev doc-snippets

Using Yarn:
```bash

@@ -22,14 +25,70 @@ yarn add -D doc-snippets

`doc-snippets` extracts and injects snippets by using tokens (without quotes):
`doc-snippets` extracts and injects snippets by using tokens:
- To mark a snippet:
- `"$start: snippet-name"` - The start of a snippet and its name (required)
- `"$end"` - The end of a snippet.
- `$start: snippet-name` - The start of a snippet and its name (required)
- `$end` - The end of a snippet.
- To inject a snippet:
- `"$snippet: snippet-name"` - This gets replaced by the snippet with the given name.
- `$snippet: snippet-name` - This gets replaced by the snippet with the given name.
Snippets are injected only into `.md` files.
### Configuration
`doc-snippets` is, by defaut, configured using a JSON file that contains a `doc-snippets` object. By default, this file is `package.json`.
The configuration object has the following structure (and default values):
```JSON
"doc-snippets": {
"extract": {
"include": "./**/*.{js,ts,json,yaml,txt,md,graphql,cue}",
"ignore": "./**/node_modules/**",
"dir": "./src"
},
"inject": {
"include": "./**/*.md",
"ignore": [],
"dir": "./src/docs"
},
"outputDir": "./docs"
}
```
#### `extract` and `inject`
The `extract` and `inject` objects both have the same structure:
- `include` - a string or array of strings containing paths to include. The paths are formatted as Glob patterns following the [node-glob specification](https://github.com/isaacs/node-glob)
- `ignore` - same as `include`, this is a string or array of strings containing paths to ignore. It follows the same Glob pattern specification as `include`
- `dir` - the base directory for injection and extraction. `include` and `ignore` use this directory as their base when searching for files.
The `extract` object specifies which files will be parsed for snippets to extract.
The `inject` object specifies which files will be copied into `outputDir` and have snippets injected into them.
**Example `extract` object:**
```JSON
"extract": {
"include": ["sample.sql", "./**/*.{js,ts}"],
"ignore": "./**/node_modules/**",
"dir": "./src"
}
```
In this example, `extract` will perform its search within the `./src` directory.
It will include:
- `./src/sample.sql`
- All files within `./src` and its subdirectories ending in `.js` and `.ts`
It will ignore:
- All directories and subdirectories of any `node_modules` directory found within `./src` and its subdirectories.
The same principles apply for the `inject` object.
#### `outputDir`
The `outputDir` is the output directory for the documentation injected with snippets.
### Running `doc-snippets`
`doc-snippets` comes with a CLI tool which should handle most scenarios.
`doc-snippets` comes with a CLI tool which is designed to handle most scenarios.

@@ -39,11 +98,11 @@ The CLI `combine` is the only currently supported command, and can be used as follows:

```bash
doc-snippets combine <snippetsDir> <docsDir> <outputDir>
# Extracts snippets from ./snippets and outputs a copy of ./src/docs into ./docs with injected snippets
doc-snippets combine ./snippets ./src/docs ./docs
doc-snippets combine
```
The `combine` command reads a `"doc-snippets"` section from a configuration file (by default this is `package.json`) and performs snippet extraction and injection, and outputs documentation with injected snippets into an `outputDir`.
#### Options
- `-i, --ignore <paths...>` - Ignore listed paths. Paths should be formatted according to the [gitignore spec 2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
- `-o, --output-dir <path>` - The output directory for injected documentation
- By default, only `node_modules` is ignored.

@@ -59,7 +118,11 @@

```typescript
import { extractSnippets, injectSnippets } from "doc-snippets"
import { extractSnippets, injectSnippetsIntoFile } from "doc-snippets";
const snippets = await extractSnippets("./snippets") //Returns a `Record<string, string>` of all snippets found within `./snippets`.
const snippets = await extractSnippets({
include: ["sample.sql", "./**/*.{js,ts}"],
ignore: "./**/node_modules/**",
dir: "./src"
}); //Returns snippets as `Record<string, string>`.
await injectSnippets(snippets, "./dest") //Injects `snippets` into .md files found inside `./dest`
await injectSnippetsIntoFile(snippets, "./dest/readme.md"); //Injects `snippets` into `./dest/readme.md`
```

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc