Open History to see the last commit
1import { stripVTControlCharacters } from 'node:util'
2import { parseSync, transformWithOxc } from 'vite'
3β
4/**
5 * Validates generated code the way a browser or bundler sees it, without using
6 * the compiler's own parser: erase TypeScript (keeping every value import) and
7 * parse the result as a JavaScript module with semantic checks. This rejects
8 * syntax errors, nameless function/class declarations, duplicate bindings
9 * (including an import redeclared by a local declaration) and exports of
10 * undeclared bindings.
11 *
12 * @returns the error messages; an empty array means the module is valid.
13 */
14export async function getModuleErrors(
15 code: string,
16 filename = 'module.tsx',
17): Promise<Array<string>> {
18 let javascript: string
19 try {
20 const result = await transformWithOxc(code, filename, {
21 jsx: 'preserve',
22 typescript: { onlyRemoveTypeImports: true },
23 })
24 javascript = result.code
25 } catch (error) {
26 return [stripVTControlCharacters((error as Error).message)]
27 }
28 const { errors } = parseSync('module.jsx', javascript, {
29 sourceType: 'module',
30 showSemanticErrors: true,
31 })
32 return errors.map((error) => error.message)
33}
34β
35/** Matches a declaration of `name` in generated code, however it is printed. */
36export function declarationOf(name: string): RegExp {
37 return new RegExp(String.raw`\b(?:const|let|var|function|class)\s+${name}\b`)
38}