@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 360 lines 14.6 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { isLocalId } from "@alchemy.run/cloudflare/LocalRuntime";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as kv from "@distilled.cloud/cloudflare/kv";
7 import * as Alchemy from "alchemy";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
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 } from "../Utils/Http.ts";
17
18 // `dev: true` runs local providers behind the RPC sidecar proxy by default,
19 // matching the process topology of the real `alchemy dev` command.
20 const { test } = Test.make({ providers: Cloudflare.providers(), dev: true });
21
22 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
23
24 const fixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "astro-app");
25 const staticFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "astro-static-app");
26 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
27
28 class DevResponseMismatch extends Data.TaggedError("DevResponseMismatch")<{
29 url: string;
30 detail: string;
31 }> {
32 override get message() {
33 return `${this.url} :: ${this.detail}`;
34 }
35 }
36
37 const devRetry = Effect.retry({
38 schedule: Schedule.min([Schedule.exponential("500 millis", 1.5), Schedule.spaced("4 seconds")]),
39 times: 10,
40 });
41
42 /**
43 * Cookie-aware fetch for the dev session round-trip: returns the body plus
44 * the `astro-session` cookie pair from `set-cookie` (if any).
45 */
46 const fetchSession = (url: string, cookie?: string) =>
47 Effect.tryPromise({
48 try: async (signal) => {
49 const res = await fetch(url, {
50 signal,
51 cache: "no-store",
52 headers: { "cache-control": "no-cache", accept: "*/*", ...(cookie ? { cookie } : {}) },
53 });
54 const body = await res.text();
55 const sessionCookie = res.headers.get("set-cookie")?.match(/astro-session=[^;,\s]+/)?.[0];
56 return { status: res.status, body, sessionCookie };
57 },
58 catch: (e) =>
59 new DevResponseMismatch({ url, detail: e instanceof Error ? e.message : String(e) }),
60 });
61
62 /**
63 * Fetch `url` and assert the exact `status` with a body containing
64 * `marker` — used for the dev 404 page, which `expectUrlContains` can't
65 * assert (it requires `res.ok`).
66 */
67 const expectStatusBody = (url: string, status: number, marker: string) =>
68 Effect.tryPromise({
69 try: async (signal) => {
70 const res = await fetch(url, {
71 signal,
72 cache: "no-store",
73 headers: { "cache-control": "no-cache", accept: "*/*" },
74 });
75 return { status: res.status, body: await res.text() };
76 },
77 catch: (e) =>
78 new DevResponseMismatch({ url, detail: e instanceof Error ? e.message : String(e) }),
79 }).pipe(
80 Effect.filterOrFail(
81 (r) => r.status === status && r.body.includes(marker),
82 (r) =>
83 new DevResponseMismatch({
84 url,
85 detail: `expected ${status} with "${marker}", got ${r.status} ${r.body.slice(0, 240)}`,
86 }),
87 ),
88 devRetry,
89 );
90
91 // Tests are independent (per-test scratch stacks, private fixture clones),
92 // so run them concurrently; suites are sequential by default.
93 describe.concurrent(
94 "Astro dev",
95 { tags: ["provider:cloudflare", "provider:cloudflare:website"] },
96 () => {
97 test.provider(
98 "Astro dev: local dev server renders SSR with bindings and local sessions",
99 (stack) =>
100 Effect.gen(function* () {
101 yield* stack.destroy();
102
103 const rootDir = yield* cloneFixture(fixtureDir, {
104 prefix: "alchemy-astro-dev-",
105 tempRoot,
106 entries: ["astro.config.mjs", "package.json", "public", "src"],
107 });
108
109 const marker = "astro-dev-marker";
110
111 const { site, sessions } = yield* stack.deploy(
112 Effect.gen(function* () {
113 const site = yield* Cloudflare.Website.Astro("AstroLocal", {
114 rootDir,
115 dev: { port: 0 },
116 memo: { include: ["src/**", "public/**", "astro.config.mjs", "package.json"] },
117 env: { TEST_MARKER: marker },
118 });
119 // Dedupes by logical id — a handle on the session namespace the
120 // Astro resource auto-provisioned, for the dev-identity assertion.
121 const sessions = yield* Cloudflare.KV.Namespace("AstroLocalSession");
122 return { site, sessions };
123 }),
124 );
125
126 // Local identity: the url points at the alchemy dev proxy — no
127 // cloud Worker exists.
128 expect(site.url).toBeDefined();
129 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
130
131 // The auto-provisioned session namespace is emulated locally — a
132 // `dev:` id is proof no cloud call ran.
133 expect(isLocalId(sessions.namespaceId)).toBe(true);
134
135 // SSR page rendered by astro's dev server (ssr environment runs
136 // in workerd behind the proxy) — reads the TEST_MARKER binding.
137 yield* expectUrlContains(`${site.url!}/`, marker, {
138 timeout: "120 seconds",
139 label: "astro dev SSR home with env binding",
140 });
141
142 // Prerendered route renders on demand in dev.
143 yield* expectUrlContains(`${site.url!}/about/`, "prerendered-page", {
144 timeout: "60 seconds",
145 label: "astro dev prerender route",
146 });
147
148 // Static asset from `public/` through the dev server.
149 yield* expectUrlContains(`${site.url!}/static.txt`, "astro-static-asset", {
150 timeout: "60 seconds",
151 label: "astro dev static asset",
152 });
153
154 // The same `public/` file read by a server route through the
155 // Worker's `ASSETS` binding.
156 yield* expectUrlContains(`${site.url!}/api/asset`, "astro-static-asset", {
157 timeout: "60 seconds",
158 label: "astro dev ASSETS binding",
159 });
160
161 // ── sessions round-trip against the LOCAL simulator ────────────────
162 const first = yield* fetchSession(`${site.url!}/session`).pipe(
163 Effect.filterOrFail(
164 (r) => r.status === 200 && r.body.includes("session-count=1"),
165 (r) =>
166 new DevResponseMismatch({
167 url: `${site.url!}/session`,
168 detail: `${r.status} ${r.body.slice(0, 240)}`,
169 }),
170 ),
171 devRetry,
172 );
173 expect(first.sessionCookie).toBeDefined();
174
175 const second = yield* fetchSession(`${site.url!}/session`, first.sessionCookie).pipe(
176 Effect.filterOrFail(
177 (r) => r.body.includes("session-count=2"),
178 (r) =>
179 new DevResponseMismatch({
180 url: `${site.url!}/session`,
181 detail: `expected session-count=2, got ${r.body.slice(0, 240)}`,
182 }),
183 ),
184 devRetry,
185 );
186 expect(second.body).toContain("session-count=2");
187
188 // Out-of-band: NO real cloud namespace was created for the
189 // auto-provisioned session KV. (Physical titles embed the logical id
190 // verbatim: `{stack}-AstroLocalSession-{stage}-{suffix}`.)
191 const { accountId } = yield* yield* CloudflareEnvironment;
192 const cloudNamespace = yield* kv.listNamespaces.items({ accountId }).pipe(
193 Stream.filter((ns) => ns.title.includes("AstroLocalSession")),
194 Stream.runHead,
195 Effect.map(Option.getOrUndefined),
196 );
197 expect(cloudNamespace).toBeUndefined();
198
199 yield* stack.destroy();
200 }).pipe(logLevel),
201 { tags: ["provider:cloudflare:kv", "live"], timeout: 300_000 },
202 );
203
204 // ─────────────────────────────────────────────────────────────────────
205 // Declared-static app in dev: `output: "static"` produces no
206 // server modules — the dev server must still answer every route from the
207 // assets-only dispatch, including the custom 404 page.
208 // ─────────────────────────────────────────────────────────────────────
209
210 test.provider(
211 "Astro dev: declared-static app serves pages and the 404 page assets-only",
212 (stack) =>
213 Effect.gen(function* () {
214 yield* stack.destroy();
215
216 const rootDir = yield* cloneFixture(staticFixtureDir, {
217 prefix: "alchemy-astro-static-dev-",
218 tempRoot,
219 entries: ["package.json", "public", "src"],
220 });
221
222 const site = yield* stack.deploy(
223 Effect.gen(function* () {
224 return yield* Cloudflare.Website.Astro("AstroStaticLocal", {
225 rootDir,
226 dev: { port: 0 },
227 memo: { include: ["src/**", "public/**", "package.json"] },
228 astro: { output: "static" },
229 assets: { notFoundHandling: "404-page" },
230 });
231 }),
232 );
233
234 expect(site.url).toBeDefined();
235 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
236
237 yield* expectUrlContains(`${site.url!}/`, "static-home", {
238 timeout: "120 seconds",
239 label: "astro dev static home",
240 });
241 yield* expectUrlContains(`${site.url!}/about/`, "static-about", {
242 timeout: "60 seconds",
243 label: "astro dev static about",
244 });
245 // Unknown routes serve the custom 404 page with a real 404 status.
246 yield* expectStatusBody(`${site.url!}/definitely-not-a-page`, 404, "static-404");
247
248 yield* stack.destroy();
249 }).pipe(logLevel),
250 { tags: ["local"], timeout: 300_000 },
251 );
252
253 // ─────────────────────────────────────────────────────────────────────
254 // `Alchemy.remote()` opt-out: the SITE_KV namespace runs LIVE even in a
255 // dev run — the local dev server's binding proxies to the real cloud
256 // namespace, and destroy deletes it from the cloud (stamped-mode delete).
257 // ─────────────────────────────────────────────────────────────────────
258
259 test.provider(
260 "Astro dev: Alchemy.remote() SITE_KV binds the real namespace from the local server",
261 (stack) =>
262 Effect.gen(function* () {
263 yield* stack.destroy();
264
265 const rootDir = yield* cloneFixture(fixtureDir, {
266 prefix: "alchemy-astro-remote-",
267 tempRoot,
268 entries: ["astro.config.mjs", "package.json", "public", "src"],
269 });
270
271 const marker = "astro-remote-marker";
272
273 const { site, liveKv } = yield* stack.deploy(
274 Effect.gen(function* () {
275 const liveKv = yield* Cloudflare.KV.Namespace("AstroRemoteSiteKV").pipe(
276 Alchemy.remote(),
277 );
278 const site = yield* Cloudflare.Website.Astro("AstroRemoteLocal", {
279 rootDir,
280 dev: { port: 0 },
281 memo: { include: ["src/**", "public/**", "astro.config.mjs", "package.json"] },
282 env: { TEST_MARKER: marker, SITE_KV: liveKv },
283 });
284 return { site, liveKv };
285 }),
286 );
287
288 // The site itself is local; the remote() namespace is REAL.
289 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
290 expect(isLocalId(liveKv.namespaceId)).toBe(false);
291
292 // Wait for the dev server before driving the binding.
293 yield* expectUrlContains(`${site.url!}/`, marker, {
294 timeout: "120 seconds",
295 label: "astro dev home (remote kv stack)",
296 });
297
298 // Write through the remote-proxied binding via the fixture's
299 // /api/kv route, then read it back through the same binding.
300 yield* Effect.tryPromise({
301 try: async (signal) => {
302 const res = await fetch(`${site.url!}/api/kv?key=remote-key&value=${marker}`, {
303 signal,
304 method: "PUT",
305 cache: "no-store",
306 });
307 return { status: res.status, body: await res.text() };
308 },
309 catch: (e) =>
310 new DevResponseMismatch({
311 url: `${site.url!}/api/kv`,
312 detail: e instanceof Error ? e.message : String(e),
313 }),
314 }).pipe(
315 Effect.filterOrFail(
316 (r) => r.status === 200,
317 (r) =>
318 new DevResponseMismatch({
319 url: `${site.url!}/api/kv`,
320 detail: `PUT ${r.status} ${r.body.slice(0, 240)}`,
321 }),
322 ),
323 devRetry,
324 );
325
326 yield* expectStatusBody(`${site.url!}/api/kv?key=remote-key`, 200, `"value":"${marker}"`);
327
328 // Out-of-band: the write landed in the REAL cloud namespace.
329 const { accountId } = yield* yield* CloudflareEnvironment;
330 const observed = yield* kv
331 .getNamespaceValue({
332 accountId,
333 namespaceId: liveKv.namespaceId,
334 keyName: "remote-key",
335 })
336 .pipe(
337 Effect.flatMap((res) =>
338 Effect.tryPromise(() =>
339 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
340 ),
341 ),
342 Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 8 }),
343 );
344 expect(observed).toBe(marker);
345
346 yield* stack.destroy();
347
348 // The live namespace was deleted from the cloud on destroy (its
349 // state row is stamped live, so the live provider handles the
350 // delete even in a dev run).
351 const gone = yield* kv.getNamespace({ accountId, namespaceId: liveKv.namespaceId }).pipe(
352 Effect.as(false),
353 Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)),
354 );
355 expect(gone).toBe(true);
356 }).pipe(logLevel),
357 { tags: ["provider:cloudflare:kv", "live"], timeout: 300_000 },
358 );
359 },
360 );