markdown-toc-gen
Version:
Generating and updating table of contents in Markdown files which conform with prettier.
70 lines (69 loc) • 2.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.MarkdownService = void 0;
const fs_1 = require("fs");
const headingsRegEx = '^\\s*(?<level>#{2,6})\\s((?<heading>.*))$';
const codeBlockRegEx = '(```[a-z]*\n[\\s\\S]*?\n\\s*```)';
/**
* MarkdownService
* provides method to parse and manipulates markdown files
*/
class MarkdownService {
constructor() {
this._headingsRegEx = new RegExp(headingsRegEx);
this._codeBlockRegEx = new RegExp(codeBlockRegEx, 'g');
}
/**
* parse given markdown file
*/
parseMarkdown(filePath) {
return (0, fs_1.readFileSync)(filePath).toString();
}
/**
* update given markdown file with toc
* @param content - markdown file content with updated toc
*/
updateMarkdown(filePath, content) {
return (0, fs_1.writeFileSync)(filePath, content);
}
/*
* extract headings from given markdown file
* @returns collection of headings structure
*/
parseHeadings(content) {
const headings = [];
for (const line of content.split('\n')) {
const match = this._headingsRegEx.exec(line);
if (match && match.groups && match.groups.level && match.groups.heading) {
const heading = match.groups.heading.trim();
headings.push({
heading,
level: match.groups.level.length - 1,
counter: headings.filter((item) => { var _a; return ((_a = item.heading) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === heading.toLowerCase(); }).length,
});
}
}
return headings;
}
/**
* removes the code blocks of the given markdown
* this is useful for parse headings and avoid parsing pseudo
* headings in code blocks
* @param content - markdown content which should be manipulated
* @returns cleaned markdown content without code blocks
*/
removeCodeBlocks(content) {
const contentWithoutCodeblocks = content.replace(this._codeBlockRegEx, '');
return contentWithoutCodeblocks;
}
/**
* set max depth for parse headers level
* @param maxDepth - max level of heading which should be parsed
*/
setMaxDepth(maxDepth) {
if (maxDepth >= 2 && maxDepth <= 6) {
this._headingsRegEx = new RegExp(headingsRegEx.replace('6', maxDepth.toString()));
}
}
}
exports.MarkdownService = MarkdownService;