Files
vercel/packages/cli/scripts/compile-templates.mjs
Chris Barber 222710f612 Add type-check and unify tsconfig (#10667)
This adds a new `pnpm type-check` that leverages `turbo` to validate the TypeScript code. This can be run at the top-level or for an individual package.

The `test-lint` workflow will run it after linting and doing the prettier check.

As apart of this effort, each package's `tsconfig.json` has been simplified. There's a new top-level `tsconfig.base.json` file that extends the Vercel Style Guide for TypeScript. Each package's `tsconfig.json` has been audited and previously suppressed rules that no longer apply have been removed. The result is each package's `tsconfig.json` is greatly simplified and we can control common settings in the base config while keeping the flexibility of package-level overrides.

Lastly, in `package/cli`, `pnpm build` calls `scripts/build.mjs` which calls `scripts/compile-templates.mjs`. The `compile-templates.mjs` file was generating invalid TypeScript code. I've fixed it and now it's happier than ever.

Note: In order to run `pnpm type-check`, you must first `pnpm build` because we need the `.d.ts` definition files.
2023-10-09 11:58:23 +00:00

44 lines
1.4 KiB
JavaScript

import execa from 'execa';
import { fileURLToPath } from 'node:url';
import { readFile, writeFile, readdir, unlink } from 'node:fs/promises';
export async function compileDevTemplates() {
const dirRoot = new URL('../', import.meta.url);
// Compile the `doT.js` template files for `vercel dev`
const templatesDir = new URL('src/util/dev/templates/', dirRoot);
const dotPacker = fileURLToPath(
new URL('../../node_modules/dot/bin/dot-packer', dirRoot)
);
await execa(process.execPath, [dotPacker], {
cwd: templatesDir,
stdio: ['ignore', 'ignore', 'inherit'],
});
const files = await readdir(templatesDir);
const compiledFiles = files.filter(f => f.endsWith('.js'));
for (const file of compiledFiles) {
const fnPath = new URL(file, templatesDir);
const tsPath = fnPath.href.replace(/\.js$/, '.ts');
const def = await readFile(
new URL(fnPath.href.replace(/\.js$/, '.tsdef')),
'utf8'
);
const interfaceName = def.match(/interface (\w+)/)[1];
const { default: fn } = await import(fnPath);
const contents = `import encodeHTML from 'escape-html';
${def}
export default ${fn
.toString()
.replace(/var encodeHTML.+\(\)\);/s, '')
.replace(/\bvar\b/g, 'let')
.replace(/\(it\s*\)/s, `(it: ${interfaceName}): string`)}`;
await Promise.all([writeFile(new URL(tsPath), contents), unlink(fnPath)]);
}
}