Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli-executable-imports.ts

45 lines1.7 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeModule from "node:module";
3import ts from "typescript-legacy";
4​
5/**
6 * Inside a Node single-executable, `import` statements and `import()` can only
7 * resolve built-in modules; any file-backed specifier throws at module
8 * evaluation (static) or at first use (dynamic). External packages therefore
9 * have to be reached through `createRequire`, which reads the real filesystem
10 * in every runtime.
11 */
12export function findEsmImportsOfExternalPackages(source: string): ReadonlyArray<string> {
13 const specifiers = new Set<string>();
14 const module = ts.createSourceFile(
15 "bundle.mjs",
16 source,
17 ts.ScriptTarget.Latest,
18 false,
19 ts.ScriptKind.JS,
20 );
21 const visit = (node: ts.Node): void => {
22 const dynamic =
23 ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword;
24 const specifierNode =
25 ts.isImportDeclaration(node) || ts.isExportDeclaration(node)
26 ? node.moduleSpecifier
27 : dynamic
28 ? node.arguments[0]
29 : undefined;
30 if (specifierNode && ts.isStringLiteralLike(specifierNode)) {
31 const specifier = specifierNode.text;
32 // Multi-runtime SDKs can retain optional Bun imports. Those are runtime
33 // built-ins, not packages to stage beside the executable. Static imports
34 // still fail here because Node would evaluate them unconditionally.
35 const runtimeBuiltin =
36 NodeModule.isBuiltin(specifier) || (dynamic && specifier.startsWith("bun:"));
37 if (!runtimeBuiltin && !specifier.startsWith("./") && !specifier.startsWith("../")) {
38 specifiers.add(specifier);
39 }
40 }
41 ts.forEachChild(node, visit);
42 };
43 visit(module);
44 return [...specifiers].sort();