The best way to control Claude Code, Codex and more from any computer or phone
| 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 Effect from "effect/Effect"; |
| 9 | import * as FileSystem from "effect/FileSystem"; |
| 10 | import * as HttpClient from "effect/http/HttpClient"; |
| 11 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 12 | import * as Path from "effect/Path"; |
| 13 | import { MinimumLogLevel } from "effect/References"; |
| 14 | import * as Schedule from "effect/Schedule"; |
| 15 | import * as Stream from "effect/Stream"; |
| 16 | import * as pathe from "pathe"; |
| 17 | import { cloneFixture } from "../Utils/Fixture.ts"; |
| 18 | import { expectUrlContains } from "../Utils/Http.ts"; |
| 19 | |
| 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", "sveltekit-app"); |
| 25 | const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp"); |
| 26 | |
| 27 | /** |
| 28 | * PUT a text body to `url`, retrying until the dev server serves 200. |
| 29 | * Kit's CSRF protection 403s form-like content types (`text/plain` |
| 30 | * included) on non-GET requests unless the `origin` header matches the |
| 31 | * site, so the site origin is sent explicitly. |
| 32 | */ |
| 33 | const putTextReady = (url: string, body: string) => |
| 34 | Effect.gen(function* () { |
| 35 | const client = yield* HttpClient.HttpClient; |
| 36 | yield* client |
| 37 | .execute( |
| 38 | HttpClientRequest.put(url).pipe( |
| 39 | HttpClientRequest.setHeaders({ origin: new URL(url).origin }), |
| 40 | HttpClientRequest.bodyText(body, "text/plain"), |
| 41 | ), |
| 42 | ) |
| 43 | .pipe( |
| 44 | Effect.flatMap((res) => |
| 45 | res.status === 200 ? Effect.void : Effect.fail(new Error(`PUT not ready: ${res.status}`)), |
| 46 | ), |
| 47 | Effect.retry({ |
| 48 | schedule: Schedule.min([ |
| 49 | Schedule.exponential("500 millis"), |
| 50 | Schedule.spaced("4 seconds"), |
| 51 | ]), |
| 52 | times: 15, |
| 53 | }), |
| 54 | ); |
| 55 | }); |
| 56 | |
| 57 | const fetchJsonReady = <T>(url: string) => |
| 58 | Effect.gen(function* () { |
| 59 | const client = yield* HttpClient.HttpClient; |
| 60 | return yield* client.get(url).pipe( |
| 61 | Effect.flatMap((res) => |
| 62 | res.status === 200 |
| 63 | ? Effect.flatMap(res.text, (body) => |
| 64 | Effect.try({ |
| 65 | try: () => JSON.parse(body) as T, |
| 66 | catch: () => new Error(`non-json body: ${body}`), |
| 67 | }), |
| 68 | ) |
| 69 | : Effect.fail(new Error(`dev server not ready: ${res.status}`)), |
| 70 | ), |
| 71 | Effect.retry({ |
| 72 | schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("4 seconds")]), |
| 73 | times: 15, |
| 74 | }), |
| 75 | ); |
| 76 | }); |
| 77 | |
| 78 | // Concurrent like the other Website suites: the kit dev server never |
| 79 | // chdirs (the kit-runtime realign plugin handles cwd != root), so |
| 80 | // nothing here mutates process-global state. |
| 81 | describe.concurrent( |
| 82 | "SvelteKit dev", |
| 83 | { tags: ["provider:cloudflare", "provider:cloudflare:website"] }, |
| 84 | () => { |
| 85 | test.provider( |
| 86 | "SvelteKit dev: local dev server renders SSR with platform.env bindings, local KV, and HMR", |
| 87 | (stack) => |
| 88 | Effect.gen(function* () { |
| 89 | yield* stack.destroy(); |
| 90 | |
| 91 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 92 | prefix: "alchemy-sveltekit-dev-", |
| 93 | tempRoot, |
| 94 | entries: ["package.json", "src", "static"], |
| 95 | }); |
| 96 | |
| 97 | const bindingMarker = "sveltekit-dev-binding-marker"; |
| 98 | |
| 99 | const { site, siteKv } = yield* stack.deploy( |
| 100 | Effect.gen(function* () { |
| 101 | // A locally-emulated KV namespace bound into `platform.env` — |
| 102 | // no cloud call runs for it in dev. |
| 103 | const siteKv = yield* Cloudflare.KV.Namespace("SiteKV"); |
| 104 | const site = yield* Cloudflare.Website.SvelteKit("SvelteKitLocal", { |
| 105 | rootDir, |
| 106 | dev: { port: 0 }, |
| 107 | memo: { include: ["src/**", "static/**", "package.json"] }, |
| 108 | env: { TEST_BINDING: bindingMarker, SITE_KV: siteKv }, |
| 109 | }); |
| 110 | return { site, siteKv }; |
| 111 | }), |
| 112 | ); |
| 113 | |
| 114 | // Local identity: the url points at the alchemy dev proxy — no |
| 115 | // cloud Worker exists — and the namespace id carries the `dev:` |
| 116 | // marker (proof no cloud call ran for it). |
| 117 | expect(site.url).toBeDefined(); |
| 118 | expect(site.url).toMatch(/^http:\/\/localhost:\d+/); |
| 119 | expect(isLocalId(siteKv.namespaceId)).toBe(true); |
| 120 | expect(siteKv.namespaceId).toMatch(/^dev:/); |
| 121 | |
| 122 | // SSR route: kit's own Vite dev server (Node SSR), with |
| 123 | // `platform.env` served by the cloudflare-runtime platform proxy |
| 124 | // and the literal env overlaid. |
| 125 | yield* expectUrlContains(`${site.url!}/`, `binding:${bindingMarker}`, { |
| 126 | timeout: "120 seconds", |
| 127 | label: "sveltekit dev SSR home with platform.env binding", |
| 128 | }); |
| 129 | |
| 130 | // API endpoint: node:crypto + platform.env through the dev server. |
| 131 | yield* expectUrlContains(`${site.url!}/api/hello`, `"binding":"${bindingMarker}"`, { |
| 132 | timeout: "60 seconds", |
| 133 | label: "sveltekit dev API route", |
| 134 | }); |
| 135 | |
| 136 | // Static asset from `static/`. |
| 137 | yield* expectUrlContains(`${site.url!}/robots.txt`, "User-agent", { |
| 138 | timeout: "60 seconds", |
| 139 | label: "sveltekit dev static asset", |
| 140 | }); |
| 141 | // The same file read by a server route through the `ASSETS` binding. |
| 142 | yield* expectUrlContains(`${site.url!}/api/asset`, "User-agent", { |
| 143 | timeout: "60 seconds", |
| 144 | label: "sveltekit ASSETS binding", |
| 145 | }); |
| 146 | |
| 147 | // ── local KV round-trip: the /api/kv routes write and read |
| 148 | // `platform.env.SITE_KV`, backed by the local simulator ───────────── |
| 149 | const kvValue = "sveltekit-dev-kv-value"; |
| 150 | yield* putTextReady(`${site.url!}/api/kv?key=greeting`, kvValue); |
| 151 | const kvRead = yield* fetchJsonReady<{ value: string | null }>( |
| 152 | `${site.url!}/api/kv?key=greeting`, |
| 153 | ); |
| 154 | expect(kvRead.value).toBe(kvValue); |
| 155 | |
| 156 | // ── HMR: edit the home route in place; kit's dev server hot-reloads |
| 157 | // and the dev URL serves the new markup without a redeploy ────────── |
| 158 | const fs = yield* FileSystem.FileSystem; |
| 159 | const path = yield* Path.Path; |
| 160 | const pagePath = path.join(rootDir, "src", "routes", "+page.svelte"); |
| 161 | const page = yield* fs.readFileString(pagePath); |
| 162 | yield* fs.writeFileString( |
| 163 | pagePath, |
| 164 | page.replace("SvelteKit SSR home", "SvelteKit SSR home v2-marker"), |
| 165 | ); |
| 166 | |
| 167 | // Bounded poll: expectUrlContains retries with a capped backoff and |
| 168 | // a hard total timeout. |
| 169 | yield* expectUrlContains(`${site.url!}/`, "v2-marker", { |
| 170 | timeout: "90 seconds", |
| 171 | label: "sveltekit dev HMR-updated home page", |
| 172 | }); |
| 173 | |
| 174 | // The KV binding survives the hot reload. |
| 175 | const kvReadAfterHmr = yield* fetchJsonReady<{ value: string | null }>( |
| 176 | `${site.url!}/api/kv?key=greeting`, |
| 177 | ); |
| 178 | expect(kvReadAfterHmr.value).toBe(kvValue); |
| 179 | |
| 180 | yield* stack.destroy(); |
| 181 | }).pipe(logLevel), |
| 182 | { tags: ["provider:cloudflare:kv", "local"], timeout: 300_000 }, |
| 183 | ); |
| 184 | |
| 185 | /** |
| 186 | * `Alchemy.remote()` opts the KV namespace OUT of local emulation: even |
| 187 | * under `alchemy dev` it is created on real Cloudflare and the dev |
| 188 | * server's `platform.env.SITE_KV` proxies to it remotely. Out-of-band |
| 189 | * reads through the cloud API prove the dev server's write landed in the |
| 190 | * real namespace, and destroy deletes it from the cloud (the state row is |
| 191 | * stamped live). |
| 192 | */ |
| 193 | test.provider( |
| 194 | "SvelteKit dev: Alchemy.remote() KV namespace runs live behind the dev server", |
| 195 | (stack) => |
| 196 | Effect.gen(function* () { |
| 197 | yield* stack.destroy(); |
| 198 | |
| 199 | const rootDir = yield* cloneFixture(fixtureDir, { |
| 200 | prefix: "alchemy-sveltekit-dev-remote-", |
| 201 | tempRoot, |
| 202 | entries: ["package.json", "src", "static"], |
| 203 | }); |
| 204 | |
| 205 | const { site, siteKv } = yield* stack.deploy( |
| 206 | Effect.gen(function* () { |
| 207 | const siteKv = yield* Cloudflare.KV.Namespace("RemoteSiteKV").pipe(Alchemy.remote()); |
| 208 | const site = yield* Cloudflare.Website.SvelteKit("SvelteKitLocalRemoteKV", { |
| 209 | rootDir, |
| 210 | dev: { port: 0 }, |
| 211 | memo: { include: ["src/**", "static/**", "package.json"] }, |
| 212 | env: { TEST_BINDING: "sveltekit-dev-remote-marker", SITE_KV: siteKv }, |
| 213 | }); |
| 214 | return { site, siteKv }; |
| 215 | }), |
| 216 | ); |
| 217 | |
| 218 | // The remote() namespace is REAL — a cloud id, not a `dev:` one — |
| 219 | // while the site itself still serves from the local dev proxy. |
| 220 | expect(site.url).toMatch(/^http:\/\/localhost:\d+/); |
| 221 | expect(isLocalId(siteKv.namespaceId)).toBe(false); |
| 222 | expect(siteKv.namespaceId).not.toMatch(/^dev:/); |
| 223 | |
| 224 | // Write through the dev server's remote-proxied binding. |
| 225 | const kvValue = "sveltekit-dev-remote-kv-value"; |
| 226 | yield* putTextReady(`${site.url!}/api/kv?key=remote-key`, kvValue); |
| 227 | const kvRead = yield* fetchJsonReady<{ value: string | null }>( |
| 228 | `${site.url!}/api/kv?key=remote-key`, |
| 229 | ); |
| 230 | expect(kvRead.value).toBe(kvValue); |
| 231 | |
| 232 | // Out-of-band: the write is visible through the cloud API — the |
| 233 | // binding really hit the live namespace. |
| 234 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 235 | const cloudValue = yield* kv |
| 236 | .getNamespaceValue({ |
| 237 | accountId, |
| 238 | namespaceId: siteKv.namespaceId, |
| 239 | keyName: "remote-key", |
| 240 | }) |
| 241 | .pipe( |
| 242 | Effect.flatMap((res) => |
| 243 | Effect.tryPromise(() => |
| 244 | new Response(Stream.toReadableStream(res.body) as BodyInit).text(), |
| 245 | ), |
| 246 | ), |
| 247 | Effect.retry({ schedule: Schedule.exponential("1 second", 1.5), times: 5 }), |
| 248 | ); |
| 249 | expect(cloudValue).toBe(kvValue); |
| 250 | |
| 251 | yield* stack.destroy(); |
| 252 | |
| 253 | // The live namespace was deleted from the cloud on destroy (its |
| 254 | // state row is stamped live, so the live provider handles the |
| 255 | // delete even in a dev run). |
| 256 | const gone = yield* kv.getNamespace({ accountId, namespaceId: siteKv.namespaceId }).pipe( |
| 257 | Effect.as(false), |
| 258 | Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)), |
| 259 | ); |
| 260 | expect(gone).toBe(true); |
| 261 | }).pipe(logLevel), |
| 262 | { tags: ["provider:cloudflare:kv", "live"], timeout: 300_000 }, |
| 263 | ); |
| 264 | |
| 265 | // ───────────────────────────────────────────────────────────────────── |
| 266 | // SPA fixture under `alchemy dev`: pages are `ssr = false`, so a deep |
| 267 | // link to a client route must serve the app shell (kit's Vite dev |
| 268 | // server renders app.html with no page markup), while `+server.ts` |
| 269 | // endpoints still execute server-side in the dev server with access to |
| 270 | // `platform.env`. |
| 271 | // ───────────────────────────────────────────────────────────────────── |
| 272 | |
| 273 | const spaFixtureDir = pathe.resolve(import.meta.dirname, "fixtures", "sveltekit-spa-app"); |
| 274 | |
| 275 | /** app.html marker in the SPA fixture — identifies the app shell. */ |
| 276 | const SPA_SHELL_MARKER = "sveltekit-spa-shell"; |
| 277 | |
| 278 | test.provider( |
| 279 | "SvelteKit dev: SPA deep links serve the app shell; server endpoints still run with platform.env bindings", |
| 280 | (stack) => |
| 281 | Effect.gen(function* () { |
| 282 | yield* stack.destroy(); |
| 283 | |
| 284 | const rootDir = yield* cloneFixture(spaFixtureDir, { |
| 285 | prefix: "alchemy-sveltekit-dev-spa-", |
| 286 | tempRoot, |
| 287 | entries: ["package.json", "src"], |
| 288 | }); |
| 289 | |
| 290 | const bindingMarker = "sveltekit-dev-spa-binding-marker"; |
| 291 | |
| 292 | const site = yield* stack.deploy( |
| 293 | Effect.gen(function* () { |
| 294 | return yield* Cloudflare.Website.SvelteKit("SvelteKitSpaLocal", { |
| 295 | rootDir, |
| 296 | dev: { port: 0 }, |
| 297 | memo: { include: ["src/**", "package.json"] }, |
| 298 | // Same props as the live SPA test — in dev the build-time |
| 299 | // fallback generation never runs (no build); kit's dev |
| 300 | // server serves the shell for `ssr = false` routes itself. |
| 301 | assets: { notFoundHandling: "single-page-application" }, |
| 302 | env: { TEST_BINDING: bindingMarker }, |
| 303 | }); |
| 304 | }), |
| 305 | ); |
| 306 | |
| 307 | // Local identity: the url points at the alchemy dev proxy — no |
| 308 | // cloud Worker exists. |
| 309 | expect(site.url).toBeDefined(); |
| 310 | expect(site.url).toMatch(/^http:\/\/localhost:\d+/); |
| 311 | |
| 312 | // (a) A deep link to a CLIENT route serves the app shell — the |
| 313 | // shell marker is present and the widget markup (which only ever |
| 314 | // renders in the browser) is absent. |
| 315 | const widgetsBody = yield* expectUrlContains(`${site.url!}/widgets`, SPA_SHELL_MARKER, { |
| 316 | timeout: "120 seconds", |
| 317 | label: "sveltekit dev SPA deep link serves the shell", |
| 318 | }); |
| 319 | expect(widgetsBody).not.toContain("sveltekit-spa-widgets"); |
| 320 | expect(widgetsBody).not.toContain("sprocket"); |
| 321 | |
| 322 | // (b) The server endpoint executes in the dev server with the |
| 323 | // binding overlaid on `platform.env`. |
| 324 | const widgets = yield* fetchJsonReady<{ |
| 325 | server: boolean; |
| 326 | message: string | null; |
| 327 | widgets: Array<{ id: string; name: string }>; |
| 328 | }>(`${site.url!}/api/widgets`); |
| 329 | expect(widgets.server).toBe(true); |
| 330 | expect(widgets.message).toBe(bindingMarker); |
| 331 | expect(widgets.widgets.map((w) => w.name)).toEqual(["sprocket", "flange", "grommet"]); |
| 332 | |
| 333 | yield* stack.destroy(); |
| 334 | }).pipe(logLevel), |
| 335 | { tags: ["local"], timeout: 300_000 }, |
| 336 | ); |
| 337 | }, |
| 338 | ); |