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

main
ts 342 lines 13.7 KB
Raw
1 import * as NodeNet from "node:net";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import { MinimumLogLevel } from "effect/References";
9 import * as pathe from "pathe";
10 import { cloneFixture } from "../Utils/Fixture.ts";
11 import { expectResponse, type ExpectedResponse } from "../Utils/Http.ts";
12 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
13
14 // Asset routing for `Website.Vite`, mirroring `@cloudflare/vite-plugin`'s
15 // `static-mpa`, `react-spa` and `spa-with-api` playgrounds. Each spec runs
16 // deployed and under `alchemy dev`, as the plugin runs each in build and dev
17 // mode; checks the plugin limits to one mode are limited the same way.
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20 const { test: devTest } = Test.make({ providers: Cloudflare.providers(), dev: true });
21
22 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
23 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
24
25 type Mode = "live" | "dev";
26 type Check = (url: string, mode: Mode) => Effect.Effect<void, unknown>;
27
28 interface Variant {
29 readonly fixture: string;
30 readonly entries: ReadonlyArray<string>;
31 readonly config?: string;
32 readonly main?: string;
33 readonly assets: Cloudflare.Website.ViteProps["assets"];
34 }
35
36 const deploySite = (stack: Test.ScratchStack, id: string, variant: Variant, mode: Mode) =>
37 Effect.gen(function* () {
38 const fs = yield* FileSystem.FileSystem;
39 const rootDir = yield* cloneFixture(pathe.resolve(import.meta.dirname, variant.fixture), {
40 prefix: `alchemy-${variant.fixture}-`,
41 tempRoot,
42 entries: [...variant.entries],
43 });
44 if (variant.config) {
45 yield* fs.copyFile(
46 pathe.join(rootDir, "configs", `${variant.config}.ts`),
47 pathe.join(rootDir, "vite.config.ts"),
48 );
49 }
50 yield* fs.remove(pathe.join(rootDir, "configs"), { recursive: true, force: true });
51 return yield* stack.deploy(
52 Cloudflare.Website.Vite(id, {
53 rootDir,
54 workersDev: true,
55 compatibility: { date: "2025-06-04", flags: ["nodejs_compat"] },
56 memo: { include: ["**/*"] },
57 main: variant.main,
58 assets: variant.assets,
59 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
60 }),
61 );
62 });
63
64 const routingTests = (
65 name: string,
66 id: string,
67 variant: Variant,
68 check: Check,
69 modes: ReadonlyArray<Mode> = ["live", "dev"],
70 ) => {
71 if (modes.includes("live")) {
72 test.provider(
73 name,
74 (stack) =>
75 Effect.gen(function* () {
76 const { accountId } = yield* yield* CloudflareEnvironment;
77 yield* stack.destroy();
78 const site = yield* deploySite(stack, id, variant, "live");
79 yield* expectWorkerExists(site.workerName, accountId);
80 yield* check(site.url!.replace(/\/$/, ""), "live");
81 yield* stack.destroy();
82 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
83 }).pipe(logLevel),
84 { tags: ["provider:cloudflare:worker", "live"], timeout: 360_000 },
85 );
86 }
87 if (modes.includes("dev")) {
88 devTest.provider(
89 `${name} (dev)`,
90 (stack) =>
91 Effect.gen(function* () {
92 yield* stack.destroy();
93 const site = yield* deploySite(stack, `${id}Dev`, variant, "dev");
94 yield* check(site.url!.replace(/\/$/, ""), "dev");
95 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
96 { tags: ["provider:cloudflare:worker", "local"], timeout: 120_000 },
97 );
98 }
99 };
100
101 // The response head as a browser reads it: repeated header lines joined with
102 // `, `. Read over a raw socket because Bun's HTTP clients keep only the last
103 // of repeated lines, which Node's dev server sends for an array value.
104 const rawHeaders = (url: string) =>
105 Effect.promise(
106 () =>
107 new Promise<Record<string, string>>((resolve, reject) => {
108 const { hostname, port, pathname } = new URL(url);
109 const socket = NodeNet.connect(Number(port), hostname, () =>
110 socket.write(
111 `GET ${pathname} HTTP/1.1\r\nHost: ${hostname}:${port}\r\nConnection: close\r\n\r\n`,
112 ),
113 );
114 let head = "";
115 socket.setEncoding("utf8");
116 socket.on("data", (chunk: string) => {
117 head += chunk;
118 const end = head.indexOf("\r\n\r\n");
119 if (end === -1) return;
120 socket.destroy();
121 const headers: Record<string, string> = {};
122 for (const line of head.slice(0, end).split("\r\n").slice(1)) {
123 const colon = line.indexOf(":");
124 const name = line.slice(0, colon).trim().toLowerCase();
125 const value = line.slice(colon + 1).trim();
126 headers[name] = headers[name] === undefined ? value : `${headers[name]}, ${value}`;
127 }
128 resolve(headers);
129 });
130 socket.on("error", reject);
131 }),
132 );
133
134 // A browser navigation; the plugin's specs use `page.goto` for these.
135 const navigate = { "sec-fetch-mode": "navigate", accept: "text/html" };
136
137 const expectBody = (url: string, marker: string, status = 200, headers?: Record<string, string>) =>
138 expectResponse(
139 url,
140 (res) =>
141 res.status !== status
142 ? `status ${res.status}, expected ${status}`
143 : res.body.includes(marker)
144 ? undefined
145 : `body without "${marker}"`,
146 { headers, label: `${url} → ${status} "${marker}"` },
147 );
148
149 const expectHeader = (
150 url: string,
151 header: string,
152 value: string | null,
153 headers?: Record<string, string>,
154 ) =>
155 expectResponse(
156 url,
157 (res) =>
158 res.headers.get(header) === value ? undefined : `${header}: ${res.headers.get(header)}`,
159 { headers, label: `${url} → ${header}: ${value}` },
160 );
161
162 const expectRedirect = (url: string, status: number, location: string) =>
163 expectResponse(
164 url,
165 (res: ExpectedResponse) => {
166 // Drop the helper's cache-busting query, which a redirect carries over.
167 const actual = res.headers.get("location")?.replace(/[?&]__alchemy_cb=\d+$/, "");
168 return res.status === status && actual === location ? undefined : `location ${actual}`;
169 },
170 { label: `${url} → ${status} ${location}` },
171 );
172
173 const expectJson = (url: string, headers?: Record<string, string>) =>
174 expectBody(url, '{"name":"Cloudflare"}', 200, headers);
175
176 describe.concurrent(
177 "Vite asset routing",
178 { tags: ["provider:cloudflare", "provider:cloudflare:website"] },
179 () => {
180 // `playground/static-mpa/__tests__/base-tests.ts`.
181 routingTests(
182 "Vite static MPA: pages, nested 404 pages, public HTML and _headers/_redirects",
183 "FixViteStaticMpa",
184 {
185 fixture: "vite-static-mpa-fixture",
186 entries: [
187 "package.json",
188 "vite.config.ts",
189 "index.html",
190 "404.html",
191 "contact.html",
192 "public-html.html",
193 "about",
194 "public",
195 ],
196 assets: { htmlHandling: "auto-trailing-slash", notFoundHandling: "404-page" },
197 },
198 (url, mode) =>
199 Effect.gen(function* () {
200 yield* expectBody(`${url}/`, "<h1>Home</h1>", 200, navigate);
201 yield* expectBody(`${url}/contact`, "<h1>Contact</h1>", 200, navigate);
202 // The canonical URL for a directory index has a trailing slash.
203 yield* expectRedirect(`${url}/about`, 307, "/about/");
204 yield* expectBody(`${url}/about/`, "<h1>About</h1>", 200, navigate);
205 yield* expectBody(`${url}/random-page`, "<h1>Root 404</h1>", 404, navigate);
206 yield* expectBody(`${url}/about/random-page`, "<h1>About 404</h1>", 404, navigate);
207 // `public/public-html.html` wins over the root `public-html.html`.
208 yield* expectBody(`${url}/public-html`, "<h1>Public Directory HTML</h1>", 200, navigate);
209 yield* expectBody(`${url}/public/public-html`, "<h1>Root 404</h1>", 404, navigate);
210 if (mode === "live") {
211 yield* expectHeader(`${url}/contact`, "x-header", "exact-header");
212 yield* expectHeader(`${url}/vite.svg`, "x-header", "splat-header");
213 yield* expectRedirect(`${url}/home`, 302, "/");
214 yield* expectRedirect(`${url}/contact/random-page`, 302, "/contact");
215 // A redirect wins over an asset at its `from` path.
216 yield* expectRedirect(`${url}/text-file.txt`, 302, "/");
217 }
218 }),
219 );
220
221 // `playground/react-spa/__tests__/react-spa.spec.ts`: `_headers` and
222 // `_redirects` apply once built; in dev (without the plugin's experimental
223 // support, which alchemy doesn't have) they don't.
224 routingTests(
225 "Vite SPA: not-found routes serve the app; _headers and _redirects apply once deployed",
226 "FixViteSpaHeaders",
227 {
228 fixture: "vite-spa-headers-fixture",
229 entries: ["package.json", "vite.config.ts", "configs", "index.html", "src", "public"],
230 assets: { notFoundHandling: "single-page-application" },
231 },
232 (url, mode) =>
233 Effect.gen(function* () {
234 yield* expectBody(`${url}/`, "<h1>Vite SPA</h1>", 200, navigate);
235 yield* expectBody(`${url}/random-page`, "<h1>Vite SPA</h1>", 200, navigate);
236 if (mode === "live") {
237 yield* expectHeader(`${url}/`, "x-header", "Custom-Value!!!");
238 yield* expectHeader(`${url}/vite.svg`, "x-header", "Custom-Value!!!");
239 yield* expectRedirect(`${url}/foo`, 302, "/bar");
240 yield* expectRedirect(`${url}/redirect.svg`, 302, "/target.svg");
241 yield* expectBody(`${url}/rewrite.svg`, "target.svg");
242 } else {
243 yield* expectHeader(`${url}/`, "x-header", null);
244 yield* expectHeader(`${url}/vite.svg`, "x-header", null);
245 }
246 }),
247 );
248
249 // `playground/react-spa/__tests__/server-headers` (dev only).
250 routingTests(
251 "Vite SPA: server.headers apply to HTML and asset responses",
252 "FixViteServerHeaders",
253 {
254 fixture: "vite-spa-headers-fixture",
255 entries: ["package.json", "vite.config.ts", "configs", "index.html", "src", "public"],
256 config: "server-headers",
257 assets: { notFoundHandling: "single-page-application" },
258 },
259 (url) =>
260 Effect.forEach(["/", "/vite.svg"], (path) =>
261 rawHeaders(`${url}${path}`).pipe(
262 Effect.tap((headers) =>
263 Effect.sync(() =>
264 expect({
265 string: headers["custom-string"],
266 array: headers["custom-string-array"],
267 number: headers["custom-number"],
268 }).toEqual({ string: "string-value", array: "one, two, three", number: "123" }),
269 ),
270 ),
271 ),
272 ),
273 ["dev"],
274 );
275
276 const spaApi = (config?: string, runWorkerFirst?: boolean | Array<string>): Variant => ({
277 fixture: "vite-spa-api-fixture",
278 entries: ["package.json", "vite.config.ts", "index.html", "src", "api", "public"],
279 config,
280 main: "./api/index.ts",
281 assets: { notFoundHandling: "single-page-application", runWorkerFirst },
282 });
283
284 // `playground/spa-with-api/__tests__/spa-with-api.spec.ts`.
285 routingTests(
286 "Vite SPA with API: navigations get the app, other requests reach the Worker",
287 "FixViteSpaApi",
288 spaApi(),
289 (url, mode) =>
290 Effect.gen(function* () {
291 yield* expectBody(`${url}/`, "<title>Vite SPA + API</title>", 200, navigate);
292 yield* expectHeader(`${url}/`, "is-worker-response", null, navigate);
293 yield* expectBody(`${url}/api/`, "<title>Vite SPA + API</title>", 200, navigate);
294 yield* expectJson(`${url}/api/`);
295 yield* expectBody(`${url}/foo`, "<title>Vite SPA + API</title>");
296 yield* expectHeader(`${url}/foo`, "is-worker-response", "true");
297 if (mode === "dev") {
298 yield* expectBody(`${url}/api/some-file.txt`, "Some file content.");
299 }
300 }),
301 );
302
303 // `playground/spa-with-api/__tests__/static-routing`.
304 routingTests(
305 "Vite SPA with API: runWorkerFirst rules route matching paths to the Worker",
306 "FixViteSpaApiStaticRouting",
307 spaApi(undefined, ["/api/*", "!/api/asset.txt"]),
308 (url, mode) =>
309 Effect.gen(function* () {
310 yield* expectHeader(`${url}/`, "is-worker-response", null, navigate);
311 yield* expectJson(`${url}/api/`, navigate);
312 yield* expectJson(`${url}/api/`);
313 yield* expectBody(`${url}/api/asset`, "Modified: Asset content.");
314 yield* expectBody(`${url}/foo`, "<title>Vite SPA + API</title>");
315 yield* expectHeader(`${url}/foo`, "is-worker-response", null);
316 if (mode === "dev") {
317 yield* expectBody(`${url}/api/asset.txt`, "Asset content.");
318 yield* expectJson(`${url}/api/some-file.txt`);
319 }
320 }),
321 );
322
323 // `playground/spa-with-api/__tests__/run-worker-first`.
324 routingTests(
325 "Vite SPA with API: runWorkerFirst true sends every request to the Worker",
326 "FixViteSpaApiRunWorkerFirst",
327 spaApi(undefined, true),
328 (url, mode) =>
329 Effect.gen(function* () {
330 yield* expectHeader(`${url}/`, "is-worker-response", "true", navigate);
331 yield* expectJson(`${url}/api/`, navigate);
332 yield* expectJson(`${url}/api/`);
333 yield* expectBody(`${url}/api/asset`, "Modified: Asset content.");
334 yield* expectHeader(`${url}/foo`, "is-worker-response", "true", navigate);
335 yield* expectHeader(`${url}/foo`, "is-worker-response", "true");
336 if (mode === "dev") {
337 yield* expectJson(`${url}/api/some-file.txt`);
338 }
339 }),
340 );
341 },
342 );