| 1 |
/** |
| 2 |
* Remark plugin to include markdown from external files. |
| 3 |
* |
| 4 |
* Usage in markdown: |
| 5 |
* ::include{file="../path/to/file.md" start="<!-- BEGIN MARKDOWN-->"} |
| 6 |
* |
| 7 |
* Options: |
| 8 |
* - file: Path to the file to include (relative to the markdown file) |
| 9 |
* - start: Optional marker to start including from (content after this marker) |
| 10 |
* - end: Optional marker to stop including at (content before this marker) |
| 11 |
*/ |
| 12 |
|
| 13 |
import fs from 'node:fs'; |
| 14 |
import path from 'node:path'; |
| 15 |
import { visit } from 'unist-util-visit'; |
| 16 |
import { fromMarkdown } from 'mdast-util-from-markdown'; |
| 17 |
import { gfm } from 'micromark-extension-gfm'; |
| 18 |
import { gfmFromMarkdown } from 'mdast-util-gfm'; |
| 19 |
|
| 20 |
export default function remarkIncludeMarkdown(options = {}) { |
| 21 |
const { basePath = process.cwd() } = options; |
| 22 |
|
| 23 |
return (tree, file) => { |
| 24 |
const includes = []; |
| 25 |
|
| 26 |
// Find all ::include directives |
| 27 |
visit(tree, 'leafDirective', (node, index, parent) => { |
| 28 |
if (node.name !== 'include') return; |
| 29 |
|
| 30 |
const filePath = node.attributes?.file; |
| 31 |
if (!filePath) { |
| 32 |
console.warn('::include directive missing "file" attribute'); |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
// Resolve the file path relative to the docs directory |
| 37 |
const resolvedPath = path.resolve(basePath, filePath); |
| 38 |
|
| 39 |
if (!fs.existsSync(resolvedPath)) { |
| 40 |
console.warn(`Include file not found: ${resolvedPath}`); |
| 41 |
return; |
| 42 |
} |
| 43 |
|
| 44 |
let content = fs.readFileSync(resolvedPath, 'utf-8'); |
| 45 |
|
| 46 |
// Handle start marker |
| 47 |
const startMarker = node.attributes?.start; |
| 48 |
if (startMarker) { |
| 49 |
const startIndex = content.indexOf(startMarker); |
| 50 |
if (startIndex !== -1) { |
| 51 |
content = content.slice(startIndex + startMarker.length); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
// Handle end marker |
| 56 |
const endMarker = node.attributes?.end; |
| 57 |
if (endMarker) { |
| 58 |
const endIndex = content.indexOf(endMarker); |
| 59 |
if (endIndex !== -1) { |
| 60 |
content = content.slice(0, endIndex); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
content = content.trim(); |
| 65 |
|
| 66 |
// Parse the included markdown into AST nodes with GFM support |
| 67 |
const includedTree = fromMarkdown(content, { |
| 68 |
extensions: [gfm()], |
| 69 |
mdastExtensions: [gfmFromMarkdown()], |
| 70 |
}); |
| 71 |
|
| 72 |
// Store for later replacement (can't modify during visit) |
| 73 |
includes.push({ index, parent, nodes: includedTree.children }); |
| 74 |
}); |
| 75 |
|
| 76 |
// Replace directives with included content (in reverse to maintain indices) |
| 77 |
for (const { index, parent, nodes } of includes.reverse()) { |
| 78 |
parent.children.splice(index, 1, ...nodes); |
| 79 |
} |
| 80 |
}; |
| 81 |
} |