The best way to control Claude Code, Codex and more from any computer or phone

main
ts 924 lines 35.5 KB
Raw
1 import * as nodeFs from "node:fs";
2 import * as os from "node:os";
3 import * as nodePath from "node:path";
4 import { describe, expect, it } from "@alchemy.run/test";
5 import * as NodeServices from "@effect/platform-node/NodeServices";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Path from "effect/Path";
9 import { rolldown, RolldownMagicString, type RolldownLog } from "rolldown";
10 import * as Bundle from "@/Bundle/Bundle";
11 import {
12 collectPureAnchors,
13 packageNameFromId,
14 purePlugin,
15 resolvePackageInfo,
16 type PackageInfo,
17 } from "@/Bundle/PurePlugin";
18
19 describe("packageNameFromId", { tags: ["unit", "local"] }, () => {
20 it("extracts a top-level package name", () => {
21 expect(packageNameFromId("/proj/node_modules/effect/dist/Effect.js")).toBe("effect");
22 });
23
24 it("extracts a scoped package name", () => {
25 expect(packageNameFromId("/proj/node_modules/@effect/cluster/dist/index.js")).toBe(
26 "@effect/cluster",
27 );
28 });
29
30 it("uses the LAST node_modules segment for nested deps", () => {
31 expect(packageNameFromId("/proj/node_modules/foo/node_modules/effect/dist/Effect.js")).toBe(
32 "effect",
33 );
34 });
35
36 it("returns null for ids outside node_modules", () => {
37 expect(packageNameFromId("/proj/src/Bundle.ts")).toBeNull();
38 });
39
40 it("normalizes Windows-style separators", () => {
41 expect(packageNameFromId("C:\\proj\\node_modules\\@effect\\cluster\\dist\\index.js")).toBe(
42 "@effect/cluster",
43 );
44 });
45 });
46
47 describe("resolvePackageInfo (filesystem walk)", { tags: ["unit", "local"] }, () => {
48 it("walks up to the nearest package.json", async () => {
49 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-resolve-pkg-"));
50 try {
51 const pkgDir = nodePath.join(root, "packages", "fancy-pkg");
52 nodeFs.mkdirSync(nodePath.join(pkgDir, "src", "deep"), { recursive: true });
53 nodeFs.writeFileSync(
54 nodePath.join(pkgDir, "package.json"),
55 JSON.stringify({ name: "@scope/fancy-pkg", sideEffects: false }),
56 );
57 const dir = nodePath.join(pkgDir, "src", "deep");
58 const cache = new Map<string, PackageInfo | null>();
59
60 const info = await resolvePackageInfo(dir, cache);
61 expect(info?.name).toBe("@scope/fancy-pkg");
62 expect(info?.sideEffects).toBe(false);
63 // Repeat hits the cache; result is identical and the visited dirs
64 // are populated.
65 expect((await resolvePackageInfo(dir, cache))?.name).toBe("@scope/fancy-pkg");
66 expect(cache.size).toBeGreaterThan(0);
67 } finally {
68 nodeFs.rmSync(root, { recursive: true, force: true });
69 }
70 });
71
72 it("caches results for sibling directories independently", async () => {
73 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-resolve-pkg-"));
74 try {
75 for (const [dir, name] of [
76 ["a", "pkg-a"],
77 ["b", "pkg-b"],
78 ] as const) {
79 nodeFs.mkdirSync(nodePath.join(root, dir, "src"), { recursive: true });
80 nodeFs.writeFileSync(nodePath.join(root, dir, "package.json"), JSON.stringify({ name }));
81 }
82 const cache = new Map<string, PackageInfo | null>();
83 expect((await resolvePackageInfo(nodePath.join(root, "a", "src"), cache))?.name).toBe(
84 "pkg-a",
85 );
86 expect((await resolvePackageInfo(nodePath.join(root, "b", "src"), cache))?.name).toBe(
87 "pkg-b",
88 );
89 } finally {
90 nodeFs.rmSync(root, { recursive: true, force: true });
91 }
92 });
93
94 it("returns null when no package.json is found upward", async () => {
95 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-resolve-pkg-"));
96 try {
97 expect(await resolvePackageInfo(root, new Map())).toBeNull();
98 } finally {
99 nodeFs.rmSync(root, { recursive: true, force: true });
100 }
101 });
102
103 it("never walks above a node_modules boundary", async () => {
104 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-resolve-pkg-"));
105 try {
106 // A stray package.json ABOVE node_modules must never be latched onto.
107 nodeFs.writeFileSync(
108 nodePath.join(root, "package.json"),
109 JSON.stringify({ name: "stray-parent" }),
110 );
111 const dir = nodePath.join(root, "node_modules", "no-manifest", "dist");
112 nodeFs.mkdirSync(dir, { recursive: true });
113 expect(await resolvePackageInfo(dir, new Map())).toBeNull();
114 } finally {
115 nodeFs.rmSync(root, { recursive: true, force: true });
116 }
117 });
118 });
119
120 describe("collectPureAnchors", { tags: ["unit", "local"] }, () => {
121 /** Applies the returned anchors to `code` with a plain string splice. */
122 const apply = (code: string, anchors: number[]): string => {
123 let out = code;
124 for (const anchor of [...anchors].sort((a, b) => b - a)) {
125 out = `${out.slice(0, anchor)}/*#__PURE__*/ ${out.slice(anchor)}`;
126 }
127 return out;
128 };
129 // Applies BOTH bound and discarded anchors — the full-annotation view a
130 // sideEffects-free package receives.
131 const annotate = async (code: string): Promise<string | null> => {
132 const anchors = await collectPureAnchors(code, "/n/effect/dist/x.js");
133 return anchors === null ? null : apply(code, [...anchors.bound, ...anchors.discarded]);
134 };
135
136 it("annotates calls in TypeScript source (worker/bun condition path)", async () => {
137 const code = `import { make } from "./util";\nexport const x: number = make();\n`;
138 const anchors = await collectPureAnchors(code, "/proj/packages/alchemy/src/Util.ts");
139 expect(anchors).not.toBeNull();
140 expect(apply(code, anchors!.bound)).toContain("/*#__PURE__*/ make()");
141 });
142
143 it("classifies variable-initializer calls as bound", async () => {
144 const anchors = await collectPureAnchors(`const x = create();`, "/n/x.js");
145 expect(anchors!.bound.length).toBe(1);
146 expect(anchors!.discarded.length).toBe(0);
147 });
148
149 it("classifies bare expression-statement calls as discarded", async () => {
150 const anchors = await collectPureAnchors(`app.get("/", handler);`, "/n/x.js");
151 expect(anchors!.bound.length).toBe(0);
152 expect(anchors!.discarded.length).toBe(1);
153 });
154
155 it("classifies assignment right-hand sides as bound, even in statement position", async () => {
156 const anchors = await collectPureAnchors(`exports.x = make();`, "/n/x.js");
157 expect(anchors!.bound.length).toBe(1);
158 expect(anchors!.discarded.length).toBe(0);
159 });
160
161 it("classifies non-final sequence expressions as discarded even in initializers", async () => {
162 const anchors = await collectPureAnchors(`const x = (register(), make());`, "/n/x.js");
163 expect(anchors!.bound.length).toBe(1);
164 expect(anchors!.discarded.length).toBe(1);
165 });
166
167 it("classifies optional-chained statement calls as discarded", async () => {
168 const anchors = await collectPureAnchors(`app?.get("/", h);`, "/n/x.js");
169 expect(anchors!.bound.length).toBe(0);
170 expect(anchors!.discarded.length).toBe(1);
171 });
172
173 it("annotates top-level call expressions", async () => {
174 expect(await annotate(`const x = create();`)).toBe(`const x = /*#__PURE__*/ create();`);
175 });
176
177 it("annotates top-level new expressions", async () => {
178 expect(await annotate(`const x = new Klass();`)).toBe(`const x = /*#__PURE__*/ new Klass();`);
179 });
180
181 it("annotates calls inside named exports", async () => {
182 expect(await annotate(`export const x = make();`)).toBe(
183 `export const x = /*#__PURE__*/ make();`,
184 );
185 });
186
187 it("annotates calls inside default exports", async () => {
188 expect(await annotate(`export default make();`)).toBe(`export default /*#__PURE__*/ make();`);
189 });
190
191 it("does NOT annotate calls inside function bodies", async () => {
192 expect(await annotate(`function f() { return inner(); }`)).toBeNull();
193 });
194
195 it("does NOT annotate IIFEs", async () => {
196 expect(await annotate(`(function () { sideEffect(); })();`)).toBeNull();
197 });
198
199 it("does NOT annotate arrow IIFEs", async () => {
200 expect(await annotate(`(() => sideEffect())();`)).toBeNull();
201 });
202
203 it("skips already-annotated calls", async () => {
204 expect(await annotate(`const x = /*#__PURE__*/ create();`)).toBeNull();
205 });
206
207 it("annotates calls through ts-as expressions", async () => {
208 expect(await annotate(`const x = make() as Foo;`)).toContain("/*#__PURE__*/ make()");
209 });
210
211 it("annotates both branches of ternary initializers", async () => {
212 const result = await annotate(`const x = cond ? a() : b();`);
213 expect(result).toContain("/*#__PURE__*/ a()");
214 expect(result).toContain("/*#__PURE__*/ b()");
215 });
216
217 it("preserves line numbers", async () => {
218 const input = `const a = first();\nconst b = second();\n`;
219 const result = await annotate(input);
220 expect(result!.split("\n").length).toBe(input.split("\n").length);
221 });
222
223 it("returns null on unparseable input", async () => {
224 expect(await collectPureAnchors(`const x = {;`, "/n/x.js")).toBeNull();
225 });
226 });
227
228 interface TransformOutput {
229 code?: unknown;
230 moduleSideEffects?: boolean | string | null;
231 }
232
233 /**
234 * Invokes a plugin's `transform` hook directly, regardless of whether it
235 * was defined as a plain function or a `{ filter, handler }` object. The
236 * plugin under test only reads `code`, `id` and `meta.magicString`, so we
237 * stub the context and meta with minimal shapes.
238 */
239 async function callTransform(
240 plugin: ReturnType<typeof purePlugin>,
241 code: string,
242 id: string,
243 ): Promise<TransformOutput | string | null> {
244 const transform = plugin.transform;
245 if (transform === undefined) throw new Error("plugin has no transform hook");
246 const handler = typeof transform === "function" ? transform : transform.handler;
247 return (await (handler as (...args: any[]) => unknown).call({} as any, code, id, {
248 moduleType: "js",
249 })) as TransformOutput | string | null;
250 }
251
252 /** Stringifies a transform result's `code` (RolldownMagicString or string). */
253 const codeOf = (result: TransformOutput | string | null): string => {
254 if (result === null) throw new Error("expected a transform result");
255 const code = typeof result === "string" ? result : result.code;
256 if (code === undefined) throw new Error("expected transformed code");
257 return String(code);
258 };
259
260 /**
261 * Invokes a plugin's `options` hook with stubbed plugin context. Awaits
262 * any returned promise so async hooks complete before we proceed.
263 */
264 async function callOptions(
265 plugin: ReturnType<typeof purePlugin>,
266 opts: { input: string; cwd?: string },
267 ): Promise<void> {
268 const optsHook = plugin.options;
269 if (typeof optsHook !== "function") return;
270 await (optsHook as (...args: any[]) => unknown).call({} as any, opts);
271 }
272
273 describe("purePlugin", { tags: ["unit", "local"] }, () => {
274 it("transforms only modules from matched packages", async () => {
275 const plugin = purePlugin();
276 const userCode = `const x = doThing();`;
277
278 const matched = await callTransform(
279 plugin,
280 userCode,
281 "/proj/node_modules/effect/dist/Effect.js",
282 );
283 expect(matched).not.toBeNull();
284 expect(codeOf(matched)).toContain("/*#__PURE__*/");
285
286 const unmatched = await callTransform(plugin, userCode, "/proj/node_modules/lodash/index.js");
287 expect(unmatched).toBeNull();
288
289 const userland = await callTransform(plugin, userCode, "/proj/src/MyModule.ts");
290 expect(userland).toBeNull();
291 });
292
293 it("returns a RolldownMagicString so rolldown generates the sourcemap natively", async () => {
294 const plugin = purePlugin();
295 const result = await callTransform(
296 plugin,
297 `const x = doThing();`,
298 "/proj/node_modules/effect/dist/Effect.js",
299 );
300 expect(result).not.toBeNull();
301 expect((result as TransformOutput).code).toBeInstanceOf(RolldownMagicString);
302 });
303
304 it("strips ?query and #hash suffixes before resolving", async () => {
305 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-query-"));
306 try {
307 const pkgDir = nodePath.join(root, "pkg");
308 nodeFs.mkdirSync(pkgDir, { recursive: true });
309 nodeFs.writeFileSync(
310 nodePath.join(pkgDir, "package.json"),
311 JSON.stringify({ name: "with-query" }),
312 );
313 const plugin = purePlugin({ packages: ["with-query"], replaceDefaults: true });
314 const result = await callTransform(
315 plugin,
316 `const x = doThing();`,
317 `${nodePath.join(pkgDir, "Mod.ts")}?v=123`,
318 );
319 expect(result).not.toBeNull();
320 expect(codeOf(result)).toContain("/*#__PURE__*/");
321 } finally {
322 nodeFs.rmSync(root, { recursive: true, force: true });
323 }
324 });
325
326 it("respects user-extended package list", async () => {
327 const plugin = purePlugin({ packages: ["my-lib"] });
328
329 const result = await callTransform(
330 plugin,
331 `const x = doThing();`,
332 "/proj/node_modules/my-lib/index.js",
333 );
334 expect(result).not.toBeNull();
335 expect(codeOf(result)).toContain("/*#__PURE__*/");
336
337 const effectResult = await callTransform(
338 plugin,
339 `const x = doThing();`,
340 "/proj/node_modules/effect/dist/Effect.js",
341 );
342 expect(effectResult).not.toBeNull();
343 });
344
345 it("replaceDefaults overrides the default package list", async () => {
346 const plugin = purePlugin({ packages: ["my-lib"], replaceDefaults: true });
347
348 const effectResult = await callTransform(
349 plugin,
350 `const x = doThing();`,
351 "/proj/node_modules/effect/dist/Effect.js",
352 );
353 expect(effectResult).toBeNull();
354 });
355
356 it("does NOT override moduleSideEffects when the package's sideEffects field is unknown", async () => {
357 // Virtual id — there is no real `package.json` to read, so the
358 // plugin must conservatively leave `moduleSideEffects` alone.
359 const plugin = purePlugin();
360 const result = await callTransform(
361 plugin,
362 `function f() { return 1; }`,
363 "/proj/node_modules/effect/dist/Effect.js",
364 );
365 // No annotatable top-level calls AND no disk-backed sideEffects:false
366 // declaration → plugin returns null (no rewrite, no hint).
367 expect(result).toBeNull();
368 });
369 });
370
371 describe("explicitly listed user package", { tags: ["unit", "local"] }, () => {
372 it.effect("overrides moduleSideEffects when a listed package declares sideEffects: false", () =>
373 Effect.gen(function* () {
374 const fs = yield* FileSystem.FileSystem;
375 const path = yield* Path.Path;
376 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-listed-sef-" });
377 yield* fs.writeFileString(
378 path.join(root, "package.json"),
379 JSON.stringify({ name: "my-pure-app", type: "module", sideEffects: false }),
380 );
381
382 const plugin = purePlugin({ packages: ["my-pure-app"] });
383
384 const result = yield* Effect.promise(() =>
385 callTransform(
386 plugin,
387 `export const v = make();\nfunction make() { return 1; }`,
388 path.join(root, "lib.ts"),
389 ),
390 );
391 expect(result).not.toBeNull();
392 expect((result as TransformOutput).moduleSideEffects).toBe(false);
393
394 yield* fs.remove(root, { recursive: true });
395 }).pipe(Effect.provide(NodeServices.layer)),
396 );
397
398 it.effect(
399 "returns a metadata-only result (no code) for side-effect-free modules with nothing to annotate",
400 () =>
401 Effect.gen(function* () {
402 const fs = yield* FileSystem.FileSystem;
403 const path = yield* Path.Path;
404 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-metaonly-" });
405 yield* fs.writeFileString(
406 path.join(root, "package.json"),
407 JSON.stringify({ name: "my-pure-app", type: "module", sideEffects: false }),
408 );
409
410 const plugin = purePlugin({ packages: ["my-pure-app"] });
411
412 // Only function declarations — nothing to annotate. The plugin
413 // must set moduleSideEffects WITHOUT returning `code` (returning
414 // untransformed code with no map is what caused rolldown's
415 // SOURCEMAP_BROKEN warning).
416 const result = yield* Effect.promise(() =>
417 callTransform(plugin, `export function f() { return 1; }`, path.join(root, "lib.ts")),
418 );
419 expect(result).not.toBeNull();
420 expect((result as TransformOutput).code).toBeUndefined();
421 expect((result as TransformOutput).moduleSideEffects).toBe(false);
422
423 yield* fs.remove(root, { recursive: true });
424 }).pipe(Effect.provide(NodeServices.layer)),
425 );
426
427 it.effect("does NOT mark entries as moduleSideEffects: false, even in matched packages", () =>
428 Effect.gen(function* () {
429 const fs = yield* FileSystem.FileSystem;
430 const path = yield* Path.Path;
431 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-entry-preserve-" });
432 yield* fs.writeFileString(
433 path.join(root, "package.json"),
434 JSON.stringify({ name: "my-app", type: "module", sideEffects: false }),
435 );
436 const entryPath = path.join(root, "entry.ts");
437
438 const plugin = purePlugin({ packages: ["my-app"] });
439 yield* Effect.promise(() => callOptions(plugin, { input: entryPath, cwd: root }));
440
441 // A bound call so the transform produces a non-null result — a
442 // discarded-only entry returns null and would skip the assertion.
443 const entryResult = yield* Effect.promise(() =>
444 callTransform(plugin, `const x = make();\nconsole.log(x);`, entryPath),
445 );
446 // The entry's moduleSideEffects flag must NOT be false regardless
447 // of what its package declares.
448 expect(entryResult).not.toBeNull();
449 expect((entryResult as TransformOutput).moduleSideEffects).not.toBe(false);
450
451 yield* fs.remove(root, { recursive: true });
452 }).pipe(Effect.provide(NodeServices.layer)),
453 );
454 });
455
456 describe("discarded-result calls (issue #949)", { tags: ["unit", "local"] }, () => {
457 it("does NOT annotate entry-module expression-statement calls (route registrations)", async () => {
458 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-949-entry-"));
459 try {
460 nodeFs.writeFileSync(
461 nodePath.join(root, "package.json"),
462 JSON.stringify({ name: "my-app", type: "module" }),
463 );
464 const entryPath = nodePath.join(root, "entry.ts");
465 const plugin = purePlugin({ packages: ["my-app"] });
466 await callOptions(plugin, { input: entryPath, cwd: root });
467
468 const code = [
469 `const app = new Hono();`,
470 `app.get("/", (c) => c.json({ code: "OK" }));`,
471 `export default { fetch: app.fetch };`,
472 ].join("\n");
473 const result = await callTransform(plugin, code, entryPath);
474 // `new Hono()` (bound to `app`) may be annotated; the discarded
475 // `app.get(...)` registration must NOT be.
476 if (result !== null) {
477 expect(codeOf(result)).not.toContain("/*#__PURE__*/ app.get");
478 }
479 } finally {
480 nodeFs.rmSync(root, { recursive: true, force: true });
481 }
482 });
483
484 it("does NOT annotate expression-statement calls in packages without an explicit sideEffects opt-in", async () => {
485 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-949-noopt-"));
486 try {
487 // No `sideEffects` field — the author never claimed purity.
488 nodeFs.writeFileSync(
489 nodePath.join(root, "package.json"),
490 JSON.stringify({ name: "my-app", type: "module" }),
491 );
492 const plugin = purePlugin({ packages: ["my-app"] });
493
494 // A NON-entry module of the user's package, imported for its side
495 // effects (`import "./routes.ts"`).
496 const code = [
497 `import { app } from "./app.ts";`,
498 `app.get("/r", () => "ok");`,
499 `export const x = makeX();`,
500 ].join("\n");
501 const result = await callTransform(plugin, code, nodePath.join(root, "routes.ts"));
502 expect(result).not.toBeNull();
503 const out = codeOf(result);
504 // Bound calls stay tree-shakeable...
505 expect(out).toContain("/*#__PURE__*/ makeX()");
506 // ...but the discarded-result registration is preserved.
507 expect(out).not.toContain("/*#__PURE__*/ app.get");
508 } finally {
509 nodeFs.rmSync(root, { recursive: true, force: true });
510 }
511 });
512
513 it("leaves the entry app's package completely untouched when it is not listed, even with sideEffects: false", async () => {
514 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-949-unlisted-"));
515 try {
516 // The app declares `sideEffects: false` (commonly cargo-culted for
517 // downstream module pruning). Without an explicit `packages` entry
518 // this must not opt the app into any annotation — deleting its own
519 // top-level registrations under minification least of all.
520 nodeFs.writeFileSync(
521 nodePath.join(root, "package.json"),
522 JSON.stringify({ name: "my-app", type: "module", sideEffects: false }),
523 );
524 const plugin = purePlugin();
525 await callOptions(plugin, { input: nodePath.join(root, "entry.ts"), cwd: root });
526
527 // A NON-entry module of the app (the entry-module guard does not
528 // apply here) with a discarded-result route registration.
529 const code = [
530 `import { app } from "./app.ts";`,
531 `app.get("/r", () => "ok");`,
532 `export const x = makeX();`,
533 ].join("\n");
534 const result = await callTransform(plugin, code, nodePath.join(root, "routes.ts"));
535 expect(result).toBeNull();
536 } finally {
537 nodeFs.rmSync(root, { recursive: true, force: true });
538 }
539 });
540
541 it("leaves the entry app's package untouched when it is not listed and declares no sideEffects field", async () => {
542 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-949-unlisted-nosef-"));
543 try {
544 nodeFs.writeFileSync(
545 nodePath.join(root, "package.json"),
546 JSON.stringify({ name: "my-app", type: "module" }),
547 );
548 const plugin = purePlugin();
549 await callOptions(plugin, { input: nodePath.join(root, "entry.ts"), cwd: root });
550
551 const result = await callTransform(
552 plugin,
553 `import { app } from "./app.ts";\napp.get("/r", () => "ok");\nexport const x = makeX();`,
554 nodePath.join(root, "routes.ts"),
555 );
556 expect(result).toBeNull();
557 } finally {
558 nodeFs.rmSync(root, { recursive: true, force: true });
559 }
560 });
561
562 it("STILL annotates expression-statement calls in packages that declare sideEffects: false", async () => {
563 // effect ships `sideEffects: []` on purpose — full annotation there is
564 // intentional and must be preserved. Use a fake on-disk package to
565 // avoid depending on the real effect layout.
566 const root = nodeFs.mkdtempSync(nodePath.join(os.tmpdir(), "alchemy-pure-949-optin-"));
567 try {
568 const pkgDir = nodePath.join(root, "node_modules", "fake-effect");
569 nodeFs.mkdirSync(pkgDir, { recursive: true });
570 nodeFs.writeFileSync(
571 nodePath.join(pkgDir, "package.json"),
572 JSON.stringify({ name: "fake-effect", sideEffects: false }),
573 );
574 const optIn = purePlugin({ packages: ["fake-effect"], replaceDefaults: true });
575 const result = await callTransform(
576 optIn,
577 `registerGlobal();`,
578 nodePath.join(pkgDir, "dist", "index.js"),
579 );
580 expect(result).not.toBeNull();
581 expect(codeOf(result)).toContain("/*#__PURE__*/ registerGlobal()");
582 } finally {
583 nodeFs.rmSync(root, { recursive: true, force: true });
584 }
585 });
586
587 it.effect("route registrations in the entry survive minify: true (end-to-end)", () =>
588 Effect.gen(function* () {
589 const fs = yield* FileSystem.FileSystem;
590 const path = yield* Path.Path;
591 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-949-e2e-" });
592
593 // A user app package with NO sideEffects declaration — the exact
594 // shape from the issue (Hono-style discarded-return registration).
595 yield* fs.writeFileString(
596 path.join(root, "package.json"),
597 JSON.stringify({ name: "my-app", type: "module" }),
598 );
599 const entry = path.join(root, "entry.ts");
600 yield* fs.writeFileString(
601 entry,
602 [
603 `import { app } from "./app.ts";`,
604 `import "./routes.ts";`,
605 `app.get("/", () => "ENTRY_ROUTE_MARKER");`,
606 `export default { fetch: (p: string) => app.handle(p) };`,
607 ].join("\n"),
608 );
609 yield* fs.writeFileString(
610 path.join(root, "app.ts"),
611 [
612 `type Handler = () => string;`,
613 `class Router {`,
614 ` routes: Record<string, Handler> = {};`,
615 ` get(p: string, h: Handler) { this.routes[p] = h; }`,
616 ` handle(p: string) { return this.routes[p]?.() ?? "404"; }`,
617 `}`,
618 `export const app = new Router();`,
619 ].join("\n"),
620 );
621 // Side-effect-imported module registering more routes — the same
622 // failure class beyond the entry file itself.
623 yield* fs.writeFileString(
624 path.join(root, "routes.ts"),
625 [
626 `import { app } from "./app.ts";`,
627 `app.get("/side", () => "SIDE_EFFECT_ROUTE_MARKER");`,
628 ].join("\n"),
629 );
630
631 const bundle = yield* Effect.tryPromise({
632 try: () => rolldown({ input: entry, cwd: root, plugins: [purePlugin()], treeshake: true }),
633 catch: (cause) => cause,
634 });
635 const { output } = yield* Effect.tryPromise({
636 try: () => bundle.generate({ format: "esm", minify: true }),
637 catch: (cause) => cause,
638 });
639 yield* Effect.tryPromise({ try: () => bundle.close(), catch: (cause) => cause });
640
641 const code = output
642 .filter((c) => c.type === "chunk")
643 .map((c) => c.code)
644 .join("\n");
645 expect(code).toContain("ENTRY_ROUTE_MARKER");
646 expect(code).toContain("SIDE_EFFECT_ROUTE_MARKER");
647
648 yield* fs.remove(root, { recursive: true });
649 }).pipe(Effect.provide(NodeServices.layer)),
650 );
651
652 it.effect(
653 "registrations in a REACHABLE module of an unlisted sideEffects:false app survive minify: true (issue #1020 end-to-end)",
654 () =>
655 Effect.gen(function* () {
656 const fs = yield* FileSystem.FileSystem;
657 const path = yield* Path.Path;
658 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-1020-e2e-" });
659
660 // The exact production shape from issue #1020: the app declares
661 // `sideEffects: false`, and route registrations live in a
662 // non-entry module whose EXPORT is used — so the module is
663 // reachable (rolldown's native package-sideEffects pruning does
664 // not apply) and only statement deletion could lose the routes.
665 // Note a side-effect-ONLY import (`import "./routes.ts"`) under
666 // `sideEffects: false` is legitimately pruned by rolldown itself;
667 // that is the field's documented module-level meaning and out of
668 // this plugin's hands.
669 yield* fs.writeFileString(
670 path.join(root, "package.json"),
671 JSON.stringify({ name: "my-app", type: "module", sideEffects: false }),
672 );
673 const entry = path.join(root, "entry.ts");
674 yield* fs.writeFileString(
675 entry,
676 [
677 `import { findRoute } from "./routes.ts";`,
678 `export default { fetch: (p: string) => findRoute(p) };`,
679 ].join("\n"),
680 );
681 yield* fs.writeFileString(
682 path.join(root, "routes.ts"),
683 [
684 `type Handler = () => string;`,
685 `class Router {`,
686 ` routes: Record<string, Handler> = {};`,
687 ` on(p: string, h: Handler) { this.routes[p] = h; }`,
688 ` find(p: string) { return this.routes[p]?.() ?? "404"; }`,
689 `}`,
690 `const matcher = new Router();`,
691 `matcher.on("/gw", () => "GATEWAY_ROUTE_MARKER");`,
692 `export const findRoute = (p: string) => matcher.find(p);`,
693 ].join("\n"),
694 );
695
696 const bundle = yield* Effect.tryPromise({
697 try: () =>
698 rolldown({ input: entry, cwd: root, plugins: [purePlugin()], treeshake: true }),
699 catch: (cause) => cause,
700 });
701 const { output } = yield* Effect.tryPromise({
702 try: () => bundle.generate({ format: "esm", minify: true }),
703 catch: (cause) => cause,
704 });
705 yield* Effect.tryPromise({ try: () => bundle.close(), catch: (cause) => cause });
706
707 const code = output
708 .filter((c) => c.type === "chunk")
709 .map((c) => c.code)
710 .join("\n");
711 expect(code).toContain("GATEWAY_ROUTE_MARKER");
712
713 yield* fs.remove(root, { recursive: true });
714 }).pipe(Effect.provide(NodeServices.layer)),
715 );
716 });
717
718 describe("Bundle.build with purePlugin", { tags: ["unit", "local"] }, () => {
719 it.effect("drops unused exports from a workspace-linked TS package (no node_modules)", () =>
720 Effect.gen(function* () {
721 const fs = yield* FileSystem.FileSystem;
722 const path = yield* Path.Path;
723 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-plugin-ts-" });
724
725 // Mimic a monorepo workspace symlink: the package lives at
726 // packages/fake-ws/, with `src/index.ts` directly importable.
727 const pkgDir = path.join(root, "packages", "fake-ws");
728 yield* fs.makeDirectory(path.join(pkgDir, "src"), { recursive: true });
729 yield* fs.writeFileString(
730 path.join(pkgDir, "package.json"),
731 JSON.stringify({
732 name: "fake-ws",
733 version: "0.0.0",
734 type: "module",
735 sideEffects: false,
736 exports: { ".": "./src/index.ts" },
737 }),
738 );
739 yield* fs.writeFileString(
740 path.join(pkgDir, "src", "index.ts"),
741 [
742 `export const used: string = makeUsed();`,
743 `export const unused: string = makeUnused();`,
744 `function makeUsed(): string { return "USED_TS_MARKER"; }`,
745 `function makeUnused(): string { return "UNUSED_TS_MARKER"; }`,
746 ].join("\n"),
747 );
748
749 // Symlink the package under node_modules so rolldown can find it.
750 // Windows requires elevation for "dir" symlinks; junctions don't.
751 const nm = path.join(root, "node_modules");
752 yield* fs.makeDirectory(nm, { recursive: true });
753 nodeFs.symlinkSync(
754 pkgDir,
755 path.join(nm, "fake-ws"),
756 process.platform === "win32" ? "junction" : "dir",
757 );
758
759 const entry = path.join(root, "entry.ts");
760 yield* fs.writeFileString(entry, `import { used } from "fake-ws";\nconsole.log(used);`);
761
762 const result = yield* Effect.tryPromise({
763 try: () =>
764 rolldown({
765 input: entry,
766 cwd: root,
767 plugins: [purePlugin({ packages: ["fake-ws"], replaceDefaults: true })],
768 treeshake: true,
769 }),
770 catch: (cause) => cause,
771 });
772 const { output } = yield* Effect.tryPromise({
773 try: () => result.generate({ format: "esm" }),
774 catch: (cause) => cause,
775 });
776 yield* Effect.tryPromise({ try: () => result.close(), catch: (cause) => cause });
777
778 const code = output
779 .filter((c) => c.type === "chunk")
780 .map((c) => c.code)
781 .join("\n");
782 expect(code).toContain("USED_TS_MARKER");
783 expect(code).not.toContain("UNUSED_TS_MARKER");
784
785 yield* fs.remove(root, { recursive: true });
786 }).pipe(Effect.provide(NodeServices.layer)),
787 );
788
789 it.effect("drops unused exports from a side-effect-free fake package", () =>
790 Effect.gen(function* () {
791 const fs = yield* FileSystem.FileSystem;
792 const path = yield* Path.Path;
793 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-plugin-" });
794
795 const fakePkgDir = path.join(root, "node_modules", "fake-effect");
796 yield* fs.makeDirectory(fakePkgDir, { recursive: true });
797 yield* fs.writeFileString(
798 path.join(fakePkgDir, "package.json"),
799 JSON.stringify({
800 name: "fake-effect",
801 version: "0.0.0",
802 type: "module",
803 main: "./index.js",
804 exports: { ".": "./index.js" },
805 }),
806 );
807 // Module-top-level call without annotation: bundlers normally
808 // assume this could have side-effects and keep it. With pure
809 // annotations + sideEffects:false we expect it dropped.
810 yield* fs.writeFileString(
811 path.join(fakePkgDir, "index.js"),
812 [
813 `export const used = makeUsed();`,
814 `export const unused = makeUnused();`,
815 `function makeUsed() { return "USED_MARKER"; }`,
816 `function makeUnused() { return "UNUSED_MARKER"; }`,
817 ].join("\n"),
818 );
819
820 const entry = path.join(root, "entry.js");
821 yield* fs.writeFileString(entry, `import { used } from "fake-effect"; console.log(used);`);
822
823 const result = yield* Effect.tryPromise({
824 try: () =>
825 rolldown({
826 input: entry,
827 cwd: root,
828 plugins: [purePlugin({ packages: ["fake-effect"], replaceDefaults: true })],
829 treeshake: true,
830 }),
831 catch: (cause) => cause,
832 });
833 const { output } = yield* Effect.tryPromise({
834 try: () => result.generate({ format: "esm" }),
835 catch: (cause) => cause,
836 });
837 yield* Effect.tryPromise({ try: () => result.close(), catch: (cause) => cause });
838
839 const code = output
840 .filter((c) => c.type === "chunk")
841 .map((c) => c.code)
842 .join("\n");
843 expect(code).toContain("USED_MARKER");
844 expect(code).not.toContain("UNUSED_MARKER");
845
846 yield* fs.remove(root, { recursive: true });
847 }).pipe(Effect.provide(NodeServices.layer)),
848 );
849
850 it.effect("emits valid sourcemaps with no SOURCEMAP_BROKEN warning", () =>
851 Effect.gen(function* () {
852 const fs = yield* FileSystem.FileSystem;
853 const path = yield* Path.Path;
854 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-pure-sourcemap-" });
855
856 const fakePkgDir = path.join(root, "node_modules", "fake-effect");
857 yield* fs.makeDirectory(fakePkgDir, { recursive: true });
858 yield* fs.writeFileString(
859 path.join(fakePkgDir, "package.json"),
860 JSON.stringify({
861 name: "fake-effect",
862 version: "0.0.0",
863 type: "module",
864 sideEffects: false,
865 exports: { ".": "./index.js", "./decls": "./decls.js" },
866 }),
867 );
868 // One module with annotatable top-level calls (transformed) and
869 // one with only declarations (metadata-only result). Under the
870 // old implementation the latter returned untransformed code with
871 // no map, flooding the build with SOURCEMAP_BROKEN warnings.
872 yield* fs.writeFileString(
873 path.join(fakePkgDir, "index.js"),
874 [
875 `export * from "./decls.js";`,
876 `export const used = makeUsed();`,
877 `function makeUsed() { return "USED_MARKER"; }`,
878 ].join("\n"),
879 );
880 yield* fs.writeFileString(
881 path.join(fakePkgDir, "decls.js"),
882 `export function helper() { return "HELPER_MARKER"; }`,
883 );
884
885 const entry = path.join(root, "entry.js");
886 yield* fs.writeFileString(
887 entry,
888 [`import { used, helper } from "fake-effect";`, `console.log(used, helper());`].join("\n"),
889 );
890
891 const logs: RolldownLog[] = [];
892 const bundle = yield* Effect.tryPromise({
893 try: () =>
894 rolldown({
895 input: entry,
896 cwd: root,
897 plugins: [purePlugin({ packages: ["fake-effect"], replaceDefaults: true })],
898 treeshake: true,
899 onLog: (_level, log) => {
900 logs.push(log);
901 },
902 }),
903 catch: (cause) => cause,
904 });
905 const { output } = yield* Effect.tryPromise({
906 try: () => bundle.generate({ format: "esm", sourcemap: true }),
907 catch: (cause) => cause,
908 });
909 yield* Effect.tryPromise({ try: () => bundle.close(), catch: (cause) => cause });
910
911 expect(logs.map((log) => log.code)).not.toContain("SOURCEMAP_BROKEN");
912
913 const chunk = output.find((c) => c.type === "chunk");
914 expect(chunk).toBeDefined();
915 expect(chunk!.map).toBeTruthy();
916 expect(chunk!.map!.mappings.length).toBeGreaterThan(0);
917
918 yield* fs.remove(root, { recursive: true });
919 }).pipe(Effect.provide(NodeServices.layer)),
920 );
921 });
922
923 // Touch Bundle to ensure tree-shaking re-export ordering during type-check.
924 void Bundle;