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

cli-external-packages.ts

171 lines7.2 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeModule from "node:module";
3​
4/**
5 * The single source of truth for packages the server CLI bundle must NOT inline.
6 *
7 * Two consumers derive from this list, and they must never disagree:
8 *
9 * - apps/server/vite.config.ts decides what stays external to the bundle.
10 * - scripts/build-desktop-artifact.ts selects the runtime dependency roots for
11 * the Windows server sidecar.
12 *
13 * A runtime package that is external but absent from the sidecar fails as soon
14 * as Node resolves it from the emitted bundle. Keeping both consumers on one
15 * list prevents packaging from drifting away from the bundle boundary.
16 *
17 * Entries are matched as prefixes (`id.startsWith(prefix)`), so they also cover
18 * a package's platform-specific siblings — `node-gyp-build` covers
19 * `node-gyp-build-optional-packages`, `@yuuang/` covers every `ffi-rs-*` binding.
20 */
21/**
22 * External because Node actually loads them from disk at runtime.
23 *
24 * Native addons (.node), the JS wrappers that dlopen them by real path, and —
25 * critically — the ordinary JS packages those wrappers require. An external
26 * package is loaded from the real filesystem, so its own `require` also
27 * resolves from the real filesystem; a dependency that was bundled away exists
28 * only inside the emitted bundle and is unreachable there. This closure is
29 * enforced by a test, not by inspection.
30 */
31export const CLI_RUNTIME_EXTERNAL_PREFIXES = [
32 "node-pty",
33 "ffi-rs",
34 "@yuuang/",
35 "@ff-labs/",
36 "@clerk/electron-passkeys",
37 "@msgpackr-extract/",
38 "msgpackr-extract",
39 "node-gyp-build",
40 "node-addon-api",
41 // Required by node-gyp-build-optional-packages. Not native, but in the
42 // closure: without it, WSL gets MODULE_NOT_FOUND while Windows is fine.
43 "detect-libc",
44 // ws's optional accelerators. Nothing in this repo declares them, so they are
45 // not in the staged production install and the packaged app does not ship
46 // them either way -- ws wraps the require in try/catch and falls back to its
47 // JS paths. They are listed because they were being inlined from the dev
48 // store: both carry binding.gyp and prebuilds and load through
49 // node-gyp-build, and a native loader inlined into a bundle chunk searches
50 // for prebuilds that cannot be beside it. Listing them keeps that from
51 // becoming real if either is ever declared as a dependency.
52 "bufferutil",
53 "utf-8-validate",
54] as const;
55​
56export function isRuntimeExternalCliDependency(id: string): boolean {
57 return CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => id.startsWith(prefix));
59​
60/**
61 * True when `id` must stay out of the bundle.
62 *
63 * This has to be wired to the bundler's `neverBundle`, not just to
64 * `alwaysBundle`. `alwaysBundle` only forces packages IN — returning false from
65 * it means "no opinion", and the default then applies: a declared dependency
66 * stays external, but a transitive one gets bundled. That is how
67 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc ended up
68 * inlined while node-pty (a declared dependency) stayed external.
69 */
70export function isExternalCliDependency(id: string): boolean {
71 return isRuntimeExternalCliDependency(id);
73​
74/** True when the CLI bundle should inline `id` rather than leave it external. */
75export function shouldBundleCliDependency(id: string): boolean {
76 if (id.startsWith("node:")) return false;
77 return !isExternalCliDependency(id);
79​
80/** Select direct dependency roots whose runtime closure belongs in the sidecar. */
81export function selectCliRuntimeExternalDependencies(
82 dependencies: Readonly<Record<string, string>>,
83): Record<string, string> {
84 return Object.fromEntries(
85 Object.entries(dependencies).filter(([name]) => isRuntimeExternalCliDependency(name)),
86 );
88​
89/**
90 * Scan an emitted bundle chunk for ESM imports of packages that are not Node
91 * built-ins.
92 *
93 * Inside a Node single-executable, `import` statements and `import()` can only
94 * resolve built-in modules; any file-backed specifier throws at module
95 * evaluation (static) or at first use (dynamic). External packages therefore
96 * have to be reached through `createRequire`, which reads the real filesystem
97 * in every runtime. The bundler cannot enforce this, so the check reads what it
98 * produced.
99 */
100export function findEsmImportsOfExternalPackages(source: string): ReadonlyArray<string> {
101 const specifiers = new Set<string>();
102 // `import x from`, `import "side-effect"`, `export ... from`, and `import()`
103 // all resolve through the module loader.
104 const patterns = [
105 /^import\s[^;]*?\sfrom\s+["']([^"']+)["']/gm,
106 /^import\s+["']([^"']+)["']/gm,
107 /^export\s[^;]*?\sfrom\s+["']([^"']+)["']/gm,
108 // Rolldown may leave a `/* @vite-ignore */` style comment before the specifier.
109 /\bimport\(\s*(?:\/\*[\s\S]*?\*\/\s*)*["']([^"']+)["']\s*[,)]/g,
110 ];
111 for (const pattern of patterns) {
112 for (const match of source.matchAll(pattern)) {
113 const specifier = match[1];
114 if (specifier === undefined) continue;
115 if (NodeModule.isBuiltin(specifier)) continue;
116 if (specifier.startsWith("./") || specifier.startsWith("../")) continue;
117 specifiers.add(specifier);
118 }
119 }
120 return [...specifiers].sort();
122​
123/**
124 * Scan an emitted bundle chunk for runtime-external packages that were inlined.
125 *
126 * Configuring the bundler is not the same as checking what it produced. The
127 * `alwaysBundle` predicate only forces packages IN; returning false from it
128 * means "no opinion", so a transitive dependency still gets bundled by default.
129 * msgpackr-extract, node-gyp-build-optional-packages and detect-libc were
130 * inlined that way while every list-based test passed, which is why this reads
131 * the artifact instead.
132 *
133 * `regionCount` is reported so the caller can tell "nothing was inlined" apart
134 * from "the marker format changed and this scan no longer sees anything".
135 *
136 * `inlinedPackages` is every package seen in a region, which lets the caller
137 * check the opposite direction too. Verifying only that externals are absent
138 * would still pass if the bundler reverted to leaving everything external: the
139 * scan would see source-file regions, report nothing inlined, and the packaged
140 * backends would then fail with ERR_MODULE_NOT_FOUND because those packages
141 * are not in the selected sidecar closure either.
142 */
143export function findInlinedExternalPackages(source: string): {
144 readonly regionCount: number;
145 readonly inlined: ReadonlyArray<string>;
146 readonly inlinedPackages: ReadonlyArray<string>;
147} {
148 // Rolldown marks each inlined module with a `//#region <path>` comment.
149 const regionPattern = /\/\/#region\s+(\S+)/g;
150 const packagePattern = /node_modules\/((?:@[^/\s]+\/)?[^/\s]+)\//g;
151​
152 let regionCount = 0;
153 const inlined = new Set<string>();
154 const inlinedPackages = new Set<string>();
155 for (const region of source.matchAll(regionPattern)) {
156 regionCount += 1;
157 const regionPath = region[1] ?? "";
158 for (const candidate of regionPath.matchAll(packagePattern)) {
159 const name = candidate[1];
160 if (name === undefined || name === ".pnpm") continue;
161 inlinedPackages.add(name);
162 if (isExternalCliDependency(name)) inlined.add(name);
163 }
164 }
165​
166 return {
167 regionCount,
168 inlined: [...inlined].sort(),
169 inlinedPackages: [...inlinedPackages].sort(),
170 };