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

cli-external-packages.test.ts

248 lines9.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 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// Native platform bindings are often optional dependencies.
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});
25type PackageManifest = typeof PackageManifest.Type;
26​
27const decodeManifest = Schema.decodeUnknownSync(Schema.fromJsonString(PackageManifest));
28​
29describe("shouldBundleCliDependency", () => {
30 it("bundles ordinary runtime dependencies", () => {
31 for (const id of ["effect", "@effect/platform", "hono", "@t3tools/shared/hostProcess"]) {
32 assert.strictEqual(shouldBundleCliDependency(id), true, id);
33 }
34 });
35​
36 it("never bundles node: builtins", () => {
37 assert.strictEqual(shouldBundleCliDependency("node:fs"), false);
38 });
39​
40 it("leaves native addons and their dlopen wrappers external", () => {
41 for (const id of [
42 "node-pty",
43 "ffi-rs",
44 "@yuuang/ffi-rs-win32-x64-msvc",
45 "@ff-labs/fff-node",
46 "@clerk/electron-passkeys",
47 "msgpackr-extract",
48 "@msgpackr-extract/msgpackr-extract-win32-x64",
49 ]) {
50 assert.strictEqual(shouldBundleCliDependency(id), false, id);
51 }
52 });
53​
54 it("leaves bun-only entry points external", () => {
55 assert.strictEqual(shouldBundleCliDependency("@effect/platform-bun"), false);
56 assert.strictEqual(shouldBundleCliDependency("@effect/sql-sqlite-bun"), false);
57 });
58​
59 it("treats prefix-matched siblings as external", () => {
60 assert.strictEqual(shouldBundleCliDependency("node-gyp-build-optional-packages"), false);
61 });
62});
63​
64describe("selectCliRuntimeExternalDependencies", () => {
65 it("keeps only runtime-external dependency roots for the Windows sidecar", () => {
66 assert.deepStrictEqual(
67 selectCliRuntimeExternalDependencies({
68 "@effect/platform-bun": "1.0.0",
69 "@ff-labs/fff-node": "2.0.0",
70 effect: "3.0.0",
71 "node-pty": "4.0.0",
72 }),
73 {
74 "@ff-labs/fff-node": "2.0.0",
75 "node-pty": "4.0.0",
76 },
77 );
78 });
79​
80 it("selects every external root declared by the server", () => {
81 assert.deepStrictEqual(
82 Object.keys(selectCliRuntimeExternalDependencies(serverPackageJson.dependencies)).sort(),
83 ["@ff-labs/fff-node", "msgpackr-extract", "node-pty"],
84 );
85 });
86});
87​
88// External loaders need their transitive dependencies on disk, including detect-libc on WSL.
89it.layer(NodeServices.layer)("external package dependency closure", (it) => {
90 // Read the pnpm store directly: isolation and exports maps block package.json resolution.
91 const readInstalledPackages = Effect.gen(function* () {
92 const fileSystem = yield* FileSystem.FileSystem;
93 const path = yield* Path.Path;
94 const storeDir = path.resolve(
95 path.dirname(NodeURL.fileURLToPath(import.meta.url)),
96 "../../node_modules/.pnpm",
97 );
98​
99 // Store files such as lock.yaml produce ENOTDIR for nested paths on Linux.
100 const isPresent = (candidate: string) =>
101 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
102​
103 const installed = new Map<string, PackageManifest>();
104 if (!(yield* isPresent(storeDir))) return installed;
105​
106 for (const entry of yield* fileSystem.readDirectory(storeDir)) {
107 const modulesDir = path.join(storeDir, entry, "node_modules");
108 if (!(yield* isPresent(modulesDir))) continue;
109​
110 for (const owner of yield* fileSystem.readDirectory(modulesDir)) {
111 const names = owner.startsWith("@")
112 ? (yield* fileSystem.readDirectory(path.join(modulesDir, owner))).map(
113 (scoped) => `${owner}/${scoped}`,
114 )
115 : [owner];
116​
117 for (const name of names) {
118 if (installed.has(name)) continue;
119 const manifestPath = path.join(modulesDir, name, "package.json");
120 if (!(yield* isPresent(manifestPath))) continue;
121 installed.set(name, decodeManifest(yield* fileSystem.readFileString(manifestPath)));
122 }
123 }
124 }
125 return installed;
126 }).pipe(Effect.cached, Effect.runSync);
127​
128 // Node never loads the build-only Bun imports.
129 const isRuntimeExternal = (name: string) =>
130 CLI_RUNTIME_EXTERNAL_PREFIXES.some((prefix) => name.startsWith(prefix));
131​
132 // A cold walk of the pnpm store can exceed the root timeout when the Windows
133 // lane runs four filesystem-heavy workspace suites at once.
134 it.effect(
135 "finds the runtime-external packages on disk",
136 () =>
137 Effect.gen(function* () {
138 const installed = yield* readInstalledPackages;
139 const found = [...installed.keys()].filter(isRuntimeExternal);
140​
141 // Require the packages behind the WSL regression so an empty scan cannot pass.
142 for (const required of ["node-pty", "node-gyp-build-optional-packages", "detect-libc"]) {
143 assert.ok(
144 found.includes(required),
145 `expected ${required} in the pnpm store; the closure check is only meaningful if it can read these (found ${found.length})`,
146 );
147 }
148 }),
149 120_000,
150 );
151​
152 it.effect("keeps every runtime dependency of an external package external too", () =>
153 Effect.gen(function* () {
154 const installed = yield* readInstalledPackages;
155 const violations: string[] = [];
156 const seen = new Set<string>();
157 // Expand scoped prefixes to installed package names before walking dependencies.
158 const queue = [...installed.keys()].filter(isRuntimeExternal);
159​
160 for (const name of queue) {
161 if (seen.has(name)) continue;
162 seen.add(name);
163​
164 const manifest = installed.get(name);
165 if (!manifest) continue;
166​
167 const declared = {
168 ...manifest.dependencies,
169 ...manifest.optionalDependencies,
170 ...manifest.peerDependencies,
171 };
172 for (const dependency of Object.keys(declared)) {
173 if (!isRuntimeExternal(dependency)) {
174 violations.push(`${name} -> ${dependency}`);
175 }
176 if (!seen.has(dependency)) queue.push(dependency);
177 }
178 }
179​
180 assert.deepStrictEqual(
181 violations,
182 [],
183 `these dependencies of external packages would be bundled away and fail to resolve under WSL: ${violations.join(", ")}`,
184 );
185 }),
186 );
187});
188​
189describe("findInlinedExternalPackages", () => {
190 const region = (path: string) => `//#region ${path}
191var x = 1;
192//#endregion
193`;
194​
195 it("flags an external package that was inlined", () => {
196 const source =
197 region("../../node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js") +
198 region(
199 "../../node_modules/.pnpm/msgpackr-extract@3.0.4/node_modules/msgpackr-extract/index.js",
200 );
201 const result = findInlinedExternalPackages(source);
202​
203 assert.deepStrictEqual(result.inlined, ["detect-libc", "msgpackr-extract"]);
204 assert.strictEqual(result.regionCount, 2);
205 });
206​
207 it("flags scoped external packages", () => {
208 const result = findInlinedExternalPackages(
209 region("../../node_modules/@ff-labs/fff-node/dist/src/index.js"),
210 );
211 assert.deepStrictEqual(result.inlined, ["@ff-labs/fff-node"]);
212 });
213​
214 it("ignores packages that are meant to be bundled", () => {
215 const source =
216 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
217 region("../../src/server/main.ts");
218 const result = findInlinedExternalPackages(source);
219​
220 assert.deepStrictEqual(result.inlined, []);
221 assert.strictEqual(result.regionCount, 2);
222 });
223​
224 // Verify ordinary packages are bundled too; an all-external bundle must not pass.
225 it("reports the packages that were inlined, not just the violations", () => {
226 const source =
227 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js") +
228 region("../../node_modules/.pnpm/yaml@2.4.0/node_modules/yaml/dist/index.js") +
229 region("../../src/server/main.ts");
230 const result = findInlinedExternalPackages(source);
231​
232 assert.deepStrictEqual(result.inlinedPackages, ["effect", "yaml"]);
233 assert.deepStrictEqual(result.inlined, []);
234 });
235​
236 it("does not report the pnpm store directory as a package", () => {
237 const result = findInlinedExternalPackages(
238 region("../../node_modules/.pnpm/effect@4.0.0/node_modules/effect/dist/index.js"),
239 );
240 assert.deepStrictEqual(result.inlinedPackages, ["effect"]);
241 });
242​
243 it("reports no regions when the marker format is absent", () => {
244 const result = findInlinedExternalPackages("var x = 1; // node_modules/detect-libc/lib.js");
245 assert.strictEqual(result.regionCount, 0);
246 assert.deepStrictEqual(result.inlined, []);
247 });
248});