@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 592 lines 21.4 KB
Raw
1 import * as NodeFsPromises from "node:fs/promises";
2 import * as NodeOs from "node:os";
3 import * as NodePath from "node:path";
4 import { pathToFileURL } from "node:url";
5 /**
6 * Build-output / option parity with upstream `@astrojs/cloudflare` v14.1.3:
7 * zero-config sessions, `_redirects` generation, `_headers` immutable
8 * Cache-Control, `base !== "/"` handling, `injectTypes`, the unsupported
9 * upstream-option guard, and build-time env feeding.
10 */
11 import * as Effect from "effect/Effect";
12 import * as Redacted from "effect/Redacted";
13 import { afterEach, describe, expect, it } from "vitest";
14 import cloudflareTarget, {
15 distilledCloudflare,
16 usesCloudflareKVSessionDriver,
17 withDevSessionKv,
18 withPrerenderSessionKv,
19 type DistilledCloudflareOptions,
20 } from "../cloudflare.ts";
21 import { buildAssetsHeadersContent, headersFileHasCacheControlForPath } from "../headers.ts";
22 import { applyWorkerEnvToProcess } from "../source.ts";
23
24 const noopLogger = {
25 info: () => {},
26 warn: () => {},
27 error: () => {},
28 debug: () => {},
29 } as never;
30
31 interface CapturedSetup {
32 session?: {
33 driver?: {
34 entrypoint?: string | { toString(): string };
35 config?: Record<string, unknown>;
36 };
37 };
38 }
39
40 const runConfigSetup = (
41 options: DistilledCloudflareOptions | undefined,
42 command: "dev" | "build",
43 config: Record<string, unknown> = {},
44 ): CapturedSetup => {
45 const integration = distilledCloudflare(options);
46 let captured: CapturedSetup | undefined;
47 const hook = integration.hooks["astro:config:setup"];
48 if (!hook) throw new Error("astro:config:setup hook missing");
49 void hook({
50 command,
51 config: { vite: {}, image: {}, ...config },
52 updateConfig: (update: unknown) => {
53 captured = update as CapturedSetup;
54 return {} as never;
55 },
56 logger: noopLogger,
57 } as never);
58 if (!captured) throw new Error("updateConfig was not called");
59 return captured;
60 };
61
62 interface ConfigDoneContext {
63 config: {
64 base: string;
65 trailingSlash?: "always" | "never" | "ignore";
66 output?: string;
67 build: {
68 client: URL;
69 server: URL;
70 assets: string;
71 assetsPrefix?: string | undefined;
72 format?: string;
73 };
74 };
75 injected: Array<{ filename: string; content: string }>;
76 }
77
78 const makeConfigDoneContext = (root: string, base = "/"): ConfigDoneContext => ({
79 config: {
80 base,
81 trailingSlash: "ignore",
82 output: "server",
83 build: {
84 client: pathToFileURL(NodePath.join(root, "dist/client") + "/"),
85 server: pathToFileURL(NodePath.join(root, "dist/server") + "/"),
86 assets: "_astro",
87 assetsPrefix: undefined,
88 format: "directory",
89 },
90 },
91 injected: [],
92 });
93
94 const runConfigDone = (
95 integration: ReturnType<typeof distilledCloudflare>,
96 ctx: ConfigDoneContext,
97 buildOutput: "static" | "server" = "server",
98 ) => {
99 const hook = integration.hooks["astro:config:done"];
100 if (!hook) throw new Error("astro:config:done hook missing");
101 void hook({
102 config: ctx.config,
103 buildOutput,
104 setAdapter: () => {},
105 injectTypes: (injectedType: { filename: string; content: string }) => {
106 ctx.injected.push(injectedType);
107 return new URL("file:///dev/null");
108 },
109 } as never);
110 };
111
112 const runBuildDone = async (
113 integration: ReturnType<typeof distilledCloudflare>,
114 ctx: ConfigDoneContext,
115 routes: Array<Record<string, unknown>> = [],
116 root?: string,
117 ) => {
118 const routesHook = integration.hooks["astro:routes:resolved"];
119 if (!routesHook) throw new Error("astro:routes:resolved hook missing");
120 void routesHook({ routes } as never);
121 const hook = integration.hooks["astro:build:done"];
122 if (!hook) throw new Error("astro:build:done hook missing");
123 await hook({
124 dir: root ? pathToFileURL(NodePath.join(root, "dist") + "/") : new URL("file:///dev/null/"),
125 assets: new Map(),
126 pages: [],
127 logger: noopLogger,
128 } as never);
129 };
130
131 const tempDirs: Array<string> = [];
132 const makeTempRoot = async (): Promise<string> => {
133 const root = await NodeFsPromises.mkdtemp(
134 NodePath.join(NodeOs.tmpdir(), "distilled-astro-test-"),
135 );
136 tempDirs.push(root);
137 return root;
138 };
139
140 afterEach(async () => {
141 for (const dir of tempDirs.splice(0)) {
142 await NodeFsPromises.rm(dir, { recursive: true, force: true });
143 }
144 });
145
146 describe("zero-config sessions", () => {
147 it("defaults the session driver to Cloudflare KV when unset", () => {
148 const captured = runConfigSetup(undefined, "build");
149 expect(captured.session?.driver).toBeDefined();
150 expect(usesCloudflareKVSessionDriver(captured.session as never)).toBe(true);
151 expect(captured.session?.driver?.config).toMatchObject({
152 binding: "SESSION",
153 });
154 });
155
156 it("uses the configured sessionKVBindingName", () => {
157 const captured = runConfigSetup({ sessionKVBindingName: "MY_SESSION" }, "build");
158 expect(captured.session?.driver?.config).toMatchObject({
159 binding: "MY_SESSION",
160 });
161 });
162
163 it("leaves a user-configured driver untouched", () => {
164 const userSession = { driver: "redis" };
165 const captured = runConfigSetup(undefined, "build", {
166 session: userSession,
167 });
168 expect(captured.session).toBe(userSession);
169 });
170
171 it("sessions: false leaves the session config untouched", () => {
172 const captured = runConfigSetup({ sessions: false }, "build");
173 expect(captured.session).toBeUndefined();
174 });
175
176 it("usesCloudflareKVSessionDriver matches by name and entrypoint", () => {
177 expect(usesCloudflareKVSessionDriver(undefined)).toBe(false);
178 expect(usesCloudflareKVSessionDriver({})).toBe(false);
179 expect(usesCloudflareKVSessionDriver({ driver: "cloudflareKVBinding" })).toBe(true);
180 expect(usesCloudflareKVSessionDriver({ driver: "cloudflare-kv-binding" })).toBe(true);
181 expect(usesCloudflareKVSessionDriver({ driver: "redis" })).toBe(false);
182 expect(
183 usesCloudflareKVSessionDriver({
184 driver: { entrypoint: "unstorage/drivers/cloudflare-kv-binding" },
185 }),
186 ).toBe(true);
187 expect(
188 usesCloudflareKVSessionDriver({
189 driver: { entrypoint: "unstorage/drivers/redis" },
190 }),
191 ).toBe(false);
192 });
193
194 it("withDevSessionKv appends the local KV binding hook", () => {
195 const marker = Effect.succeed({ name: "OTHER", text: "x" }) as never;
196 const withExisting = withDevSessionKv(
197 { worker: { name: "w", bindings: [marker] } as never },
198 "SESSION",
199 );
200 expect(withExisting.worker?.name).toBe("w");
201 expect(withExisting.worker?.bindings).toHaveLength(2);
202 expect(withExisting.worker?.bindings?.[0]).toBe(marker);
203
204 const fromScratch = withDevSessionKv(undefined, "SESSION");
205 expect(fromScratch.worker?.bindings).toHaveLength(1);
206 });
207
208 it("withPrerenderSessionKv injects the local KV only when sessions need it", () => {
209 const injected = withPrerenderSessionKv(undefined, {
210 needsSessionKVBinding: true,
211 sessionDevKV: true,
212 binding: "SESSION",
213 });
214 expect(injected?.worker?.bindings).toHaveLength(1);
215
216 const optedOut = withPrerenderSessionKv(undefined, {
217 needsSessionKVBinding: true,
218 sessionDevKV: false,
219 binding: "SESSION",
220 });
221 expect(optedOut).toBeUndefined();
222
223 const noSessions = withPrerenderSessionKv(
224 { worker: { name: "w" } as never },
225 { needsSessionKVBinding: false, sessionDevKV: true, binding: "SESSION" },
226 );
227 expect(noSessions?.worker?.bindings).toBeUndefined();
228 });
229 });
230
231 describe("unsupported upstream options", () => {
232 it("rejects upstream adapter options with a clear error", () => {
233 expect(() => distilledCloudflare({ imageService: "compile" } as never)).toThrowError(
234 /unsupported @astrojs\/cloudflare option[\s\S]*imageService[\s\S]*passthrough/,
235 );
236 expect(() => distilledCloudflare({ configPath: "wrangler.json" } as never)).toThrowError(
237 /configPath/,
238 );
239 });
240
241 it("accepts the supported options", () => {
242 expect(() =>
243 distilledCloudflare({
244 sessions: false,
245 sessionDevKV: false,
246 sessionKVBindingName: "S",
247 }),
248 ).not.toThrow();
249 });
250 });
251
252 describe("astro:config:done", () => {
253 it("injects the cloudflare.d.ts types reference", async () => {
254 const root = await makeTempRoot();
255 const integration = distilledCloudflare();
256 const ctx = makeConfigDoneContext(root);
257 runConfigDone(integration, ctx);
258 expect(ctx.injected).toHaveLength(1);
259 expect(ctx.injected[0]?.filename).toBe("cloudflare.d.ts");
260 expect(ctx.injected[0]?.content).toContain("@alchemy.run/frontend-frameworks/astro/types.d.ts");
261 });
262
263 it("keeps build.client untouched for base '/'", async () => {
264 const root = await makeTempRoot();
265 const integration = distilledCloudflare();
266 const ctx = makeConfigDoneContext(root, "/");
267 const before = ctx.config.build.client.href;
268 runConfigDone(integration, ctx);
269 expect(ctx.config.build.client.href).toBe(before);
270 });
271
272 it("nests build.client under the base and reports the original directory", async () => {
273 const root = await makeTempRoot();
274 const reported: Array<string> = [];
275 const integration = distilledCloudflare({
276 onOriginalClientDir: (dir) => reported.push(dir),
277 });
278 const ctx = makeConfigDoneContext(root, "/docs");
279 const original = ctx.config.build.client.href;
280 runConfigDone(integration, ctx);
281 expect(ctx.config.build.client.href).toBe(new URL("./docs/", original).href);
282 expect(reported).toHaveLength(1);
283 expect(NodePath.resolve(reported[0]!)).toBe(NodePath.join(root, "dist/client"));
284 });
285 });
286
287 describe("astro:build:done", () => {
288 const redirectRoute = {
289 type: "redirect",
290 pattern: "/old-about",
291 pathname: "/old-about",
292 entrypoint: undefined,
293 redirect: "/about/",
294 segments: [[{ content: "old-about", dynamic: false, spread: false }]],
295 };
296
297 it("writes _redirects for redirect routes and injects immutable _headers", async () => {
298 const root = await makeTempRoot();
299 const clientDir = NodePath.join(root, "dist/client");
300 await NodeFsPromises.mkdir(clientDir, { recursive: true });
301 const integration = distilledCloudflare();
302 const ctx = makeConfigDoneContext(root);
303 runConfigDone(integration, ctx);
304 await runBuildDone(integration, ctx, [redirectRoute], root);
305
306 const redirects = await NodeFsPromises.readFile(
307 NodePath.join(clientDir, "_redirects"),
308 "utf-8",
309 );
310 expect(redirects).toContain("/old-about");
311 expect(redirects).toContain("/about/");
312 expect(redirects).toContain("301");
313
314 const headers = await NodeFsPromises.readFile(NodePath.join(clientDir, "_headers"), "utf-8");
315 expect(headers).toContain("/_astro/*");
316 expect(headers).toContain("Cache-Control: public, max-age=31536000, immutable");
317 });
318
319 it("appends redirects to an existing _redirects and preserves user _headers rules", async () => {
320 const root = await makeTempRoot();
321 const clientDir = NodePath.join(root, "dist/client");
322 await NodeFsPromises.mkdir(clientDir, { recursive: true });
323 await NodeFsPromises.writeFile(NodePath.join(clientDir, "_redirects"), "/legacy / 302\n");
324 await NodeFsPromises.writeFile(
325 NodePath.join(clientDir, "_headers"),
326 "/api/*\n X-Custom: yes\n",
327 );
328 const integration = distilledCloudflare();
329 const ctx = makeConfigDoneContext(root);
330 runConfigDone(integration, ctx);
331 await runBuildDone(integration, ctx, [redirectRoute], root);
332
333 const redirects = await NodeFsPromises.readFile(
334 NodePath.join(clientDir, "_redirects"),
335 "utf-8",
336 );
337 expect(redirects).toContain("/legacy / 302");
338 expect(redirects).toContain("/old-about");
339
340 const headers = await NodeFsPromises.readFile(NodePath.join(clientDir, "_headers"), "utf-8");
341 expect(headers).toContain("X-Custom: yes");
342 expect(headers).toContain("/_astro/*");
343 });
344
345 it("leaves _headers alone when a matching Cache-Control rule already exists", async () => {
346 const root = await makeTempRoot();
347 const clientDir = NodePath.join(root, "dist/client");
348 await NodeFsPromises.mkdir(clientDir, { recursive: true });
349 const existing = "/_astro/*\n Cache-Control: no-store\n";
350 await NodeFsPromises.writeFile(NodePath.join(clientDir, "_headers"), existing);
351 const integration = distilledCloudflare();
352 const ctx = makeConfigDoneContext(root);
353 runConfigDone(integration, ctx);
354 await runBuildDone(integration, ctx, [], root);
355 const headers = await NodeFsPromises.readFile(NodePath.join(clientDir, "_headers"), "utf-8");
356 expect(headers).toBe(existing);
357 });
358
359 it("skips the Cache-Control injection when assetsPrefix is set", async () => {
360 const root = await makeTempRoot();
361 const clientDir = NodePath.join(root, "dist/client");
362 await NodeFsPromises.mkdir(clientDir, { recursive: true });
363 const integration = distilledCloudflare();
364 const ctx = makeConfigDoneContext(root);
365 ctx.config.build.assetsPrefix = "https://cdn.example.com";
366 runConfigDone(integration, ctx);
367 await runBuildDone(integration, ctx, [], root);
368 await expect(
369 NodeFsPromises.readFile(NodePath.join(clientDir, "_headers"), "utf-8"),
370 ).rejects.toThrow();
371 });
372
373 it("with base !== '/', moves the special files up to the original client dir", async () => {
374 const root = await makeTempRoot();
375 const clientDir = NodePath.join(root, "dist/client");
376 const nestedDir = NodePath.join(clientDir, "docs");
377 await NodeFsPromises.mkdir(nestedDir, { recursive: true });
378 // Astro writes the special files into the (remapped) client dir.
379 await NodeFsPromises.writeFile(NodePath.join(nestedDir, "_redirects"), "/nested / 302\n");
380 await NodeFsPromises.writeFile(NodePath.join(nestedDir, ".assetsignore"), "secret.txt\n");
381 const integration = distilledCloudflare();
382 const ctx = makeConfigDoneContext(root, "/docs");
383 runConfigDone(integration, ctx);
384 await runBuildDone(integration, ctx, [], root);
385
386 const redirects = await NodeFsPromises.readFile(
387 NodePath.join(clientDir, "_redirects"),
388 "utf-8",
389 );
390 expect(redirects).toContain("/nested / 302");
391 const ignore = await NodeFsPromises.readFile(
392 NodePath.join(clientDir, ".assetsignore"),
393 "utf-8",
394 );
395 expect(ignore).toContain("secret.txt");
396 // The base-prefixed headers rule lands at the original client dir root.
397 const headers = await NodeFsPromises.readFile(NodePath.join(clientDir, "_headers"), "utf-8");
398 expect(headers).toContain("/docs/_astro/*");
399 });
400
401 it("with base !== '/', 404.html survives the client-dir nesting (stays under the base)", async () => {
402 const root = await makeTempRoot();
403 const clientDir = NodePath.join(root, "dist/client");
404 const nestedDir = NodePath.join(clientDir, "docs");
405 await NodeFsPromises.mkdir(nestedDir, { recursive: true });
406 // Astro writes the prerendered 404 page into the (remapped) client dir.
407 await NodeFsPromises.writeFile(NodePath.join(nestedDir, "404.html"), "<h1>not found</h1>");
408 const integration = distilledCloudflare();
409 const ctx = makeConfigDoneContext(root, "/docs");
410 runConfigDone(integration, ctx, "static");
411 await runBuildDone(integration, ctx, [], root);
412
413 // Only the asset-server special files move up; the 404 page stays nested
414 // under the base, where Cloudflare's `not_found_handling: "404-page"`
415 // nearest-parent lookup finds it for every in-base URL.
416 const nested404 = await NodeFsPromises.readFile(NodePath.join(nestedDir, "404.html"), "utf-8");
417 expect(nested404).toContain("not found");
418 });
419 });
420
421 describe("cloudflare target finish (base !== '/')", () => {
422 it("points clientDirectory back at the original client dir", async () => {
423 const root = await makeTempRoot();
424 const target = cloudflareTarget({});
425 const integration = target.integration();
426 const ctx = makeConfigDoneContext(root, "/docs");
427 runConfigDone(integration, ctx);
428 const nested = NodePath.join(root, "dist/client/docs");
429 const output = {
430 clientDirectory: nested,
431 serverModules: undefined,
432 externalWorkspaces: new Set<string>(),
433 };
434 const finished = await Effect.runPromise(
435 target.finish!(output as never, {
436 root,
437 framework: "astro",
438 }) as unknown as Effect.Effect<{
439 clientDirectory: string | undefined;
440 }>,
441 );
442 expect(finished.clientDirectory).toBe(NodePath.join(root, "dist/client"));
443 });
444
445 it("leaves the output untouched for base '/'", async () => {
446 const root = await makeTempRoot();
447 const target = cloudflareTarget({});
448 const integration = target.integration();
449 const ctx = makeConfigDoneContext(root, "/");
450 runConfigDone(integration, ctx);
451 const clientDirectory = NodePath.join(root, "dist/client");
452 const output = {
453 clientDirectory,
454 serverModules: undefined,
455 externalWorkspaces: new Set<string>(),
456 };
457 const finished = await Effect.runPromise(
458 target.finish!(output as never, {
459 root,
460 framework: "astro",
461 }) as unknown as Effect.Effect<{
462 clientDirectory: string | undefined;
463 }>,
464 );
465 expect(finished.clientDirectory).toBe(clientDirectory);
466 });
467
468 it("strips serverModules when the resolved buildOutput is static (assets-only)", async () => {
469 const root = await makeTempRoot();
470 const target = cloudflareTarget({});
471 const integration = target.integration();
472 const ctx = makeConfigDoneContext(root, "/");
473 runConfigDone(integration, ctx, "static");
474 const clientDirectory = NodePath.join(root, "dist/client");
475 const output = {
476 clientDirectory,
477 // Astro bundles an SSR entry even for a fully-static build (it drives
478 // prerendering); the finish pass must drop it from the deploy.
479 serverModules: [{ name: "entry.mjs", content: "export default {}" }],
480 externalWorkspaces: new Set<string>(),
481 };
482 const finished = await Effect.runPromise(
483 target.finish!(output as never, {
484 root,
485 framework: "astro",
486 }) as unknown as Effect.Effect<{
487 clientDirectory: string | undefined;
488 serverModules: unknown;
489 }>,
490 );
491 expect(finished.serverModules).toBeUndefined();
492 expect(finished.clientDirectory).toBe(clientDirectory);
493 });
494
495 it("static + base !== '/': assets-only AND clientDirectory back at the original dir", async () => {
496 const root = await makeTempRoot();
497 const target = cloudflareTarget({});
498 const integration = target.integration();
499 const ctx = makeConfigDoneContext(root, "/docs");
500 runConfigDone(integration, ctx, "static");
501 const nested = NodePath.join(root, "dist/client/docs");
502 const output = {
503 clientDirectory: nested,
504 serverModules: [{ name: "entry.mjs", content: "export default {}" }],
505 externalWorkspaces: new Set<string>(),
506 };
507 const finished = await Effect.runPromise(
508 target.finish!(output as never, {
509 root,
510 framework: "astro",
511 }) as unknown as Effect.Effect<{
512 clientDirectory: string | undefined;
513 serverModules: unknown;
514 }>,
515 );
516 expect(finished.serverModules).toBeUndefined();
517 expect(finished.clientDirectory).toBe(NodePath.join(root, "dist/client"));
518 });
519 });
520
521 describe("headers utility", () => {
522 it("detects existing Cache-Control rules (set and detach forms)", () => {
523 expect(
524 headersFileHasCacheControlForPath("/_astro/*\n Cache-Control: no-store\n", "/_astro/probe"),
525 ).toBe(true);
526 expect(
527 headersFileHasCacheControlForPath("/_astro/*\n ! Cache-Control\n", "/_astro/probe"),
528 ).toBe(true);
529 expect(
530 headersFileHasCacheControlForPath("/api/*\n Cache-Control: no-store\n", "/_astro/probe"),
531 ).toBe(false);
532 expect(headersFileHasCacheControlForPath("/_astro/*\n X-Custom: 1\n", "/_astro/probe")).toBe(
533 false,
534 );
535 expect(
536 headersFileHasCacheControlForPath(
537 "https://example.com/_astro/*\n Cache-Control: no-store\n",
538 "/_astro/probe",
539 ),
540 ).toBe(true);
541 expect(
542 headersFileHasCacheControlForPath("/:dir/file\n Cache-Control: x\n", "/_astro/file"),
543 ).toBe(true);
544 });
545
546 it("builds the immutable block, prepending it to existing content", async () => {
547 const fresh = await buildAssetsHeadersContent(
548 { assetsDir: "_astro", basePrefix: "", headersPath: "unused" },
549 async () => {
550 throw new Error("missing");
551 },
552 );
553 expect(fresh?.assetsPattern).toBe("/_astro/*");
554 expect(fresh?.content).toBe(
555 "/_astro/*\n Cache-Control: public, max-age=31536000, immutable\n",
556 );
557
558 const merged = await buildAssetsHeadersContent(
559 { assetsDir: "_astro", basePrefix: "/docs", headersPath: "unused" },
560 async () => "/api/*\n X-Custom: yes",
561 );
562 expect(merged?.assetsPattern).toBe("/docs/_astro/*");
563 expect(merged?.content).toContain("/docs/_astro/*\n Cache-Control:");
564 expect(merged?.content.endsWith("/api/*\n X-Custom: yes\n")).toBe(true);
565 });
566 });
567
568 describe("applyWorkerEnvToProcess", () => {
569 it("applies literal env values and skips non-literals", async () => {
570 const key = (suffix: string) => `DISTILLED_ASTRO_TEST_${suffix}`;
571 for (const suffix of ["STR", "SECRET", "NUM", "BOOL", "EFFECT"]) {
572 delete process.env[key(suffix)];
573 }
574 await Effect.runPromise(
575 applyWorkerEnvToProcess({
576 [key("STR")]: "plain",
577 [key("SECRET")]: Redacted.make("hidden"),
578 [key("NUM")]: 42,
579 [key("BOOL")]: true,
580 [key("EFFECT")]: Effect.succeed("nope"),
581 }),
582 );
583 expect(process.env[key("STR")]).toBe("plain");
584 expect(process.env[key("SECRET")]).toBe("hidden");
585 expect(process.env[key("NUM")]).toBe("42");
586 expect(process.env[key("BOOL")]).toBe("true");
587 expect(process.env[key("EFFECT")]).toBeUndefined();
588 for (const suffix of ["STR", "SECRET", "NUM", "BOOL"]) {
589 delete process.env[key(suffix)];
590 }
591 });
592 });