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

cli-external-packages.test.ts

268 lines9.9 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 { findEsmImportsOfExternalPackages } from "./cli-executable-imports.ts";
11​
12import {
13 isRuntimeExternalCliDependency,
14 findInlinedExternalPackages,
15 selectCliRuntimeExternalDependencies,
16 shouldBundleCliDependency,
17} from "./cli-external-packages.ts";
18​
19// Native bindings live in optionalDependencies; checking dependencies alone misses them.
20const PackageManifest = Schema.Struct({
21 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
22 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
23 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
24 peerDependenciesMeta: Schema.optional(
25 Schema.Record(Schema.String, Schema.Struct({ optional: Schema.optional(Schema.Boolean) })),
26 ),
27});
28type PackageManifest = typeof PackageManifest.Type;
29​
30const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
31​
32describe("shouldBundleCliDependency", () => {
33 it("leaves native addons and their dlopen wrappers external", () => {
34 for (const id of [
35 "node-pty",
36 "ffi-rs",
37 "@yuuang/ffi-rs-win32-x64-msvc",
38 "@ff-labs/fff-node",
39 "@napi-rs/keyring",
40 "@clerk/electron-passkeys",
41 "node-addon-api",
42 ]) {
43 assert.strictEqual(shouldBundleCliDependency(id), false, id);
44 }
45 });
46​
47 it("treats prefix-matched siblings as external", () => {
48 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
49 });
50});
51​
52it.layer(NodeServices.layer)("external package dependency closure", (it) => {
53 // Read the pnpm store directly: isolation hides transitive names and exports maps can block package.json.
54 const readInstalledPackages = Effect.gen(function* () {
55 const fileSystem = yield* FileSystem.FileSystem;
56 const path = yield* Path.Path;
57 const storeDir = path.resolve(
58 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
59 "../../node_modules/.pnpm",
60 );
61​
62 // Paths under store files such as lock.yaml raise ENOTDIR, not absence.
63 const isPresent = (candidate: string) =>
64 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
65​
66 const installed = new Map<string, PackageManifest>();
67 if (!(yield* isPresent(storeDir))) return installed;
68​
69 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
70 const modulesDir = path.join(storeDir, entry, "node_modules");
71 if (!(yield* isPresent(modulesDir))) continue;
72​
73 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
74 const names = owner.startsWith("@")
75 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
76 (scoped) => `${owner}/${scoped}`,
77 )
78 : [owner];
79​
80 for (const name of names) {
81 if (installed.has(name)) continue;
82 const manifestPath = path.join(modulesDir, name, "package.json");
83 if (!(yield* isPresent(manifestPath))) continue;
84 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
85 }
86 }
87 }
88 return installed;
89 }).pipe(Effect.cached, Effect.runSync);
90​
91 const isRuntimeExternal = isRuntimeExternalCliDependency;
92​
93 it.effect("keeps every runtime dependency of an external package external too", () =>
94 Effect.gen(function* () {
95 const installed = yield* readInstalledPackages;
96 const violations: string[] = [];
97 const seen = new Set<string>();
98 const queue = [...installed.keys()].filter(isRuntimeExternal);
99​
100 for (const name of queue) {
101 if (seen.has(name)) continue;
102 seen.add(name);
103​
104 const manifest = installed.get(name);
105 if (!manifest) continue;
106​
107 const declared = {
108 ...manifest.dependencies,
109 ...manifest.optionalDependencies,
110 ...manifest.peerDependencies,
111 };
112 for (const dependency of Object.keys(declared)) {
113 if (!isRuntimeExternal(dependency)) {
114 violations.push(`${name} -> ${dependency}`);
115 }
116 if (!seen.has(dependency)) queue.push(dependency);
117 }
118 }
119​
120 assert.deepStrictEqual(
121 violations,
122 [],
123 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
124 );
125 }),
126 );
127​
128 // The stage installs only externals the server lists, so a required peer must be reachable from them.
129 it.effect("stages a provider for every required peer of a staged external", () =>
130 Effect.gen(function* () {
131 const fileSystem = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const installed = yield* readInstalledPackages;
134 const server = decodeManifest(
135 yield* fileSystem.readFileString(
136 path.resolve(
137 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
138 "../../apps/server/package.json",
139 ),
140 ),
141 );
142​
143 const staged = new Set<string>();
144 const queue = Object.keys(selectCliRuntimeExternalDependencies(server.dependencies ?? {}));
145 for (const name of queue) {
146 if (staged.has(name)) continue;
147 staged.add(name);
148 const manifest = installed.get(name);
149 queue.push(
150 ...Object.keys({ ...manifest?.dependencies, ...manifest?.optionalDependencies }),
151 );
152 }
153​
154 const missing = [...staged].flatMap((name) => {
155 const manifest = installed.get(name);
156 return Object.keys(manifest?.peerDependencies ?? {})
157 .filter((peer) => !manifest?.peerDependenciesMeta?.[peer]?.optional && !staged.has(peer))
158 .map((peer) => `${name} -> ${peer}`);
159 });
160​
161 assert.deepStrictEqual(
162 missing,
163 [],
164 `these peers of staged external packages are missing from the packaged app; add them to apps/server dependencies: ${missing.join(", ")}`,
165 );
166 }),
167 );
168});
169​
170describe("findInlinedExternalPackages", () => {
171 const region = (path: string) => `//#region ${path}
172var x = 1;
173//#endregion
174`;
175​
176 it("flags an external package that was inlined", () => {
177 const source =
178 region("../../node_modules/.pnpm/node-addon-api@7.1.1/node_modules/node-addon-api/index.js") +
179 region(
180 "../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js",
181 );
182 const result = findInlinedExternalPackages(source);
183​
184 assert.deepStrictEqual(result.inlined, ["node-addon-api", "node-gyp-build-optional-packages"]);
185 assert.strictEqual(result.regionCount, 2);
186 });
187​
188 it("reports the packages that were inlined, not just the violations", () => {
189 const source =
190 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
191 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
192 region("../../src/server/main.ts");
193 const result = findInlinedExternalPackages(source);
194​
195 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
196 assert.deepStrictEqual(result.inlined, []);
197 });
198​
199 it("reads the plain `// <path>` markers newer Rolldown emits", () => {
200 const source = [
201 "// \0rolldown/runtime.js",
202 "var x = 1;",
203 "// ../../node_modules/.pnpm/node-addon-api@7.1.1/node_modules/node-addon-api/index.js",
204 "var y = 2; // trailing comment",
205 "// ../../src/server/main.ts",
206 "",
207 ].join("\n");
208 const result = findInlinedExternalPackages(source);
209​
210 assert.strictEqual(result.regionCount, 3);
211 assert.deepStrictEqual(result.inlined, ["node-addon-api"]);
212 });
213});
214​
215describe("findEsmImportsOfExternalPackages", () => {
216 it("flags static and dynamic imports of file-backed packages", () => {
217 const source = [
218 'import { FileFinder } from "@ff-labs/fff-node";',
219 'import * as fs from "fs";',
220 'import { createRequire } from "node:module";',
221 'const pty = () => import("node-pty");',
222 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
223 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
224 'const local = () => import("./chunk-abc.mjs");',
225 ].join("\n");
226​
227 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
228 "@ff-labs/fff-bin-linux-x64-gnu",
229 "@ff-labs/fff-node",
230 "ffi-rs",
231 "node-pty",
232 ]);
233 });
234​
235 it("flags side-effect imports and re-exports too", () => {
236 const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
237 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
238 "ffi-rs",
239 "msgpackr-extract",
240 ]);
241 });
242​
243 it("ignores imports inside generated extension source and comments", () => {
244 const source = [
245 'const extension = `import { Type } from "typebox";\nimport type { ExtensionAPI } from "@earendil-works/pi-coding-agent";`;',
246 '// import "comment-only";',
247 "const example = 'import(\"string-only\")';",
248 'const interpolated = `source ${import("real-package")}`;',
249 ].join("\n");
250 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), ["real-package"]);
251 });
252​
253 it("allows optional dynamic Bun built-ins but rejects static imports", () => {
254 assert.deepStrictEqual(
255 findEsmImportsOfExternalPackages('const load = () => import("bun:sqlite");'),
256 [],
257 );
258 assert.deepStrictEqual(
259 findEsmImportsOfExternalPackages('import { Database } from "bun:sqlite";'),
260 ["bun:sqlite"],
261 );
262 });
263​
264 it("does not mistake createRequire calls for imports", () => {
265 const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
266 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
267 });
268});