11/**
2- * Post-build script: rewrites extensionless relative imports in a built package's
3- * dist/ output to include explicit ".js" extensions.
2+ * Post-build script: rewrites extensionless relative imports in the core
3+ * package's dist/ output to include explicit ".js" extensions.
44 *
5- * tsc with moduleResolution:"bundler" emits `from "./foo"` without an extension.
5+ * tsc with moduleResolution:"bundler" emits `from "./foo"` (no extension) .
66 * Node.js ESM requires `from "./foo.js"`. This script bridges the gap.
7- *
8- * Usage:
9- * - node scripts/rewrite-esm-imports.js rewrites packages/core/dist
10- * - node scripts/rewrite-esm-imports.js server rewrites packages/server/dist
117 */
12- import { existsSync , readFileSync , writeFileSync } from "node:fs" ;
8+ import { readFileSync , writeFileSync } from "node:fs" ;
139import { dirname , join } from "node:path" ;
1410import { fileURLToPath } from "node:url" ;
1511import { globSync } from "glob" ;
1612
1713const __dirname = dirname ( fileURLToPath ( import . meta. url ) ) ;
1814const root = join ( __dirname , ".." ) ;
19- const packageName = process . argv [ 2 ] ?? "core" ;
20- const allowedPackages = new Set ( [ "core" , "server" ] ) ;
21-
22- if ( ! allowedPackages . has ( packageName ) ) {
23- throw new Error ( `Unsupported package for ESM import rewrite: ${ packageName } ` ) ;
24- }
25-
26- const distDir = join ( root , "packages" , packageName , "dist" ) ;
27- if ( ! existsSync ( distDir ) ) {
28- throw new Error ( `Cannot rewrite ESM imports because dist directory does not exist: ${ distDir } ` ) ;
29- }
15+ const distDir = join ( root , "packages" , "core" , "dist" ) ;
3016
3117const files = globSync ( "**/*.js" , { cwd : distDir , absolute : true } ) ;
3218
33- // Match: from "./anything" or from "../anything".
34- // The negative lookahead skips specifiers that already end in common explicit extensions.
19+ // Match: from "./anything" or from "../anything"
20+ // Negative lookahead: skip if already ends with .js, .json, .node, or is a bare specifier
3521const IMPORT_RE = / ( f r o m \s + [ " ' ] ) ( \. \. ? \/ [ ^ " ' ] + ?) (?< ! \. [ a - z A - Z 0 - 9 ] { 1 , 4 } ) ( [ " ' ] ) / g;
3622
3723let totalRewrites = 0 ;
@@ -51,4 +37,4 @@ for (const filePath of files) {
5137 }
5238}
5339
54- console . log ( `\n✅ Rewrote ${ totalRewrites } imports across ${ files . length } files in ${ packageName } /dist/\n` ) ;
40+ console . log ( `\n✅ Rewrote ${ totalRewrites } imports across ${ files . length } files in core /dist/\n` ) ;
0 commit comments