Debian Codegraph @

www/src/lib/remark-cdn-version.js

raw symbols SCIP
1 /**
2 * Remark plugin: replace a __VERSION__ token with the current htmx version,
3 * giving CDN/npm snippets across all docs a single source of truth
4 * (www/src/data/integrity.json, generated from package.json).
5 *
6 * Runs on the markdown AST, before syntax highlighting, so the token is a
7 * single text value rather than split across highlight spans. Touched node
8 * types: `code`/`inlineCode` (fenced + inline snippets), `html` (raw HTML in
9 * .md), and `mdxJsx*Element` string attributes (raw `<a href>` links in .mdx).
10 * Prose `text` nodes are intentionally left alone.
11 *
12 * JSX `<Code>` blocks in .mdx are not markdown nodes and are unaffected; those
13 * interpolate `${integrity.version}` directly.
14 *
15 * @param {{ version: string, token?: string }} options
16 */
17 export function remarkCdnVersion({version, token = '__VERSION__'} = {}) {
18 if (!version) throw new Error('remarkCdnVersion: version is required');
19 const sub = (s) => typeof s === 'string' ? s.split(token).join(version) : s;
20 return function (tree) {
21 replace(tree, sub);
22 };
23 }
24
25 function replace(node, sub) {
26 if (node.type === 'code' || node.type === 'inlineCode' || node.type === 'html') {
27 node.value = sub(node.value);
28 }
29 if (node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement') {
30 for (const attr of node.attributes || []) {
31 if (attr.type === 'mdxJsxAttribute') attr.value = sub(attr.value);
32 }
33 }
34 if (node.children) for (const child of node.children) replace(child, sub);
35 }