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

main
ts 128 lines 5.25 KB
Raw
1 import * as NodeFs from "node:fs";
2 import * as NodeOs from "node:os";
3 import * as NodePath from "node:path";
4 import * as Effect from "effect/Effect";
5 import { afterAll, beforeAll, describe, expect, it } from "vitest";
6 import { bundleWorker, CREATE_REQUIRE_BANNER, WORKER_ENTRY_NAME } from "../Bundle.ts";
7
8 /**
9 * A synthetic `.open-next` output exercising the four final-bundle rules:
10 * relative imports that must be inlined (`middleware/handler.mjs`,
11 * `.build/durable-objects/*.js`), the dynamic server-handler import that must
12 * stay a lazy chunk, an absolute `?module`-suffixed `.wasm` import, a
13 * `cloudflare:*` external, and a CJS-style `require` of a node builtin.
14 */
15 const makeOpenNextFixture = (root: string) => {
16 const openNext = NodePath.join(root, ".open-next");
17 NodeFs.mkdirSync(NodePath.join(openNext, "middleware"), { recursive: true });
18 NodeFs.mkdirSync(NodePath.join(openNext, ".build", "durable-objects"), {
19 recursive: true,
20 });
21 NodeFs.mkdirSync(NodePath.join(openNext, "server-functions", "default"), {
22 recursive: true,
23 });
24
25 const wasmPath = NodePath.join(openNext, "server-functions", "default", "example.wasm");
26 // Minimal valid wasm header: "\0asm" + version 1.
27 NodeFs.writeFileSync(wasmPath, Buffer.from([0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
28
29 NodeFs.writeFileSync(
30 NodePath.join(openNext, WORKER_ENTRY_NAME),
31 [
32 `import { env } from "cloudflare:workers";`,
33 `import { handleMiddleware } from "./middleware/handler.mjs";`,
34 `export { DOQueueHandler } from "./.build/durable-objects/queue.js";`,
35 `export default {`,
36 ` async fetch(request) {`,
37 ` handleMiddleware(env);`,
38 ` const { default: handler } = await import("./server-functions/default/handler.mjs");`,
39 ` return handler(request);`,
40 ` },`,
41 `};`,
42 ].join("\n"),
43 );
44 NodeFs.writeFileSync(
45 NodePath.join(openNext, "middleware", "handler.mjs"),
46 `export const handleMiddleware = () => "MIDDLEWARE_MARKER";`,
47 );
48 NodeFs.writeFileSync(
49 NodePath.join(openNext, ".build", "durable-objects", "queue.js"),
50 `export class DOQueueHandler {}`,
51 );
52 NodeFs.writeFileSync(
53 NodePath.join(openNext, "server-functions", "default", "handler.mjs"),
54 [
55 // The absolute `?module` import OpenNext's setWranglerExternal leaves
56 // behind "for wrangler to bundle".
57 `import wasm from ${JSON.stringify(`${wasmPath}?module`)};`,
58 // CJS-converted Next server code requires node builtins dynamically.
59 `const pickRequire = () => require("fs");`,
60 `export default () => ["HANDLER_MARKER", wasm, pickRequire];`,
61 ].join("\n"),
62 );
63 return openNext;
64 };
65
66 describe("bundleWorker", () => {
67 const root = NodeFs.mkdtempSync(NodePath.join(NodeOs.tmpdir(), "distilled-nextjs-bundle-"));
68 const outDirectory = NodePath.join(root, "dist", "worker");
69 let files: Array<string> = [];
70
71 beforeAll(async () => {
72 const openNextDirectory = makeOpenNextFixture(root);
73 await Effect.runPromise(bundleWorker({ openNextDirectory, outDirectory }));
74 // Windows readdir yields backslash-separated relative paths; the
75 // assertions below match POSIX module-name shapes.
76 files = NodeFs.readdirSync(outDirectory, { recursive: true }).map((file) =>
77 String(file).replaceAll("\\", "/"),
78 );
79 });
80
81 afterAll(() => {
82 NodeFs.rmSync(root, { recursive: true, force: true });
83 });
84
85 const read = (name: string) => NodeFs.readFileSync(NodePath.join(outDirectory, name), "utf8");
86
87 it("emits the worker entry with the createRequire banner", () => {
88 expect(files).toContain(WORKER_ENTRY_NAME);
89 const entry = read(WORKER_ENTRY_NAME);
90 for (const line of CREATE_REQUIRE_BANNER.split("\n")) {
91 expect(entry).toContain(line);
92 }
93 // The `import.meta.url ?? "file:///"` fallback is load-bearing: workerd
94 // modules have an undefined import.meta.url.
95 expect(entry).toContain(`import.meta.url ?? "file:///"`);
96 });
97
98 it("inlines the middleware and durable-object imports into the entry", () => {
99 const entry = read(WORKER_ENTRY_NAME);
100 expect(entry).toContain("MIDDLEWARE_MARKER");
101 expect(entry).toContain("DOQueueHandler");
102 });
103
104 it("keeps the server handler a lazy chunk", () => {
105 const entry = read(WORKER_ENTRY_NAME);
106 expect(entry).not.toContain("HANDLER_MARKER");
107 const chunks = files.filter((file) => file.startsWith("chunks/") && file.endsWith(".js"));
108 expect(chunks.length).toBeGreaterThan(0);
109 expect(chunks.some((chunk) => read(chunk).includes("HANDLER_MARKER"))).toBe(true);
110 });
111
112 it("keeps cloudflare:* and node:* imports external", () => {
113 const entry = read(WORKER_ENTRY_NAME);
114 expect(entry).toContain(`"cloudflare:workers"`);
115 expect(entry).toContain(`"node:module"`);
116 });
117
118 it("copies ?module wasm imports out as .wasm files with relative imports", () => {
119 const wasmFiles = files.filter((file) => file.endsWith(".wasm"));
120 expect(wasmFiles.length).toBe(1);
121 const chunks = files.filter((file) => file.startsWith("chunks/") && file.endsWith(".js"));
122 const importer = chunks.find((chunk) => read(chunk).includes("HANDLER_MARKER"));
123 expect(importer).toBeDefined();
124 const content = read(importer!);
125 expect(content).not.toContain("?module");
126 expect(content).toContain(NodePath.basename(wasmFiles[0]!));
127 });
128 });