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

main
ts 286 lines 11.7 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 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", "nuxt-app");
25 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
26
27 const fixtureEntries = [".gitignore", "package.json", "nuxt.config.ts", "app", "server", "public"];
28
29 const memoInclude = ["app/**", "server/**", "public/**", "nuxt.config.ts", "package.json"];
30
31 // Tests are independent (per-test scratch stacks, private fixture clones),
32 // so run them concurrently; suites are sequential by default.
33 describe.concurrent(
34 "Nuxt dev",
35 { tags: ["provider:cloudflare", "provider:cloudflare:kv", "provider:cloudflare:website"] },
36 () => {
37 test.provider(
38 "Nuxt dev: local dev server renders SSR with event.context.cloudflare bindings",
39 (stack) =>
40 Effect.gen(function* () {
41 const fs = yield* FileSystem.FileSystem;
42 const path = yield* Path.Path;
43
44 yield* stack.destroy();
45
46 const rootDir = yield* cloneFixture(fixtureDir, {
47 prefix: "alchemy-nuxt-dev-",
48 tempRoot,
49 entries: fixtureEntries,
50 });
51
52 const bindingMarker = "nuxt-dev-binding-marker";
53
54 const deployed = yield* stack.deploy(
55 Effect.gen(function* () {
56 const siteKv = yield* Cloudflare.KV.Namespace("NuxtDevKV");
57 const site = yield* Cloudflare.Website.Nuxt("NuxtLocal", {
58 rootDir,
59 dev: { port: 0 },
60 memo: { include: memoInclude },
61 env: { TEST_BINDING: bindingMarker, SITE_KV: siteKv },
62 });
63 return { site, siteKv };
64 }),
65 );
66 const site = deployed.site;
67
68 // Local identity: the url points at the alchemy dev proxy — no
69 // cloud Worker exists — and the KV namespace is emulated (a `dev:`
70 // id, proof no cloud API call ran).
71 expect(site.url).toBeDefined();
72 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
73 expect(isLocalId(deployed.siteKv.namespaceId)).toBe(true);
74
75 // SSR page rendered by nitro's dev server behind the proxy.
76 yield* expectUrlContains(`${site.url!}/`, "NUXT_PAGE_MARKER", {
77 timeout: "120 seconds",
78 label: "nuxt dev SSR home page",
79 });
80
81 // The SSR page reads `event.context.cloudflare.env.TEST_BINDING` —
82 // the dev platform bridge reconstructs the runtime contract over
83 // the cloudflare-runtime platform proxy.
84 yield* expectUrlContains(`${site.url!}/`, `binding:${bindingMarker}`, {
85 timeout: "60 seconds",
86 label: "nuxt dev SSR page with event.context.cloudflare.env binding",
87 });
88
89 // API route through the same contract.
90 yield* expectUrlContains(`${site.url!}/api/hello`, "api-route-ok", {
91 timeout: "60 seconds",
92 label: "nuxt dev API route",
93 });
94 // A `public/` file read by a server route through the `ASSETS` binding.
95 yield* expectUrlContains(`${site.url!}/api/asset`, "User-agent", {
96 timeout: "60 seconds",
97 label: "nuxt dev ASSETS binding",
98 });
99
100 // KV binding round-trip against the local simulator, through the
101 // platform-proxy bridge (nitro dev worker thread → host workerd).
102 const put = yield* putJsonReady<{ put: boolean }>(
103 `${site.url!}/api/kv?key=dev-key&value=dev-value`,
104 );
105 expect(put.put).toBe(true);
106 const got = yield* fetchJsonReady<{ value: string | null }>(
107 `${site.url!}/api/kv?key=dev-key`,
108 );
109 expect(got.value).toBe("dev-value");
110
111 // ── HMR: edit an API route in place. The stack is NOT re-applied —
112 // nitro's dev rebuild must pick the change up and serve it through
113 // the same alchemy proxy ─────────────────────────────────────────
114 const helloPath = path.join(rootDir, "server/api/hello.ts");
115 const hello = yield* fs.readFileString(helloPath);
116 yield* fs.writeFileString(
117 helloPath,
118 hello.replace('marker: "api-route-ok"', 'marker: "api-route-v2"'),
119 );
120
121 // Bounded poll until nitro's dev rebuild serves the new marker.
122 yield* expectUrlContains(`${site.url!}/api/hello`, "api-route-v2", {
123 timeout: "90 seconds",
124 label: "nuxt dev API route after HMR edit",
125 });
126
127 // The binding bridge survived the dev-server reload: the KV binding
128 // still round-trips (old key readable, new write lands).
129 const stillThere = yield* fetchJsonReady<{ value: string | null }>(
130 `${site.url!}/api/kv?key=dev-key`,
131 );
132 expect(stillThere.value).toBe("dev-value");
133 const put2 = yield* putJsonReady<{ put: boolean }>(
134 `${site.url!}/api/kv?key=post-hmr-key&value=post-hmr-value`,
135 );
136 expect(put2.put).toBe(true);
137 const got2 = yield* fetchJsonReady<{ value: string | null }>(
138 `${site.url!}/api/kv?key=post-hmr-key`,
139 );
140 expect(got2.value).toBe("post-hmr-value");
141
142 yield* stack.destroy();
143 }).pipe(logLevel),
144 { tags: ["local"], timeout: 300_000 },
145 );
146
147 /**
148 * `Alchemy.remote()` opts the KV namespace OUT of local emulation: even
149 * under `alchemy dev` the namespace is created on real Cloudflare and the
150 * dev server's binding proxies to it remotely. Out-of-band reads through
151 * the cloud API prove the write landed in the real namespace, and destroy
152 * (with the state row stamped live) deletes it from the cloud.
153 *
154 * The dev platform proxy is hosted in the sidecar's runtime stack
155 * (`DevContext.runtimeContext` threaded through the framework dev bridge),
156 * which includes remote-bindings support — the proxy's internal layer is
157 * local-only by design.
158 */
159 test.provider(
160 "Nuxt dev: Alchemy.remote() KV namespace runs live behind the dev server",
161 (stack) =>
162 Effect.gen(function* () {
163 yield* stack.destroy();
164
165 const rootDir = yield* cloneFixture(fixtureDir, {
166 prefix: "alchemy-nuxt-dev-remote-",
167 tempRoot,
168 entries: fixtureEntries,
169 });
170
171 const deployed = yield* stack.deploy(
172 Effect.gen(function* () {
173 const siteKv = yield* Cloudflare.KV.Namespace("NuxtDevRemoteKV").pipe(
174 Alchemy.remote(),
175 );
176 const site = yield* Cloudflare.Website.Nuxt("NuxtRemoteKvLocal", {
177 rootDir,
178 dev: { port: 0 },
179 memo: { include: memoInclude },
180 env: { TEST_BINDING: "nuxt-dev-remote-marker", SITE_KV: siteKv },
181 });
182 return { site, siteKv };
183 }),
184 );
185 const site = deployed.site;
186
187 // The site is served locally, but the remote() namespace is REAL —
188 // a live cloud id, not a `dev:` fabrication.
189 expect(site.url).toMatch(/^http:\/\/localhost:\d+/);
190 expect(deployed.siteKv.namespaceId).toBeDefined();
191 expect(deployed.siteKv.namespaceId).not.toMatch(/^dev:/);
192
193 // Write through the dev server's remote-proxied binding.
194 const put = yield* putJsonReady<{ put: boolean }>(
195 `${site.url!}/api/kv?key=remote-key&value=remote-value`,
196 );
197 expect(put.put).toBe(true);
198 const got = yield* fetchJsonReady<{ value: string | null }>(
199 `${site.url!}/api/kv?key=remote-key`,
200 );
201 expect(got.value).toBe("remote-value");
202
203 // Out-of-band: the write is visible through the cloud KV API — the
204 // remote-proxied binding really hit the live namespace.
205 const { accountId } = yield* yield* CloudflareEnvironment;
206 const observed = yield* kv
207 .getNamespaceValue({
208 accountId,
209 namespaceId: deployed.siteKv.namespaceId,
210 keyName: "remote-key",
211 })
212 .pipe(
213 Effect.retry({
214 while: (e): boolean => e._tag === "KeyNotFound",
215 schedule: Schedule.min([
216 Schedule.exponential("1 second"),
217 Schedule.spaced("3 seconds"),
218 ]),
219 times: 8,
220 }),
221 Effect.flatMap((res) =>
222 Effect.tryPromise(() =>
223 new Response(Stream.toReadableStream(res.body) as BodyInit).text(),
224 ),
225 ),
226 );
227 expect(observed).toBe("remote-value");
228
229 yield* stack.destroy();
230
231 // The live namespace was deleted from the cloud on destroy (its
232 // state row is stamped live, so the live provider handles the
233 // delete even in a dev run).
234 const gone = yield* kv
235 .getNamespace({ accountId, namespaceId: deployed.siteKv.namespaceId })
236 .pipe(
237 Effect.as(false),
238 Effect.catchTag("NamespaceNotFound", () => Effect.succeed(true)),
239 );
240 expect(gone).toBe(true);
241 }).pipe(logLevel),
242 { tags: ["live"], timeout: 300_000 },
243 );
244 },
245 );
246
247 /** GET `url` until it answers 200 with a JSON body. */
248 const fetchJsonReady = <T>(url: string) =>
249 Effect.gen(function* () {
250 const client = yield* HttpClient.HttpClient;
251 return yield* client.get(url).pipe(
252 Effect.flatMap((res) =>
253 res.status === 200
254 ? Effect.flatMap(res.text, (body) =>
255 Effect.try({
256 try: () => JSON.parse(body) as T,
257 catch: () => new Error(`non-json body: ${body}`),
258 }),
259 )
260 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
261 ),
262 Effect.retry({
263 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
264 times: 10,
265 }),
266 );
267 });
268
269 /** PUT (empty body) to `url` until it answers 200 with a JSON body. */
270 const putJsonReady = <T>(url: string) =>
271 HttpClient.execute(HttpClientRequest.put(url)).pipe(
272 Effect.flatMap((res) =>
273 res.status === 200
274 ? Effect.flatMap(res.text, (responseBody) =>
275 Effect.try({
276 try: () => JSON.parse(responseBody) as T,
277 catch: () => new Error(`non-json body: ${responseBody}`),
278 }),
279 )
280 : Effect.fail(new Error(`Worker not ready: ${res.status}`)),
281 ),
282 Effect.retry({
283 schedule: Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]),
284 times: 10,
285 }),
286 );