-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsplit-syntax-type.mjs
More file actions
42 lines (38 loc) · 1.93 KB
/
Copy pathsplit-syntax-type.mjs
File metadata and controls
42 lines (38 loc) · 1.93 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
// Postprocess for the grammar type-generation pipeline (see grammars/*/package.json
// `generate:types` and scripts/build-grammar.sh).
//
// dts-tree-sitter emits the grammar's SyntaxType as an enum inside the generated
// tree-sitter.d.ts. An enum living only in a .d.ts has no runtime representation:
// esbuild inlines its members, but Rolldown/Rolldown-based bundlers (tsdown) treat
// the .d.ts as types-only and erase it, so `node.type === SyntaxType.X` silently
// becomes `=== undefined`. To make the values exist at runtime under any bundler,
// this splits the enum into a sibling runtime syntax-type.ts and rewrites the
// .d.ts to import the enum as a type (its own NamedNode<T extends SyntaxType> etc.
// still resolve). Consumers import the value from ./syntax-type.
//
// Usage: node split-syntax-type.mjs <tree-sitter.d.ts> <syntax-type.ts>
import fs from "node:fs";
const [dtsPath, outPath] = process.argv.slice(2);
if (!dtsPath || !outPath) {
console.error("usage: split-syntax-type.mjs <tree-sitter.d.ts> <syntax-type.ts>");
process.exit(1);
}
let dts = fs.readFileSync(dtsPath, "utf8");
const start = dts.indexOf("export enum SyntaxType {");
if (start === -1) {
console.error(`split-syntax-type: no 'export enum SyntaxType' found in ${dtsPath}`);
process.exit(1);
}
const close = dts.indexOf("\n}", start); // enum members carry no nested braces
const block = dts.slice(start, close + 2); // through the closing brace
const header =
"// Auto-generated from the grammar by split-syntax-type.mjs. Do not hand-edit.\n" +
"// Runtime SyntaxType enum, split out of tree-sitter.d.ts so the values exist\n" +
"// at runtime under any bundler.\n";
fs.writeFileSync(outPath, header + block + "\n");
dts =
`import type { SyntaxType } from "./syntax-type";\n\n` +
dts.slice(0, start) +
"// SyntaxType is a runtime enum in ./syntax-type (imported as a type above)." +
dts.slice(close + 2);
fs.writeFileSync(dtsPath, dts);