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

cli-external-packages.test.ts

346 lines13.7 KB

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