forked from pangular-inspector/devtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvars.plugin.ts
More file actions
67 lines (62 loc) · 2.05 KB
/
Copy pathvars.plugin.ts
File metadata and controls
67 lines (62 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import {readFileSync} from 'node:fs';
import {join} from 'node:path';
import type {Plugin} from 'vite';
/**
* Single source of truth for "the current published version" in markdown
* content. Reads `create-ngmd/package.json` at build time (or the project's
* own `package.json` in a scaffolded site, where `create-ngmd/` doesn't
* exist), exposes its `version` as the `{{ngmd-version}}` token, and
* substitutes it into every `.md` source before AnalogJS hands the body
* to marked.
*
* Saves the two-place hand-update in changelog + technologies pages
* after every npm publish. Extend the `vars` map if you need more.
*
* Shared with `rawMdPlugin` via `substituteMdVars()` so the "Copy
* Markdown" / "Open in LLM" downloads see the same substituted text
* as the rendered page.
*/
let memo: Record<string, string> | null = null;
function readVars(root: string): Record<string, string> {
if (memo) return memo;
let version = '';
for (const file of ['create-ngmd/package.json', 'package.json']) {
try {
const pkg = JSON.parse(readFileSync(join(root, file), 'utf8'));
if (typeof pkg.version === 'string') {
version = pkg.version;
break;
}
} catch {}
}
memo = {'ngmd-version': version};
return memo;
}
/**
* Apply `{{token}}` substitutions to a markdown body. Unknown tokens
* are left in place so an unrecognised marker survives to the rendered
* page rather than silently disappearing.
*/
export function substituteMdVars(body: string, root = process.cwd()): string {
const vars = readVars(root);
return body.replace(/\{\{\s*([\w-]+)\s*\}\}/g, (match, key) => {
return key in vars ? vars[key] : match;
});
}
export function varsPlugin(): Plugin {
let root = process.cwd();
return {
name: 'ngmd-vars',
enforce: 'pre',
configResolved(cfg) {
root = cfg.root;
memo = null;
},
transform(code, id) {
if (!id.endsWith('.md')) return null;
const out = substituteMdVars(code, root);
if (out === code) return null;
return {code: out, map: null};
},
};
}