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 findInlinedExternalPackages,
15 selectCliRuntimeExternalDependencies,
16 shouldBundleCliDependency,
17} from "./cli-external-packages.ts";
18
19// Only the field this test cares about; decoding ignores everything else.
20// optionalDependencies matter as much as dependencies here: every native family
21// in the list declares its actual platform bindings there (ffi-rs -> @yuuang/*,
22// msgpackr-extract -> @msgpackr-extract/*, fff-node -> @ff-labs/fff-bin-*), so
23// reading only `dependencies` would check nothing for exactly those packages.
24const PackageManifest = Schema.Struct({
25 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
26 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
27 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
28});
29type PackageManifest = typeof PackageManifest.Type;
30
31const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
32
33describe("shouldBundleCliDependency", () => {
34 it("bundles ordinary runtime dependencies", () => {
35 for (const id of ["effect", "@effect/platform", "hono", "@t3tools/shared/hostProcess"]) {
36 assert.strictEqual(shouldBundleCliDependency(id), true, id);
37 }
38 });
39
40 it("never bundles node: builtins", () => {
41 assert.strictEqual(shouldBundleCliDependency("node:fs"), false);
42 });
43
44 it("leaves native addons and their dlopen wrappers external", () => {
45 for (const id of [
46 "node-pty",
47 "ffi-rs",
48 "@yuuang/ffi-rs-win32-x64-msvc",
49 "@ff-labs/fff-node",
50 "@clerk/electron-passkeys",
51 "msgpackr-extract",
52 "@msgpackr-extract/msgpackr-extract-win32-x64",
53 ]) {
54 assert.strictEqual(shouldBundleCliDependency(id), false, id);
55 }
56 });
57
58 it("leaves bun-only entry points external", () => {
59 assert.strictEqual(shouldBundleCliDependency("@effect/platform-bun"), false);
60 assert.strictEqual(shouldBundleCliDependency("@effect/sql-sqlite-bun"), false);
61 });
62
63 // The real package is `node-gyp-build-optional-packages`, reached by prefix.
64 // It is transitive to a selected dependency root, so the runtime closure test
65 // below ensures it follows that root into the sidecar.
66 it("treats prefix-matched siblings as external", () => {
67 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
68 });
69});
70
71describe("selectCliRuntimeExternalDependencies", () => {
72 it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
73 assert.deepStrictEqual(
74 selectCliRuntimeExternalDependencies({
75 "@effect/platform-bun": "1.0.0",
76 "@ff-labs/fff-node": "2.0.0",
77 effect: "3.0.0",
78 "node-pty": "4.0.0",
79 }),
80 {
81 "@ff-labs/fff-node": "2.0.0",
82 "node-pty": "4.0.0",
83 },
84 );
85 });
86
87 it("selects every external root declared by the server", () => {
88 assert.deepStrictEqual(
89 Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
90 ["@ff-labs/fff-node", "msgpackr-extract", "node-pty"],
91 );
92 });
93});
94
95// An external package is loaded from the real filesystem, so its own `require`
96// also resolves from the real filesystem. If one of its dependencies was
97// bundled away instead of left external, that dependency does not follow the
98// selected root into the sidecar.
99//
100// Found the hard way: node-gyp-build-optional-packages requires detect-libc,
101// which was bundled. Windows was fine; WSL got MODULE_NOT_FOUND.
102it.layer(NodeServices.layer)("external package dependency closure", (it) => {
103 // Read manifests off disk from the pnpm store rather than resolving them.
104 // `require("<name>/package.json")` cannot do this job: under pnpm isolation a
105 // transitive package (detect-libc, msgpackr-extract, ffi-rs) is not reachable
106 // by name from this file at all, and an `exports` map can refuse the
107 // `/package.json` subpath outright (@ff-labs/fff-node). Both surface as "not
108 // installed", which would let this test skip everything and pass while
109 // checking nothing. The store contains the dependency graph the sidecar's
110 // minimal production install resolves.
111 const readInstalledPackages = Effect.gen(function* () {
112 const fileSystem = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const storeDir = path.resolve(
115 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
116 "../../node_modules/.pnpm",
117 );
118
119 // The store holds regular files too (lock.yaml), so a path built under one
120 // raises ENOTDIR rather than reporting absence. That throws on Linux while
121 // Windows quietly returns false, which is exactly the kind of difference
122 // this test exists to catch, so treat any failure as "not there".
123 const isPresent = (candidate: string) =>
124 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
125
126 const installed = new Map<string, PackageManifest>();
127 if (!(yield* isPresent(storeDir))) return installed;
128
129 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
130 const modulesDir = path.join(storeDir, entry, "node_modules");
131 if (!(yield* isPresent(modulesDir))) continue;
132
133 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
134 const names = owner.startsWith("@")
135 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
136 (scoped) => `${owner}/${scoped}`,
137 )
138 : [owner];
139
140 for (const name of names) {
141 if (installed.has(name)) continue;
142 const manifestPath = path.join(modulesDir, name, "package.json");
143 if (!(yield* isPresent(manifestPath))) continue;
144 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
145 }
146 }
147 }
148 return installed;
149 }).pipe(Effect.cached, Effect.runSync);
150
151 // Runtime-external only. The build-only entries resolve `bun:*` and are never
152 // loaded by Node, so their closure genuinely does not need to be external.
153 const isRuntimeExternal = (name: string) =>
154 CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => name.startsWith(prefix));
155
156 it.effect("finds the runtime-external packages on disk", () =>
157 Effect.gen(function* () {
158 const installed = yield* readInstalledPackages;
159 const found = [...installed.keys()].filter(isRuntimeExternal);
160
161 // Without this the closure check below can pass vacuously: if nothing is
162 // read, nothing is checked. These are the packages whose closure actually
163 // broke WSL, so require them by name.
164 for (const required of ["node-pty", "node-gyp-build-optional-packages", "detect-libc"]) {
165 assert.ok(
166 found.includes(required),
167 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
168 );
169 }
170 }),
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});