import { readFileSync, statSync } from 'node:fs'; import { extname, isAbsolute } from 'node:path'; // stdin:由 .ts/.tsx 绝对路径组成的 JSON 数组。stdout:每行一条静态声明的 JSON 记录。 // createSourceFile 只解析文本,不解析导入路径,也不执行导入的模块。 async function main() { let paths; try { paths = JSON.parse(readFileSync(0, 'utf8')); } catch { throw new Error('Expected a non-empty JSON array of source paths on stdin'); } if (!Array.isArray(paths) || paths.length === 0) { throw new Error('Expected a non-empty JSON array of source paths on stdin'); } let ts; try { ({ default: ts } = await import('../frontend/node_modules/typescript/lib/typescript.js')); } catch { throw new Error( 'Cannot load the locked TypeScript compiler; run: pnpm --dir frontend install --frozen-lockfile', ); } const records = []; for (const path of paths) { if ( typeof path !== 'string' || !isAbsolute(path) || !['.ts', '.tsx'].includes(extname(path)) ) { throw new Error( 'Invalid source path: expected an absolute .ts or .tsx file', ); } let source; try { if (!statSync(path).isFile()) throw new Error('not a file'); source = readFileSync(path, 'utf8'); } catch { throw new Error(`Invalid source path: cannot read file ${path}`); } const kind = extname(path) === '.tsx' ? ts.ScriptKind.TSX : ts.ScriptKind.TS; const sourceFile = ts.createSourceFile( path, source, ts.ScriptTarget.Latest, false, kind, ); for (const statement of sourceFile.statements) { const moduleSpecifier = ts.isImportDeclaration(statement) ? statement.moduleSpecifier : ts.isExportDeclaration(statement) ? statement.moduleSpecifier : undefined; if (moduleSpecifier && ts.isStringLiteral(moduleSpecifier)) { records.push({ path, line: sourceFile.getLineAndCharacterOfPosition( statement.getStart(sourceFile), ).line + 1, specifier: moduleSpecifier.text, }); } } } // 保证失败时不输出部分结果:即使后面的文件无效,也不能输出前面成功解析的记录。 if (records.length) process.stdout.write( records.map((record) => JSON.stringify(record)).join('\n') + '\n', ); } try { await main(); } catch (error) { process.stderr.write(`static-module-parser: ${error.message}\n`); process.exitCode = 2; }