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

main
ts 191 lines 5.9 KB
Raw
1 import * as NodeFs from "node:fs/promises";
2 import * as NodeOs from "node:os";
3 import * as NodePath from "node:path";
4 import { cloudflare as officialCloudflare } from "@cloudflare/vite-plugin";
5 import * as vite from "vite";
6 import { afterAll, describe, expect, it } from "vitest";
7 import cloudflareVitePlugin from "../../plugin.ts";
8
9 // Differential conformance: the same project built with
10 // `@cloudflare/vite-plugin` and with Alchemy's plugin must produce the same
11 // output layout, which frameworks and deploy tooling read back.
12
13 const COMPATIBILITY_DATE = "2026-03-17";
14 const FLAGS = ["nodejs_compat"];
15
16 // Wrangler's deploy configuration, not part of the build output Alchemy reads.
17 const WRANGLER_OUTPUTS = new Set([".dev.vars", "wrangler.json", ".assetsignore"]);
18
19 const WORKER = [
20 `import { Buffer } from "node:buffer";`,
21 `import text from "./message.txt";`,
22 `export default {`,
23 ` async fetch() {`,
24 ` using _scope = { [Symbol.dispose]() {} };`,
25 ` const { lazy } = await import("./lazy.ts");`,
26 ` return new Response(Buffer.from(text + lazy).toString());`,
27 ` },`,
28 `};`,
29 ].join("\n");
30
31 const CLIENT = {
32 "index.html": `<!doctype html><html><body><script type="module" src="/src/client.ts"></script></body></html>`,
33 "src/client.ts": `import "./client.css"; console.log("client");`,
34 "src/client.css": `body { color: red; }`,
35 };
36
37 const WORKER_FILES = {
38 "src/index.ts": WORKER,
39 "src/lazy.ts": `export const lazy = "lazy";`,
40 "src/message.txt": "hello",
41 };
42
43 interface Shape {
44 name: string;
45 files: Record<string, string>;
46 /** Whether the project has a Worker entry. */
47 worker: boolean;
48 }
49
50 const SHAPES: ReadonlyArray<Shape> = [
51 {
52 name: "a Worker and a client",
53 worker: true,
54 files: { ...WORKER_FILES, ...CLIENT, "public/robots.txt": "User-agent: *" },
55 },
56 {
57 name: "a Worker and public assets only",
58 worker: true,
59 files: { ...WORKER_FILES, "public/robots.txt": "User-agent: *" },
60 },
61 {
62 name: "a Worker importing an asset by URL",
63 worker: true,
64 files: {
65 ...WORKER_FILES,
66 "src/index.ts": `import logo from "./logo.svg?url";\nexport default { fetch: () => new Response(logo) };`,
67 "src/logo.svg": `<svg xmlns="http://www.w3.org/2000/svg"></svg>`,
68 },
69 },
70 { name: "a Worker only", worker: true, files: WORKER_FILES },
71 {
72 name: "assets only",
73 worker: false,
74 files: { ...CLIENT, "public/robots.txt": "User-agent: *" },
75 },
76 ];
77
78 const roots: Array<string> = [];
79
80 const project = async (files: Record<string, string>) => {
81 const root = await NodeFs.realpath(
82 await NodeFs.mkdtemp(NodePath.join(NodeOs.tmpdir(), "alchemy-vite-build-parity-")),
83 );
84 roots.push(root);
85 for (const [file, content] of Object.entries({
86 "package.json": JSON.stringify({ type: "module" }),
87 ...files,
88 })) {
89 await NodeFs.mkdir(NodePath.dirname(NodePath.join(root, file)), { recursive: true });
90 await NodeFs.writeFile(NodePath.join(root, file), content);
91 }
92 return root;
93 };
94
95 const build = async (root: string, plugins: vite.PluginOption) => {
96 const builder = await vite.createBuilder({
97 configFile: false,
98 root,
99 logLevel: "silent",
100 plugins: [plugins],
101 });
102 await builder.buildApp();
103 };
104
105 const official = (shape: Shape) =>
106 officialCloudflare({
107 viteEnvironment: { name: "ssr" },
108 inspectorPort: false,
109 persistState: false,
110 config: {
111 name: "worker",
112 ...(shape.worker ? { main: "./src/index.ts" } : {}),
113 compatibility_date: COMPATIBILITY_DATE,
114 compatibility_flags: FLAGS,
115 },
116 });
117
118 const alchemy = (shape: Shape) =>
119 cloudflareVitePlugin({
120 ...(shape.worker ? { main: "./src/index.ts" } : {}),
121 compatibilityDate: COMPATIBILITY_DATE,
122 compatibilityFlags: FLAGS,
123 });
124
125 /** Every output file, relative to `dist`, with content hashes normalized. */
126 const outputs = async (root: string) => {
127 const dist = NodePath.join(root, "dist");
128 const files = await NodeFs.readdir(dist, { recursive: true, withFileTypes: true }).catch(
129 () => [],
130 );
131 return files
132 .filter((file) => file.isFile() && !WRANGLER_OUTPUTS.has(file.name))
133 .map((file) =>
134 NodePath.relative(dist, NodePath.join(file.parentPath, file.name))
135 .replaceAll("\\", "/")
136 .replace(/-[\w-]{8}(?=\.)/g, "-[hash]"),
137 )
138 .sort();
139 };
140
141 // The exported names; the local bindings behind them are the bundler's.
142 const exportedNames = (root: string) =>
143 NodeFs.readFile(NodePath.join(root, "dist/ssr/index.js"), "utf8").then((code) =>
144 [...code.matchAll(/export\s*\{([^}]*)\}/g)]
145 .flatMap((match) => match[1]!.split(","))
146 .map((specifier) =>
147 specifier
148 .trim()
149 .split(/\s+as\s+/)
150 .at(-1),
151 )
152 .filter(Boolean)
153 .sort(),
154 );
155
156 afterAll(async () => {
157 await Promise.all(roots.map((root) => NodeFs.rm(root, { recursive: true, force: true })));
158 });
159
160 describe.each(SHAPES)("build output matches @cloudflare/vite-plugin for $name", (shape) => {
161 const built = (async () => {
162 const [officialRoot, alchemyRoot] = await Promise.all([
163 project(shape.files),
164 project(shape.files),
165 ]);
166 await build(officialRoot, official(shape));
167 await build(alchemyRoot, alchemy(shape));
168 return { officialRoot, alchemyRoot };
169 })();
170
171 it("emits the same files", async () => {
172 const { officialRoot, alchemyRoot } = await built;
173 expect(await outputs(alchemyRoot)).toEqual(await outputs(officialRoot));
174 }, 120_000);
175
176 it.skipIf(!shape.worker)(
177 "keeps the same entry chunk exports",
178 async () => {
179 const { officialRoot, alchemyRoot } = await built;
180 expect(await exportedNames(alchemyRoot)).toEqual(await exportedNames(officialRoot));
181 },
182 120_000,
183 );
184 });
185
186 it("keeps `using` declarations as written", async () => {
187 const root = await project(SHAPES[0]!.files);
188 await build(root, alchemy(SHAPES[0]!));
189 const code = await NodeFs.readFile(NodePath.join(root, "dist/ssr/index.js"), "utf8");
190 expect(code).toMatch(/\busing [\w$]+ =/);
191 }, 120_000);