-
-
Notifications
You must be signed in to change notification settings - Fork 216
/
generate-types.js
48 lines (42 loc) · 1.7 KB
/
generate-types.js
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
import fs from 'fs';
import * as ohm from 'ohm-js';
import prettier from 'prettier';
import {fileURLToPath, URL} from 'url';
// Direct import from the @ohm-js/cli package!
// We do this to avoid a circular dependency between @ohm-js/cli and ohm-js.
import {getActionDecls} from '../../cli/src/helpers/generateTypes.js';
/*
This script uses the internals of @ohm-js/cli to generate portions of Ohm's
main TypeScript declarations (index.d.ts).
*/
const templatePath = new URL('./data/index.d.ts.template', import.meta.url);
const doNotEditBanner =
'// DO NOT EDIT! This file is autogenerated from scripts/data/index.d.ts.template.\n';
// Renders a very simple Mustache-style template, with variables like
// `{{varName}}` and comments like `{{! This is a comment. }}`
const render = (template, vars) =>
template.replace(/{{([^{}]*)}}/g, (_, name) => {
if (name.trim().startsWith('!')) return ''; // Comment
return vars[name]; // Variable substitution.
});
(async function main() {
// Get the BuiltInRules grammar and generate the types.
const BuiltInRules = ohm.ohmGrammar.superGrammar;
const builtInRuleActions = ['', ...getActionDecls(BuiltInRules)].join('\n ');
// Render index.d.ts from the template, overwriting the existing file contents.
const template = await fs.promises.readFile(templatePath, 'utf-8');
const output = render(template, {
builtInRuleActions,
doNotEditBanner,
});
const options = await prettier.resolveConfig(fileURLToPath(templatePath));
const formattedOutput = prettier.format(output, {
...options,
parser: 'typescript',
});
await fs.promises.writeFile(
new URL('../index.d.ts', import.meta.url),
formattedOutput,
'utf-8',
);
})();