Open History to see the last commit
1import * as NodeURL from "node:url";
2
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, describe, it } from "@effect/vitest";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9
10import serverPackageJson from "../../apps/server/package.json" with { type: "json" };
11
12import {
13 CLI_RUNTIME_EXTERNAL_PREFIXES,
14 findEsmImportsOfExternalPackages,
15 findInlinedExternalPackages,
16 selectCliRuntimeExternalDependencies,
17 shouldBundleCliDependency,
18} from "./cli-external-packages.ts";
19
20// Only the field this test cares about; decoding ignores everything else.
21// optionalDependencies matter as much as dependencies here: every native family
22// in the list declares its actual platform bindings there (ffi-rs -> @yuuang/*,
23// msgpackr-extract -> @msgpackr-extract/*, fff-node -> @ff-labs/fff-bin-*), so
24// reading only `dependencies` would check nothing for exactly those packages.
25const PackageManifest = Schema.Struct({
26 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
27 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
28 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
29});
30type PackageManifest = typeof PackageManifest.Type;
31
32const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
33
34describe("shouldBundleCliDependency", () => {
35 it("bundles ordinary runtime dependencies", () => {
36 for (const id of ["effect", "@effect/platform", "hono", "@t3tools/shared/hostProcess"]) {
37 assert.strictEqual(shouldBundleCliDependency(id), true, id);
38 }
39 });
40
41 it("never bundles node: builtins", () => {
42 assert.strictEqual(shouldBundleCliDependency("node:fs"), false);
43 });
44
45 it("leaves native addons and their dlopen wrappers external", () => {
46 for (const id of [
47 "node-pty",
48 "ffi-rs",
49 "@yuuang/ffi-rs-win32-x64-msvc",
50 "@ff-labs/fff-node",
51 "@clerk/electron-passkeys",
52 "msgpackr-extract",
53 "@msgpackr-extract/msgpackr-extract-win32-x64",
54 ]) {
55 assert.strictEqual(shouldBundleCliDependency(id), false, id);
56 }
57 });
58
59 // The real package is `node-gyp-build-optional-packages`, reached by prefix.
60 // It is transitive to a selected dependency root, so the runtime closure test
61 // below ensures it follows that root into the sidecar.
62 it("treats prefix-matched siblings as external", () => {
63 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
64 });
65});
66
67describe("selectCliRuntimeExternalDependencies", () => {
68 it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
69 assert.deepStrictEqual(
70 selectCliRuntimeExternalDependencies({
71 "@ff-labs/fff-node": "2.0.0",
72 effect: "3.0.0",
73 "node-pty": "4.0.0",
74 }),
75 {
76 "@ff-labs/fff-node": "2.0.0",
77 "node-pty": "4.0.0",
78 },
79 );
80 });
81
82 it("selects every external root declared by the server", () => {
83 assert.deepStrictEqual(
84 Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
85 ["@ff-labs/fff-node", "msgpackr-extract", "node-pty"],
86 );
87 });
88});
89
90// An external package is loaded from the real filesystem, so its own `require`
91// also resolves from the real filesystem. If one of its dependencies was
92// bundled away instead of left external, that dependency does not follow the
93// selected root into the sidecar.
94//
95// Found the hard way: node-gyp-build-optional-packages requires detect-libc,
96// which was bundled. Windows was fine; WSL got MODULE_NOT_FOUND.
97it.layer(NodeServices.layer)("external package dependency closure", (it) => {
98 // Read manifests off disk from the pnpm store rather than resolving them.
99 // `require("<name>/package.json")` cannot do this job: under pnpm isolation a
100 // transitive package (detect-libc, msgpackr-extract, ffi-rs) is not reachable
101 // by name from this file at all, and an `exports` map can refuse the
102 // `/package.json` subpath outright (@ff-labs/fff-node). Both surface as "not
103 // installed", which would let this test skip everything and pass while
104 // checking nothing. The store contains the dependency graph the sidecar's
105 // minimal production install resolves.
106 const readInstalledPackages = Effect.gen(function* () {
107 const fileSystem = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const storeDir = path.resolve(
110 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
111 "../../node_modules/.pnpm",
112 );
113
114 // The store holds regular files too (lock.yaml), so a path built under one
115 // raises ENOTDIR rather than reporting absence. That throws on Linux while
116 // Windows quietly returns false, which is exactly the kind of difference
117 // this test exists to catch, so treat any failure as "not there".
118 const isPresent = (candidate: string) =>
119 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
120
121 const installed = new Map<string, PackageManifest>();
122 if (!(yield* isPresent(storeDir))) return installed;
123
124 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
125 const modulesDir = path.join(storeDir, entry, "node_modules");
126 if (!(yield* isPresent(modulesDir))) continue;
127
128 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
129 const names = owner.startsWith("@")
130 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
131 (scoped) => `${owner}/${scoped}`,
132 )
133 : [owner];
134
135 for (const name of names) {
136 if (installed.has(name)) continue;
137 const manifestPath = path.join(modulesDir, name, "package.json");
138 if (!(yield* isPresent(manifestPath))) continue;
139 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
140 }
141 }
142 }
143 return installed;
144 }).pipe(Effect.cached, Effect.runSync);
145
146 // Runtime-external only. The build-only entries resolve `bun:*` and are never
147 // loaded by Node, so their closure genuinely does not need to be external.
148 const isRuntimeExternal = (name: string) =>
149 CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => name.startsWith(prefix));
150
151 // A cold walk of the pnpm store can exceed the root timeout when the Windows
152 // lane runs four filesystem-heavy workspace suites at once.
153 it.effect(
154 "finds the runtime-external packages on disk",
155 () =>
156 Effect.gen(function* () {
157 const installed = yield* readInstalledPackages;
158 const found = [...installed.keys()].filter(isRuntimeExternal);
159
160 // Without this the closure check below can pass vacuously: if nothing is
161 // read, nothing is checked. These are the packages whose closure actually
162 // broke WSL, so require them by name.
163 for (const required of ["node-pty", "node-gyp-build-optional-packages", "detect-libc"]) {
164 assert.ok(
165 found.includes(required),
166 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
167 );
168 }
169 }),
170 120_000,
171 );
172
173 it.effect("keeps every runtime dependency of an external package external too", () =>
174 Effect.gen(function* () {
175 const installed = yield* readInstalledPackages;
176 const violations: string[] = [];
177 const seen = new Set<string>();
178 // Seeded from what is actually installed and matches a prefix, so scoped
179 // prefixes like "@yuuang/" and "@ff-labs/" are covered too. Seeding from
180 // the prefix strings themselves would skip every scoped entry, since a
181 // prefix is not a package name.
182 const queue = [...installed.keys()].filter(isRuntimeExternal);
183
184 for (const name of queue) {
185 if (seen.has(name)) continue;
186 seen.add(name);
187
188 const manifest = installed.get(name);
189 if (!manifest) continue;
190
191 const declared = {
192 ...(manifest.dependencies ?? {}),
193 ...(manifest.optionalDependencies ?? {}),
194 ...(manifest.peerDependencies ?? {}),
195 };
196 for (const dependency of Object.keys(declared)) {
197 if (!isRuntimeExternal(dependency)) {
198 violations.push(`${name} -> ${dependency}`);
199 }
200 if (!seen.has(dependency)) queue.push(dependency);
201 }
202 }
203
204 assert.deepStrictEqual(
205 violations,
206 [],
207 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
208 );
209 }),
210 );
211});
212
213// Configuring the bundler is not the same as checking what it emitted. These
214// exercise the scanner against the marker shape rolldown actually produces.
215describe("findInlinedExternalPackages", () => {
216 const region = (path: string) => `//#region ${path}
217var x = 1;
218//#endregion
219`;
220
221 it("flags an external package that was inlined", () => {
222 const source =
223 region("../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js") +
224 region(
225 "../../node_modules/.pnpm/msgpackr-extract@3.0.4/node_modules/msgpackr-extract/index.js",
226 );
227 const result = findInlinedExternalPackages(source);
228
229 assert.deepStrictEqual(result.inlined, ["detect-libc", "msgpackr-extract"]);
230 assert.strictEqual(result.regionCount, 2);
231 });
232
233 it("flags scoped external packages", () => {
234 const result = findInlinedExternalPackages(
235 region("../../node_modules/@ff-labs/fff-node/dist/src/index.js"),
236 );
237 assert.deepStrictEqual(result.inlined, ["@ff-labs/fff-node"]);
238 });
239
240 it("ignores packages that are meant to be bundled", () => {
241 const source =
242 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
243 region("../../src/server/main.ts");
244 const result = findInlinedExternalPackages(source);
245
246 assert.deepStrictEqual(result.inlined, []);
247 assert.strictEqual(result.regionCount, 2);
248 });
249
250 // regionCount is what separates "clean" from "this scan went blind because the
251 // marker format changed". A caller that ignores it gets a vacuous pass.
252 // The scan has to answer both directions. Checking only that externals are
253 // absent still passes on a bundle that externalized everything, which is the
254 // failure this whole change prevents.
255 it("reports the packages that were inlined, not just the violations", () => {
256 const source =
257 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
258 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
259 region("../../src/server/main.ts");
260 const result = findInlinedExternalPackages(source);
261
262 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
263 assert.deepStrictEqual(result.inlined, []);
264 });
265
266 it("does not report the pnpm store directory as a package", () => {
267 const result = findInlinedExternalPackages(
268 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js"),
269 );
270 assert.deepStrictEqual(result.inlinedPackages, ["effect"]);
271 });
272
273 it("reports no regions when the marker format is absent", () => {
274 const result = findInlinedExternalPackages("var x = 1; // node_modules/detect-libc/lib.js");
275 assert.strictEqual(result.regionCount, 0);
276 assert.deepStrictEqual(result.inlined, []);
277 });
278});
279
280// The single-executable build can only `import` built-ins. A file-backed
281// import of an external package passes every bundler check and the regular
282// `node dist/bin.mjs` path, then fails inside the executable, so the scan
283// reads the emitted module graph instead.
284describe("findEsmImportsOfExternalPackages", () => {
285 it("flags static and dynamic imports of file-backed packages", () => {
286 const source = [
287 'import { FileFinder } from "@ff-labs/fff-node";',
288 'import * as fs from "fs";',
289 'import { createRequire } from "node:module";',
290 'const pty = () => import("node-pty");',
291 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
292 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
293 'const local = () => import("./chunk-abc.mjs");',
294 ].join("\n");
295
296 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
297 "@ff-labs/fff-bin-linux-x64-gnu",
298 "@ff-labs/fff-node",
299 "ffi-rs",
300 "node-pty",
301 ]);
302 });
303
304 it("flags side-effect imports and re-exports too", () => {
305 const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
306 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
307 "ffi-rs",
308 "msgpackr-extract",
309 ]);
310 });
311
312 it("does not mistake createRequire calls for imports", () => {
313 const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
314 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
315 });
316});