ploop/scripts/parse_static_module_specifiers.mjs

85 lines
2.5 KiB
JavaScript

import { readFileSync, statSync } from 'node:fs';
import { extname, isAbsolute } from 'node:path';
// stdin: a JSON array of absolute .ts/.tsx paths. stdout: JSON lines of static declarations.
// createSourceFile only parses text; it neither resolves nor executes imported modules.
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,
});
}
}
}
// Keep failures atomic: an invalid later file must not emit a partial success result.
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;
}