@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 1,028 lines 43.9 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as kv from "@distilled.cloud/cloudflare/kv";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Option from "effect/Option";
10 import * as Path from "effect/Path";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import * as Stream from "effect/Stream";
14 import * as pathe from "pathe";
15 import { cloneFixture } from "../Utils/Fixture.ts";
16 import { expectUrlContains, expectUrlRedirect } from "../Utils/Http.ts";
17 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
22
23 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures/astro-app");
24 const staticFixtureDir = pathe.resolve(import.meta.dirname, "fixtures/astro-static-app");
25
26 // Keep the temp clone under the alchemy package so the project root stays
27 // within the workspace (same constraint as the Vite tests) and so the
28 // fixture's `astro` dependency resolves by walking up to
29 // `packages/alchemy/node_modules`.
30 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
31
32 class SessionFetchFailed extends Data.TaggedError("SessionFetchFailed")<{
33 url: string;
34 message: string;
35 }> {}
36
37 /**
38 * Cookie-aware fetch for the session round-trip: returns the body plus
39 * the `astro-session` cookie pair from `set-cookie` (if any).
40 */
41 const fetchSession = (url: string, cookie?: string) =>
42 Effect.tryPromise({
43 try: async (signal) => {
44 const u = new URL(url);
45 u.searchParams.set("__alchemy_cb", String(Date.now()));
46 const res = await fetch(u, {
47 signal,
48 cache: "no-store",
49 headers: { "cache-control": "no-cache", accept: "*/*", ...(cookie ? { cookie } : {}) },
50 });
51 const body = await res.text();
52 const sessionCookie = res.headers.get("set-cookie")?.match(/astro-session=[^;,\s]+/)?.[0];
53 return { status: res.status, body, sessionCookie };
54 },
55 catch: (e) =>
56 new SessionFetchFailed({ url, message: e instanceof Error ? e.message : String(e) }),
57 });
58
59 class AstroResponseMismatch extends Data.TaggedError("AstroResponseMismatch")<{
60 url: string;
61 detail: string;
62 }> {
63 override get message() {
64 return `${this.url} :: ${this.detail}`;
65 }
66 }
67
68 const responseRetry = Effect.retry({
69 schedule: Schedule.min([Schedule.exponential("1 second", 1.5), Schedule.spaced("8 seconds")]),
70 times: 8,
71 });
72
73 /**
74 * Fetch the middleware-backed `/locals` page and assert the middleware ran
75 * in the SAME request that rendered the page: the `x-middleware: hit`
76 * header is present and the body renders the exact per-request id the
77 * middleware mirrored onto `x-request-id`.
78 */
79 const expectMiddlewareLocals = (url: string) =>
80 Effect.tryPromise({
81 try: async (signal) => {
82 const u = new URL(url);
83 u.searchParams.set("__alchemy_cb", String(Date.now()));
84 const res = await fetch(u, {
85 signal,
86 cache: "no-store",
87 headers: { "cache-control": "no-cache", accept: "*/*" },
88 });
89 return {
90 status: res.status,
91 body: await res.text(),
92 middleware: res.headers.get("x-middleware"),
93 requestId: res.headers.get("x-request-id"),
94 };
95 },
96 catch: (e) =>
97 new AstroResponseMismatch({ url, detail: e instanceof Error ? e.message : String(e) }),
98 }).pipe(
99 Effect.filterOrFail(
100 (r) =>
101 r.status === 200 &&
102 r.middleware === "hit" &&
103 r.requestId !== null &&
104 r.body.includes(`locals-request-id=${r.requestId}`),
105 (r) =>
106 new AstroResponseMismatch({
107 url,
108 detail: `${r.status} x-middleware=${r.middleware} x-request-id=${r.requestId} body=${r.body.slice(0, 200)}`,
109 }),
110 ),
111 responseRetry,
112 );
113
114 /**
115 * Fetch a hashed asset and assert it serves 200 with the immutable
116 * Cache-Control from the adapter-emitted `_headers`. Without the
117 * provider folding `_headers` into the PUT asset config the asset
118 * serves Cloudflare's default `public, max-age=0, must-revalidate`.
119 */
120 const expectImmutableAsset = (assetUrl: string) =>
121 Effect.tryPromise({
122 try: async (signal) => {
123 const u = new URL(assetUrl);
124 u.searchParams.set("__alchemy_cb", String(Date.now()));
125 const res = await fetch(u, {
126 signal,
127 cache: "no-store",
128 headers: { "cache-control": "no-cache", accept: "*/*" },
129 });
130 await res.arrayBuffer();
131 return { status: res.status, cacheControl: res.headers.get("cache-control") };
132 },
133 catch: (e) =>
134 new AstroResponseMismatch({
135 url: assetUrl,
136 detail: e instanceof Error ? e.message : String(e),
137 }),
138 }).pipe(
139 Effect.filterOrFail(
140 (r) => r.status === 200 && r.cacheControl === "public, max-age=31536000, immutable",
141 (r) =>
142 new AstroResponseMismatch({
143 url: assetUrl,
144 detail: `${r.status} cache-control: ${r.cacheControl}`,
145 }),
146 ),
147 responseRetry,
148 );
149
150 /** The exact payload `src/pages/api/binary.ts` serves. */
151 const BINARY_BYTES = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01, 0x02, 0x03];
152
153 /**
154 * Fetch the binary endpoint and assert the exact bytes and content type
155 * survive the round trip through the Worker.
156 */
157 const expectBinaryEndpoint = (url: string) =>
158 Effect.tryPromise({
159 try: async (signal) => {
160 const u = new URL(url);
161 u.searchParams.set("__alchemy_cb", String(Date.now()));
162 const res = await fetch(u, {
163 signal,
164 cache: "no-store",
165 headers: { "cache-control": "no-cache", accept: "*/*" },
166 });
167 return {
168 status: res.status,
169 contentType: res.headers.get("content-type"),
170 bytes: [...new Uint8Array(await res.arrayBuffer())],
171 };
172 },
173 catch: (e) =>
174 new AstroResponseMismatch({ url, detail: e instanceof Error ? e.message : String(e) }),
175 }).pipe(
176 Effect.filterOrFail(
177 (r) =>
178 r.status === 200 &&
179 r.contentType === "application/octet-stream" &&
180 r.bytes.length === BINARY_BYTES.length &&
181 r.bytes.every((b, i) => b === BINARY_BYTES[i]),
182 (r) =>
183 new AstroResponseMismatch({
184 url,
185 detail: `${r.status} ${r.contentType} bytes=[${r.bytes.join(",")}]`,
186 }),
187 ),
188 responseRetry,
189 );
190
191 /**
192 * POST the urlencoded feedback form and assert the server-rendered echo —
193 * pins that POSTs reach the Worker through the asset router.
194 */
195 const expectFormPostEcho = (url: string, message: string) =>
196 Effect.tryPromise({
197 try: async (signal) => {
198 const res = await fetch(url, {
199 signal,
200 method: "POST",
201 cache: "no-store",
202 body: new URLSearchParams({ message }),
203 headers: { "cache-control": "no-cache", accept: "*/*" },
204 });
205 return { status: res.status, body: await res.text() };
206 },
207 catch: (e) =>
208 new AstroResponseMismatch({ url, detail: e instanceof Error ? e.message : String(e) }),
209 }).pipe(
210 Effect.filterOrFail(
211 (r) => r.status === 200 && r.body.includes(`received: ${message}`),
212 (r) => new AstroResponseMismatch({ url, detail: `${r.status} ${r.body.slice(0, 240)}` }),
213 ),
214 responseRetry,
215 );
216
217 /**
218 * Round-trip a value through the fixture's `/api/kv` route (backed by the
219 * user-declared `SITE_KV` binding): PUT then GET until the read observes
220 * the write.
221 */
222 const kvRoundTrip = (base: string, key: string, value: string) =>
223 Effect.gen(function* () {
224 yield* Effect.tryPromise({
225 try: async (signal) => {
226 const res = await fetch(
227 `${base}/api/kv?key=${encodeURIComponent(key)}&value=${encodeURIComponent(value)}`,
228 { signal, method: "PUT", cache: "no-store" },
229 );
230 return { status: res.status, body: await res.text() };
231 },
232 catch: (e) =>
233 new AstroResponseMismatch({
234 url: `${base}/api/kv`,
235 detail: e instanceof Error ? e.message : String(e),
236 }),
237 }).pipe(
238 Effect.filterOrFail(
239 (r) => r.status === 200,
240 (r) =>
241 new AstroResponseMismatch({
242 url: `${base}/api/kv`,
243 detail: `PUT ${r.status} ${r.body.slice(0, 240)}`,
244 }),
245 ),
246 responseRetry,
247 );
248
249 // Read back through the binding, retrying through KV read lag.
250 yield* Effect.tryPromise({
251 try: async (signal) => {
252 const res = await fetch(
253 `${base}/api/kv?key=${encodeURIComponent(key)}&__alchemy_cb=${Date.now()}`,
254 { signal, cache: "no-store" },
255 );
256 return { status: res.status, body: await res.text() };
257 },
258 catch: (e) =>
259 new AstroResponseMismatch({
260 url: `${base}/api/kv`,
261 detail: e instanceof Error ? e.message : String(e),
262 }),
263 }).pipe(
264 Effect.filterOrFail(
265 (r) => r.status === 200 && r.body.includes(`"value":"${value}"`),
266 (r) =>
267 new AstroResponseMismatch({
268 url: `${base}/api/kv`,
269 detail: `GET ${r.status} ${r.body.slice(0, 240)}`,
270 }),
271 ),
272 responseRetry,
273 );
274 });
275
276 class NamespaceStillExists extends Data.TaggedError("NamespaceStillExists") {}
277
278 const waitForNamespaceToBeDeleted = Effect.fn(function* (namespaceId: string, accountId: string) {
279 yield* kv.getNamespace({ accountId, namespaceId }).pipe(
280 Effect.flatMap(() => Effect.fail(new NamespaceStillExists())),
281 Effect.retry({
282 while: (e): e is NamespaceStillExists => e instanceof NamespaceStillExists,
283 schedule: Schedule.min([Schedule.exponential(250), Schedule.spaced("2 seconds")]),
284 times: 10,
285 }),
286 Effect.catchTag("NamespaceNotFound", () => Effect.void),
287 );
288 });
289
290 // Tests are independent (per-test scratch stacks, private fixture clones),
291 // so run them concurrently; suites are sequential by default.
292 describe.concurrent(
293 "Astro",
294 {
295 tags: [
296 "provider:cloudflare",
297 "provider:cloudflare:website",
298 "provider:cloudflare:worker",
299 "live",
300 ],
301 },
302 () => {
303 test.provider(
304 "Astro: SSR + env binding + prerender + static assets deploy; unchanged sources memo-skip the rebuild",
305 (stack) =>
306 Effect.gen(function* () {
307 const { accountId } = yield* yield* CloudflareEnvironment;
308 const fs = yield* FileSystem.FileSystem;
309 const path = yield* Path.Path;
310
311 yield* stack.destroy();
312
313 const rootDir = yield* cloneFixture(fixtureDir, {
314 prefix: "alchemy-astro-",
315 tempRoot,
316 entries: ["astro.config.mjs", "package.json", "public", "src"],
317 });
318
319 // Restrict the input memo to fixture sources so the test isn't
320 // re-hashing the whole monorepo on every deploy. `workspaces: []`
321 // pins the hash to the fixture alone: auto-detection would fold in
322 // workspace-linked integration packages, whose trees can change
323 // between deploys (concurrent development in this repo), breaking
324 // the unchanged-rebuild memo assertion below. Workspace-aware
325 // memoization has its own dedicated test in Vite.test.ts.
326 const memo = {
327 include: ["src/**", "public/**", "package.json", "astro.config.mjs"],
328 workspaces: [],
329 };
330
331 // A random value is fine here — it is binding data, not a resource
332 // name — and it stays constant across this test's deploys so the
333 // metadata hash cannot mask a broken input-hash memo.
334 const marker = `astro-marker-${Date.now()}`;
335
336 const deploy = () =>
337 stack.deploy(
338 Effect.gen(function* () {
339 // A REAL user-declared KV namespace bound through `env` —
340 // distinct from the auto-provisioned session namespace. The
341 // fixture's `/api/kv` route reads/writes it via the runtime env.
342 const siteKv = yield* Cloudflare.KV.Namespace("SiteKV");
343 const site = yield* Cloudflare.Website.Astro("AstroSite", {
344 rootDir,
345 workersDev: { enabled: true, previewsEnabled: true },
346 // `nodejs_compat` deliberately omitted — the resource
347 // auto-injects it, and this deploy proves that path.
348 compatibility: { date: "2026-03-10" },
349 memo,
350 env: {
351 TEST_MARKER: marker,
352 SITE_KV: siteKv,
353 PUBLIC_SITE_MARKER: "ASTRO_PUBLIC_ENV_MARKER",
354 },
355 assets: { htmlHandling: "auto-trailing-slash", notFoundHandling: "none" },
356 });
357 // Resource creation dedupes by logical id, so this returns the
358 // session namespace the Astro resource auto-provisioned — a
359 // handle for the out-of-band lifecycle assertions below.
360 const sessions = yield* Cloudflare.KV.Namespace("AstroSiteSession");
361 return { site, sessions, siteKv };
362 }),
363 );
364
365 // ── deploy 1: build + serve ────────────────────────────────────────
366 const { site: site1, sessions, siteKv } = yield* deploy();
367 expect(site1.url).toBeDefined();
368 expect(site1.hash?.input).toBeDefined();
369 yield* expectWorkerExists(site1.workerName, accountId);
370
371 // SSR page rendered in the Worker, reading the env binding.
372 yield* expectUrlContains(`${site1.url!}/`, marker, {
373 timeout: "120 seconds",
374 label: "SSR page renders env binding",
375 });
376 // A declared public env value is inlined into a page prerendered
377 // at build time.
378 yield* expectUrlContains(`${site1.url!}/public-env/`, "ASTRO_PUBLIC_ENV_MARKER", {
379 timeout: "60 seconds",
380 label: "astro public env",
381 });
382 // Prerendered page served from static assets. Keep the body — the
383 // hashed-asset assertion below extracts the `/_astro/*.css` href.
384 const aboutBody = yield* expectUrlContains(`${site1.url!}/about/`, "prerendered-page", {
385 timeout: "60 seconds",
386 label: "prerendered page",
387 });
388 // Plain static asset from public/.
389 yield* expectUrlContains(`${site1.url!}/static.txt`, "astro-static-asset", {
390 timeout: "60 seconds",
391 label: "static asset",
392 });
393 // The same file read by a server route through the `ASSETS` binding.
394 yield* expectUrlContains(`${site1.url!}/api/asset`, "astro-static-asset", {
395 timeout: "60 seconds",
396 label: "ASSETS binding",
397 });
398
399 // ── sessions: the SESSION KV namespace is auto-provisioned and
400 // `Astro.session` round-trips through it ───────────────────────────
401 expect(sessions.namespaceId).toBeDefined();
402 const actualSessions = yield* kv.getNamespace({
403 accountId,
404 namespaceId: sessions.namespaceId,
405 });
406 expect(actualSessions.id).toEqual(sessions.namespaceId);
407
408 // Wait for the route to serve before the cookie round-trip.
409 yield* expectUrlContains(`${site1.url!}/session`, "session-count=", {
410 timeout: "60 seconds",
411 label: "session page",
412 });
413
414 // A single edge request can still 404 right after the readiness
415 // probe above succeeded (workers.dev colo inconsistency) — retry
416 // through it, bounded, before asserting on the body.
417 const first = yield* fetchSession(`${site1.url!}/session`).pipe(
418 Effect.filterOrFail(
419 (res) => res.status === 200,
420 (res) =>
421 new SessionFetchFailed({
422 url: `${site1.url!}/session`,
423 message: `expected 200, got ${res.status}: ${res.body.slice(0, 240)}`,
424 }),
425 ),
426 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 8 }),
427 );
428 expect(first.status).toBe(200);
429 expect(first.body).toContain("session-count=1");
430 expect(first.sessionCookie).toBeDefined();
431
432 // Replaying the session cookie must observe the previous request's
433 // KV write. Retry through KV's (brief, same-colo) read lag.
434 const second = yield* fetchSession(`${site1.url!}/session`, first.sessionCookie).pipe(
435 Effect.filterOrFail(
436 (res) => res.body.includes("session-count=2"),
437 (res) =>
438 new SessionFetchFailed({
439 url: `${site1.url!}/session`,
440 message: `expected session-count=2, got: ${res.body.slice(0, 240)}`,
441 }),
442 ),
443 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 8 }),
444 );
445 expect(second.body).toContain("session-count=2");
446
447 // ── middleware: locals + response-header mutation ──────────────────
448 yield* expectMiddlewareLocals(`${site1.url!}/locals`);
449
450 // ── config redirects flow through `_redirects` to the asset layer ──
451 yield* expectUrlRedirect(`${site1.url!}/old-about`, "/about/", {
452 status: 301,
453 timeout: "60 seconds",
454 label: "config redirect via _redirects",
455 });
456
457 // ── binary endpoint returns the exact bytes ────────────────────────
458 yield* expectBinaryEndpoint(`${site1.url!}/api/binary`);
459
460 // ── urlencoded form POST reaches the Worker through the asset
461 // router and re-renders with the echoed message ─────────────────────
462 yield* expectFormPostEcho(`${site1.url!}/feedback`, marker);
463
464 // ── user-declared KV binding: round-trip through the runtime env,
465 // then verify out-of-band that the write landed in the REAL
466 // namespace ────────────────────────────────────────────────────────
467 expect(siteKv.namespaceId).toBeDefined();
468 yield* kvRoundTrip(site1.url!, "astro-live-key", marker);
469 const observed = yield* kv
470 .getNamespaceValue({
471 accountId,
472 namespaceId: siteKv.namespaceId,
473 keyName: "astro-live-key",
474 })
475 .pipe(
476 Effect.flatMap((res) =>
477 Effect.tryPromise(() =>
478 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
479 ),
480 ),
481 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 8 }),
482 );
483 expect(observed).toBe(marker);
484
485 // ── hashed `/_astro/*` asset serves with the immutable Cache-Control
486 // from the adapter-emitted `_headers` — pins the WorkerProvider
487 // folding a source build's `_headers`/`_redirects` into the PUT
488 // asset config (source providers hash the files but don't pre-merge
489 // them into `config`; only alchemy's own `readAssets` does). Without
490 // that merge the asset serves Cloudflare's default
491 // `public, max-age=0, must-revalidate`. ───────────────────────────
492 const assetHref = aboutBody.match(/\/_astro\/[^"']+\.css/)?.[0];
493 expect(assetHref).toBeDefined();
494 const assetUrl = `${site1.url!}${assetHref!}`;
495 yield* expectImmutableAsset(assetUrl);
496
497 // ── deploy 2: nothing changed ⇒ memo hit (no rebuild) ──────────────
498 const { site: site2 } = yield* deploy();
499 expect(site2.hash?.input).toEqual(site1.hash?.input);
500 expect(site2.hash?.bundle).toEqual(site1.hash?.bundle);
501 expect(site2.hash?.assets).toEqual(site1.hash?.assets);
502
503 // The no-op redeploy takes the provider's hash-matched KEEP path,
504 // which rebuilds the asset config wholesale (no upload jwt). A
505 // regression there would silently wipe the `_headers`/`_redirects`
506 // rules on every no-op deploy — re-assert both still serve.
507 yield* expectImmutableAsset(assetUrl);
508 yield* expectUrlRedirect(`${site1.url!}/old-about`, "/about/", {
509 status: 301,
510 timeout: "60 seconds",
511 label: "redirect after no-op keep-assets deploy",
512 });
513
514 // ── deploy 3: edit a page ⇒ memo busts, new content serves ─────────
515 const indexPath = path.join(rootDir, "src/pages/index.astro");
516 const source = yield* fs.readFileString(indexPath);
517 yield* fs.writeFileString(
518 indexPath,
519 source.replace("Astro Fixture", "Astro Fixture Edited"),
520 );
521
522 const { site: site3 } = yield* deploy();
523 expect(site3.hash?.input).toBeDefined();
524 expect(site3.hash?.input).not.toEqual(site1.hash?.input);
525 yield* expectUrlContains(`${site3.url!}/`, "Astro Fixture Edited", {
526 timeout: "60 seconds",
527 label: "edited SSR page",
528 });
529
530 yield* stack.destroy();
531 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
532
533 // Destroy must also clean up the auto-provisioned session namespace
534 // and the user-declared SITE_KV namespace.
535 yield* waitForNamespaceToBeDeleted(sessions.namespaceId, accountId);
536 yield* waitForNamespaceToBeDeleted(siteKv.namespaceId, accountId);
537 }).pipe(logLevel),
538 { tags: ["provider:cloudflare:kv"], timeout: 420_000 },
539 );
540
541 class NotFoundPageMismatch extends Data.TaggedError("NotFoundPageMismatch")<{
542 url: string;
543 actual: string;
544 }> {}
545
546 /**
547 * Assert `url` answers a REAL `404` whose body contains `marker` — the
548 * built `404.html` served by the asset layer (`notFoundHandling:
549 * "404-page"`), not a worker-rendered page and not Cloudflare's
550 * placeholder. Retries through edge propagation like `expectUrlContains`
551 * (which can't be used here: it requires `res.ok`).
552 */
553 const expectNotFoundPage = (url: string, marker: string) =>
554 Effect.tryPromise({
555 try: async (signal) => {
556 const u = new URL(url);
557 u.searchParams.set("__alchemy_cb", String(Date.now()));
558 const res = await fetch(u, {
559 signal,
560 cache: "no-store",
561 headers: { "cache-control": "no-cache", accept: "*/*" },
562 });
563 const body = await res.text();
564 return { status: res.status, body };
565 },
566 catch: (e) =>
567 new NotFoundPageMismatch({ url, actual: e instanceof Error ? e.message : String(e) }),
568 }).pipe(
569 Effect.filterOrFail(
570 (res) => res.status === 404 && res.body.includes(marker),
571 (res) =>
572 new NotFoundPageMismatch({ url, actual: `${res.status} ${res.body.slice(0, 240)}` }),
573 ),
574 Effect.retry({
575 schedule: Schedule.max([
576 Schedule.min([Schedule.exponential("750 millis", 1.5), Schedule.spaced("8 seconds")]),
577 Schedule.recurs(15),
578 ]),
579 }),
580 );
581
582 // ─────────────────────────────────────────────────────────────────────
583 // Assets-only deploys (seam: SourceBuildOutput.bundle === undefined)
584 //
585 // A declared `output: "static"` project prerenders every page,
586 // so the astro source's build produces NO server modules — the source
587 // path must flow `bundle: undefined` into the WorkerProvider's
588 // assets-only mode: the script PUT carries no modules and no main_module,
589 // and Cloudflare's asset layer answers every request (including the built
590 // 404.html via `errorPage: "404.html"`). Session auto-provisioning
591 // is skipped — no Worker code could ever read the namespace.
592 // ─────────────────────────────────────────────────────────────────────
593
594 test.provider(
595 "Astro: output 'static' deploys assets-only — no server bundle, 404.html from assets, memoized rebuilds",
596 (stack) =>
597 Effect.gen(function* () {
598 const { accountId } = yield* yield* CloudflareEnvironment;
599 const fs = yield* FileSystem.FileSystem;
600 const path = yield* Path.Path;
601
602 yield* stack.destroy();
603
604 const rootDir = yield* cloneFixture(staticFixtureDir, {
605 prefix: "alchemy-astro-static-",
606 tempRoot,
607 entries: ["package.json", "public", "src"],
608 });
609
610 // Same discipline as the SSR test above: pin the input hash to the
611 // fixture so concurrent development in this repo can't bust the
612 // unchanged-rebuild memo assertion.
613 const memo = { include: ["src/**", "public/**", "package.json"], workspaces: [] };
614
615 const deploy = () =>
616 stack.deploy(
617 Effect.gen(function* () {
618 return yield* Cloudflare.Website.Astro("AstroStaticSite", {
619 rootDir,
620 workersDev: { enabled: true, previewsEnabled: true },
621 compatibility: { date: "2026-03-10" },
622 memo,
623 astro: { output: "static" },
624 assets: { notFoundHandling: "404-page" },
625 });
626 }),
627 );
628
629 // ── deploy 1: build + assets-only serve ────────────────────────────
630 const site1 = yield* deploy();
631 expect(site1.url).toBeDefined();
632 expect(site1.hash?.input).toBeDefined();
633 expect(site1.hash?.assets).toBeDefined();
634 // The contract under test: no server bundle was produced or
635 // uploaded — the bundle hash slot stays empty.
636 expect(site1.hash?.bundle).toBeUndefined();
637 yield* expectWorkerExists(site1.workerName, accountId);
638
639 // Every page serves from the asset layer.
640 yield* expectUrlContains(`${site1.url!}/`, "static-home", {
641 timeout: "120 seconds",
642 label: "static home page",
643 });
644 yield* expectUrlContains(`${site1.url!}/about/`, "static-about", {
645 timeout: "60 seconds",
646 label: "static about page",
647 });
648 yield* expectUrlContains(`${site1.url!}/static.txt`, "astro-static-public-asset", {
649 timeout: "60 seconds",
650 label: "public asset",
651 });
652
653 // Unknown routes get the BUILT 404.html with a real 404 status —
654 // Cloudflare's asset layer applies `notFoundHandling` itself; no
655 // Worker script is involved.
656 yield* expectNotFoundPage(`${site1.url!}/definitely-not-a-page`, "static-404");
657
658 // Session auto-provisioning is skipped for declared-static sites:
659 // no KV namespace titled for this stack's session id may exist.
660 // (Physical titles embed the logical id verbatim:
661 // `{stack}-AstroStaticSiteSession-{stage}-{suffix}`.)
662 const sessionNamespace = yield* kv.listNamespaces.items({ accountId }).pipe(
663 Stream.filter((ns) => ns.title.includes("AstroStaticSiteSession")),
664 Stream.runHead,
665 Effect.map(Option.getOrUndefined),
666 );
667 expect(sessionNamespace).toBeUndefined();
668
669 // ── deploy 2: nothing changed ⇒ memo hit, still assets-only ────────
670 const site2 = yield* deploy();
671 expect(site2.hash?.input).toEqual(site1.hash?.input);
672 expect(site2.hash?.assets).toEqual(site1.hash?.assets);
673 expect(site2.hash?.bundle).toBeUndefined();
674 expect(site2.url).toBe(site1.url);
675
676 // ── deploy 3: edit a page ⇒ memo busts, new content serves,
677 // and the deploy REMAINS assets-only ───────────────────────────────
678 const indexPath = path.join(rootDir, "src/pages/index.astro");
679 const source = yield* fs.readFileString(indexPath);
680 yield* fs.writeFileString(indexPath, source.replace("static-home", "static-home-v2"));
681
682 const site3 = yield* deploy();
683 expect(site3.hash?.input).toBeDefined();
684 expect(site3.hash?.input).not.toEqual(site1.hash?.input);
685 expect(site3.hash?.bundle).toBeUndefined();
686 yield* expectUrlContains(`${site3.url!}/`, "static-home-v2", {
687 timeout: "60 seconds",
688 label: "edited static home page",
689 });
690
691 yield* stack.destroy();
692 yield* waitForWorkerToBeDeleted(site1.workerName, accountId);
693 }).pipe(logLevel),
694 { tags: ["provider:cloudflare:kv"], timeout: 360_000 },
695 );
696
697 // ─────────────────────────────────────────────────────────────────────
698 // A file-level `output: "static"` is honored (#1765)
699 //
700 // With no `astro.output` prop, the project's own `astro.config.mjs`
701 // decides: an existing static site stays assets-only on its first
702 // deploy instead of silently gaining a Worker script and a session
703 // namespace.
704 // ─────────────────────────────────────────────────────────────────────
705
706 test.provider(
707 "Astro: a config-file output 'static' deploys assets-only without the astro.output prop",
708 (stack) =>
709 Effect.gen(function* () {
710 const { accountId } = yield* yield* CloudflareEnvironment;
711 const fs = yield* FileSystem.FileSystem;
712 const path = yield* Path.Path;
713
714 yield* stack.destroy();
715
716 const rootDir = yield* cloneFixture(staticFixtureDir, {
717 prefix: "alchemy-astro-static-config-",
718 tempRoot,
719 entries: ["package.json", "public", "src"],
720 });
721 yield* fs.writeFileString(
722 path.join(rootDir, "astro.config.mjs"),
723 'import { defineConfig } from "astro/config";\n\nexport default defineConfig({ output: "static" });\n',
724 );
725
726 const site = yield* stack.deploy(
727 Effect.gen(function* () {
728 return yield* Cloudflare.Website.Astro("AstroStaticConfigSite", {
729 rootDir,
730 workersDev: { enabled: true, previewsEnabled: true },
731 compatibility: { date: "2026-03-10" },
732 assets: { notFoundHandling: "404-page" },
733 });
734 }),
735 );
736
737 // No server bundle was produced or uploaded.
738 expect(site.hash?.assets).toBeDefined();
739 expect(site.hash?.bundle).toBeUndefined();
740 yield* expectWorkerExists(site.workerName, accountId);
741 yield* expectUrlContains(`${site.url!}/`, "static-home", {
742 timeout: "120 seconds",
743 label: "static home page",
744 });
745 yield* expectNotFoundPage(`${site.url!}/definitely-not-a-page`, "static-404");
746
747 // A static site never provisions the session namespace.
748 const sessionNamespace = yield* kv.listNamespaces.items({ accountId }).pipe(
749 Stream.filter((ns) => ns.title.includes("AstroStaticConfigSiteSession")),
750 Stream.runHead,
751 Effect.map(Option.getOrUndefined),
752 );
753 expect(sessionNamespace).toBeUndefined();
754
755 yield* stack.destroy();
756 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
757 }).pipe(logLevel),
758 { tags: ["provider:cloudflare:kv"], timeout: 240_000 },
759 );
760
761 // ─────────────────────────────────────────────────────────────────────
762 // SPA fallback: `assets.notFoundHandling: "single-page-application"`
763 //
764 // A client-routed static build: every real page is a prerendered asset,
765 // and a hard GET to any UNREGISTERED route must serve the app shell
766 // (`/index.html`) with a 200 so the client router can boot. The built
767 // `404.html` must NOT serve — SPA handling supersedes the 404 page.
768 // ─────────────────────────────────────────────────────────────────────
769
770 test.provider(
771 "Astro: SPA not-found handling serves the app shell for deep links",
772 (stack) =>
773 Effect.gen(function* () {
774 const { accountId } = yield* yield* CloudflareEnvironment;
775
776 yield* stack.destroy();
777
778 const rootDir = yield* cloneFixture(staticFixtureDir, {
779 prefix: "alchemy-astro-spa-",
780 tempRoot,
781 entries: ["package.json", "public", "src"],
782 });
783
784 const site = yield* stack.deploy(
785 Effect.gen(function* () {
786 return yield* Cloudflare.Website.Astro("AstroSpaSite", {
787 rootDir,
788 workersDev: { enabled: true, previewsEnabled: true },
789 compatibility: { date: "2026-03-10" },
790 memo: { include: ["src/**", "public/**", "package.json"], workspaces: [] },
791 astro: { output: "static" },
792 assets: { notFoundHandling: "single-page-application" },
793 });
794 }),
795 );
796
797 expect(site.url).toBeDefined();
798 // Fully-static SPA deploy: assets only, no server bundle.
799 expect(site.hash?.bundle).toBeUndefined();
800 yield* expectWorkerExists(site.workerName, accountId);
801
802 // The app shell itself serves at `/`.
803 yield* expectUrlContains(`${site.url!}/`, "static-home", {
804 timeout: "120 seconds",
805 label: "SPA shell at /",
806 });
807
808 // (a) A hard GET to a route that was never registered serves the
809 // shell (`index.html`) with a 200 — `expectUrlContains` requires
810 // `res.ok`, so a 404 status can't satisfy this. The built
811 // `404.html` must NOT leak through.
812 const deepLinkBody = yield* expectUrlContains(
813 `${site.url!}/spa/definitely/not/a/route`,
814 "static-home",
815 { timeout: "60 seconds", label: "deep link serves SPA shell" },
816 );
817 expect(deepLinkBody).not.toContain("static-404");
818
819 // (b) A real prerendered page still serves its own content, not
820 // the shell.
821 const aboutBody = yield* expectUrlContains(`${site.url!}/about/`, "static-about", {
822 timeout: "60 seconds",
823 label: "real page still serves",
824 });
825 expect(aboutBody).not.toContain("static-home");
826
827 // (c) A real static asset still serves normally.
828 yield* expectUrlContains(`${site.url!}/static.txt`, "astro-static-public-asset", {
829 timeout: "60 seconds",
830 label: "static asset with SPA handling",
831 });
832
833 yield* stack.destroy();
834 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
835 }).pipe(logLevel),
836 { timeout: 360_000 },
837 );
838
839 // ─────────────────────────────────────────────────────────────────────
840 // Custom worker entry (seam: AstroProps.main → the cloudflare target's
841 // `worker.main` → the vite plugin's entry). `main` points the deploy at
842 // the user's own module, which wraps Astro's handler and re-exports the
843 // `Counter` Durable Object class — DO classes must live on the deployed
844 // worker for their namespace bindings to resolve. Mirrors Waku's test.
845 // ─────────────────────────────────────────────────────────────────────
846
847 test.provider(
848 "Astro: main deploys a custom worker entry hosting a Durable Object",
849 (stack) =>
850 Effect.gen(function* () {
851 const { accountId } = yield* yield* CloudflareEnvironment;
852
853 yield* stack.destroy();
854
855 const rootDir = yield* cloneFixture(fixtureDir, {
856 prefix: "alchemy-astro-main-",
857 tempRoot,
858 entries: ["astro.config.mjs", "package.json", "public", "src"],
859 });
860
861 const site = yield* stack.deploy(
862 Effect.gen(function* () {
863 return yield* Cloudflare.Website.Astro("AstroMainSite", {
864 rootDir,
865 // The user's own worker entry: wraps Astro's handler and
866 // exports the Counter DO.
867 main: "src/worker-entry.ts",
868 compatibility: { date: "2026-03-10" },
869 memo: {
870 include: ["src/**", "public/**", "package.json", "astro.config.mjs"],
871 workspaces: [],
872 },
873 env: {
874 TEST_MARKER: "astro-main-marker",
875 COUNTER: Cloudflare.DurableObject("Counter", { className: "Counter" }),
876 },
877 });
878 }),
879 );
880
881 expect(site.url).toBeDefined();
882 yield* expectWorkerExists(site.workerName, accountId);
883
884 // The deployed entry is the USER module, not Astro's own entry.
885 yield* expectUrlContains(`${site.url!}/api/entry`, '"entry":"worker-entry"', {
886 timeout: "120 seconds",
887 label: "custom worker entry",
888 });
889
890 // The DO namespace is bound and state increments ACROSS requests.
891 const count = (body: string) => (JSON.parse(body) as { count: number }).count;
892 const first = count(
893 yield* expectUrlContains(`${site.url!}/api/counter/increment`, '"count"', {
894 timeout: "60 seconds",
895 label: "counter increment",
896 }),
897 );
898 const second = count(
899 yield* expectUrlContains(`${site.url!}/api/counter/increment`, '"count"', {
900 timeout: "60 seconds",
901 label: "counter increment",
902 }),
903 );
904 expect(second).toBe(first + 1);
905
906 // Wrapping Astro's handler keeps every Astro route working: the
907 // SSR page still renders and reads bindings, and the prerendered
908 // page and public asset still serve.
909 yield* expectUrlContains(`${site.url!}/`, "astro-main-marker", {
910 timeout: "60 seconds",
911 label: "SSR page through the custom entry",
912 });
913 yield* expectUrlContains(`${site.url!}/about/`, "prerendered-page", {
914 timeout: "60 seconds",
915 label: "prerendered page with custom entry",
916 });
917 yield* expectUrlContains(`${site.url!}/static.txt`, "astro-static-asset", {
918 timeout: "60 seconds",
919 label: "static asset with custom entry",
920 });
921
922 yield* stack.destroy();
923 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
924 }).pipe(logLevel),
925 { timeout: 360_000 },
926 );
927
928 // ─────────────────────────────────────────────────────────────────────
929 // Route caching (#2320): `cache: { provider: cacheCloudflare() }` turns
930 // on Workers Cache for the Worker, and `routeRules` decide what the edge
931 // caches. Each page stamps a fresh UUID per render, so a repeated body
932 // proves the edge served it without invoking the Worker; a route with
933 // no rule must render on every request (`no-store` default).
934 // ─────────────────────────────────────────────────────────────────────
935
936 test.provider(
937 "Astro: cacheCloudflare() route rules serve repeat requests from Workers Cache",
938 (stack) =>
939 Effect.gen(function* () {
940 const { accountId } = yield* yield* CloudflareEnvironment;
941 const fs = yield* FileSystem.FileSystem;
942 const path = yield* Path.Path;
943
944 yield* stack.destroy();
945
946 const rootDir = yield* cloneFixture(fixtureDir, {
947 prefix: "alchemy-astro-cache-",
948 tempRoot,
949 entries: ["package.json", "public", "src"],
950 });
951 yield* fs.writeFileString(
952 path.join(rootDir, "astro.config.mjs"),
953 [
954 'import { defineConfig } from "astro/config";',
955 'import { cacheCloudflare } from "@alchemy.run/frontend-frameworks/astro/cache";',
956 "",
957 "export default defineConfig({",
958 ' output: "server",',
959 " cache: { provider: cacheCloudflare() },",
960 ' routeRules: { "/cached": { maxAge: 300 } },',
961 "});",
962 "",
963 ].join("\n"),
964 );
965 const page = (name: string) =>
966 `---\nconst id = crypto.randomUUID();\n---\n<p>${name}:{id}</p>\n`;
967 yield* fs.writeFileString(path.join(rootDir, "src/pages/cached.astro"), page("cached"));
968 yield* fs.writeFileString(
969 path.join(rootDir, "src/pages/uncached.astro"),
970 page("uncached"),
971 );
972
973 const site = yield* stack.deploy(
974 Effect.gen(function* () {
975 return yield* Cloudflare.Website.Astro("AstroCacheSite", {
976 rootDir,
977 workersDev: { enabled: true, previewsEnabled: true },
978 compatibility: { date: "2026-03-10" },
979 memo: {
980 include: ["src/**", "public/**", "package.json", "astro.config.mjs"],
981 workspaces: [],
982 },
983 });
984 }),
985 );
986 expect(site.url).toBeDefined();
987 yield* expectWorkerExists(site.workerName, accountId);
988 yield* expectUrlContains(`${site.url!}/cached`, "cached:", {
989 timeout: "120 seconds",
990 label: "cached route propagation",
991 });
992
993 // Same URL every time (no cache-busting): the cache key must match.
994 const render = (route: string) =>
995 Effect.tryPromise(async (signal) => {
996 const res = await fetch(`${site.url!}/${route}`, { signal });
997 const body = await res.text();
998 return res.ok ? body.match(new RegExp(`${route}:([0-9a-f-]{36})`))?.[1] : undefined;
999 });
1000
1001 let previous: string | undefined;
1002 const hit = yield* render("cached").pipe(
1003 Effect.map((id) => {
1004 const isHit = id !== undefined && id === previous;
1005 if (id !== undefined) previous = id;
1006 return isHit;
1007 }),
1008 Effect.repeat({
1009 schedule: Schedule.spaced("2 seconds"),
1010 until: (isHit) => isHit,
1011 times: 20,
1012 }),
1013 );
1014 expect(hit).toBe(true);
1015
1016 const first = yield* render("uncached");
1017 const second = yield* render("uncached");
1018 expect(first).toBeDefined();
1019 expect(second).toBeDefined();
1020 expect(second).not.toBe(first);
1021
1022 yield* stack.destroy();
1023 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
1024 }).pipe(logLevel),
1025 { tags: ["provider:cloudflare:kv", "provider:cloudflare:cache"], timeout: 360_000 },
1026 );
1027 },
1028 );