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

cli-external-packages.test.ts

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