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

cli-external-packages.test.ts

218 lines8.3 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 shouldBundleCliDependency,
16} from "./cli-external-packages.ts";
17​
18// optionalDependencies matter as much as dependencies here: every native family
19// in the list declares its actual platform bindings there (ffi-rs -> @yuuang/*,
20// fff-node -> @ff-labs/fff-bin-*), so reading only `dependencies` would check
21// nothing for exactly those packages.
22const PackageManifest = Schema.Struct({
23 dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
24 optionalDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
25 peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
26});
27type PackageManifest = typeof PackageManifest.Type;
28​
29const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
30​
31describe("shouldBundleCliDependency", () => {
32 it("leaves native addons and their dlopen wrappers external", () => {
33 for (const id of [
34 "node-pty",
35 "ffi-rs",
36 "@yuuang/ffi-rs-win32-x64-msvc",
37 "@ff-labs/fff-node",
38 "@napi-rs/keyring",
39 "@clerk/electron-passkeys",
40 "node-addon-api",
41 ]) {
42 assert.strictEqual(shouldBundleCliDependency(id), false, id);
43 }
44 });
45​
46 it("treats prefix-matched siblings as external", () => {
47 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
48 });
49});
50​
51it.layer(NodeServices.layer)("external package dependency closure", (it) => {
52 // Read manifests off disk from the pnpm store rather than resolving them.
53 // `require("<name>/package.json")` cannot do this job: under pnpm isolation a
54 // transitive package (node-addon-api, ffi-rs) is not reachable by name from
55 // this file at all, and an `exports` map can refuse the `/package.json`
56 // subpath outright (@ff-labs/fff-node).
57 const readInstalledPackages = Effect.gen(function* () {
58 const fileSystem = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const storeDir = path.resolve(
61 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
62 "../../node_modules/.pnpm",
63 );
64​
65 // The store holds regular files too (lock.yaml), so a path built under one
66 // raises ENOTDIR rather than reporting absence.
67 const isPresent = (candidate: string) =>
68 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
69​
70 const installed = new Map<string, PackageManifest>();
71 if (!(yield* isPresent(storeDir))) return installed;
72​
73 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
74 const modulesDir = path.join(storeDir, entry, "node_modules");
75 if (!(yield* isPresent(modulesDir))) continue;
76​
77 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
78 const names = owner.startsWith("@")
79 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
80 (scoped) => `${owner}/${scoped}`,
81 )
82 : [owner];
83​
84 for (const name of names) {
85 if (installed.has(name)) continue;
86 const manifestPath = path.join(modulesDir, name, "package.json");
87 if (!(yield* isPresent(manifestPath))) continue;
88 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
89 }
90 }
91 }
92 return installed;
93 }).pipe(Effect.cached, Effect.runSync);
94​
95 // Runtime-external only. The build-only entries resolve `bun:*` and are never
96 // loaded by Node, so their closure genuinely does not need to be external.
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​
135describe("findInlinedExternalPackages", () => {
136 const region = (path: string) => `//#region ${path}
137var x = 1;
138//#endregion
139`;
140​
141 it("flags an external package that was inlined", () => {
142 const source =
143 region("../../node_modules/.pnpm/node-addon-api@7.1.1/node_modules/node-addon-api/index.js") +
144 region(
145 "../../node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js",
146 );
147 const result = findInlinedExternalPackages(source);
148​
149 assert.deepStrictEqual(result.inlined, ["node-addon-api", "node-gyp-build-optional-packages"]);
150 assert.strictEqual(result.regionCount, 2);
151 });
152​
153 it("reports the packages that were inlined, not just the violations", () => {
154 const source =
155 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
156 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
157 region("../../src/server/main.ts");
158 const result = findInlinedExternalPackages(source);
159​
160 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
161 assert.deepStrictEqual(result.inlined, []);
162 });
163});
164​
165describe("findEsmImportsOfExternalPackages", () => {
166 it("flags static and dynamic imports of file-backed packages", () => {
167 const source = [
168 'import { FileFinder } from "@ff-labs/fff-node";',
169 'import * as fs from "fs";',
170 'import { createRequire } from "node:module";',
171 'const pty = () => import("node-pty");',
172 'const data = () => import("@ff-labs/fff-bin-linux-x64-gnu", { with: { type: "json" } });',
173 'const lazy = () => import(/* @vite-ignore */ "ffi-rs");',
174 'const local = () => import("./chunk-abc.mjs");',
175 ].join("\n");
176​
177 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
178 "@ff-labs/fff-bin-linux-x64-gnu",
179 "@ff-labs/fff-node",
180 "ffi-rs",
181 "node-pty",
182 ]);
183 });
184​
185 it("flags side-effect imports and re-exports too", () => {
186 const source = ['import "msgpackr-extract";', 'export { load } from "ffi-rs";'].join("\n");
187 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), [
188 "ffi-rs",
189 "msgpackr-extract",
190 ]);
191 });
192​
193 it("ignores imports inside generated extension source and comments", () => {
194 const source = [
195 'const extension = `import { Type } from "typebox";\nimport type { ExtensionAPI } from "@earendil-works/pi-coding-agent";`;',
196 '// import "comment-only";',
197 "const example = 'import(\"string-only\")';",
198 'const interpolated = `source ${import("real-package")}`;',
199 ].join("\n");
200 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), ["real-package"]);
201 });
202​
203 it("allows optional dynamic Bun built-ins but rejects static imports", () => {
204 assert.deepStrictEqual(
205 findEsmImportsOfExternalPackages('const load = () => import("bun:sqlite");'),
206 [],
207 );
208 assert.deepStrictEqual(
209 findEsmImportsOfExternalPackages('import { Database } from "bun:sqlite";'),
210 ["bun:sqlite"],
211 );
212 });
213​
214 it("does not mistake createRequire calls for imports", () => {
215 const source = 'const { FileFinder } = createRequire(import.meta.url)("@ff-labs/fff-node");';
216 assert.deepStrictEqual(findEsmImportsOfExternalPackages(source), []);
217 });
218});