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

main
ts 355 lines 12.2 KB
Raw
1 import * as NodeNet from "node:net";
2 import * as Cloudflare from "@alchemy.run/cloudflare";
3 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Redacted from "effect/Redacted";
9 import { MinimumLogLevel } from "effect/References";
10 import * as Schedule from "effect/Schedule";
11 import * as pathe from "pathe";
12 import { cloneFixture } from "../Utils/Fixture.ts";
13 import { expectResponse } from "../Utils/Http.ts";
14 import { expectWorkerExists, waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
15
16 // Node.js compatibility of a `Website.Vite` Worker, mirroring
17 // `@cloudflare/vite-plugin`'s `node-compat` playground: each variant is the
18 // playground's Worker (`vite-node-compat-fixture/src/<variant>`) with its
19 // compatibility settings and bindings, run deployed and under `alchemy dev`
20 // as the plugin runs each in build and dev mode.
21
22 const { test } = Test.make({ providers: Cloudflare.providers() });
23 const { test: devTest } = Test.make({ providers: Cloudflare.providers(), dev: true });
24
25 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
26 const tempRoot = pathe.resolve(import.meta.dirname, "../../../.tmp");
27 const fixtureDir = pathe.resolve(import.meta.dirname, "vite-node-compat-fixture");
28
29 type Mode = "live" | "dev";
30
31 interface Variant {
32 name: string;
33 date: string;
34 flags: Array<string>;
35 env?: (mode: Mode, context: { pgPort: number }) => Record<string, unknown>;
36 config?: string;
37 modes?: ReadonlyArray<Mode>;
38 check: (
39 url: string,
40 mode: Mode,
41 /** The site's log since this attempt's deploy. */
42 log: Effect.Effect<string>,
43 ) => Effect.Effect<void, unknown, FileSystem.FileSystem>;
44 }
45
46 const expectText = (url: string, expected: string) =>
47 expectResponse(url, (res) =>
48 res.status === 200 && res.body === expected
49 ? undefined
50 : `${res.status} ${JSON.stringify(res.body.slice(0, 600))}, expected ${JSON.stringify(expected)}`,
51 );
52
53 const expectJson = (url: string, check: (body: unknown) => void) =>
54 expectResponse(url, (res) => {
55 if (res.status !== 200) return `status ${res.status} ${res.body.slice(0, 600)}`;
56 try {
57 check(JSON.parse(res.body));
58 return undefined;
59 } catch {
60 return `json ${res.body.slice(0, 300)}`;
61 }
62 });
63
64 const VARIANTS: ReadonlyArray<Variant> = [
65 {
66 name: "cloudflare-node",
67 date: "2025-11-13",
68 flags: ["nodejs_compat"],
69 check: (url) => expectText(url, "Hello from an httpServerHandler"),
70 },
71 {
72 name: "als",
73 date: "2024-12-30",
74 flags: ["nodejs_als"],
75 check: (url, mode, log) =>
76 Effect.gen(function* () {
77 yield* expectText(url, "OK!");
78 // It won't log any Node.js compat warnings.
79 if (mode === "dev") {
80 expect(yield* log).not.toContain("Unexpected Node.js imports");
81 }
82 }),
83 },
84 {
85 name: "basic",
86 date: "2024-12-30",
87 flags: ["nodejs_compat"],
88 env: () => ({
89 MY_DO: Cloudflare.DurableObject("MyDurableObject", { className: "MyDurableObject" }),
90 MY_SERVICE: Cloudflare.WorkerEntrypoint("MyWorkerEntrypoint"),
91 }),
92 check: (url) => expectText(url, `"OK!"`),
93 },
94 {
95 // Third-party packages unenv aliases (`cross-fetch`).
96 name: "cross-env",
97 date: "2024-12-30",
98 flags: ["nodejs_compat"],
99 check: (url) => expectText(url, `"OK!"`),
100 },
101 {
102 name: "crypto",
103 date: "2024-12-30",
104 flags: ["nodejs_compat"],
105 check: (url) =>
106 expectResponse(url, (res) =>
107 res.status === 200 &&
108 res.body.startsWith(`"OK!": -----BEGIN CERTIFICATE-----\nMIICZjCCAc+gAwIBAgIUOsv8Y+x40C+g`)
109 ? undefined
110 : `${res.status} ${res.body.slice(0, 300)}`,
111 ),
112 },
113 {
114 name: "debug",
115 date: "2025-07-30",
116 flags: ["nodejs_compat"],
117 env: () => ({ DEBUG: "example:*,test" }),
118 check: (url) =>
119 expectJson(url, (body) =>
120 expect(body).toEqual([
121 "test Test import message 1",
122 "example:foo Example foo import message",
123 "test Test import enabled message",
124 ]),
125 ),
126 },
127 {
128 name: "https",
129 date: "2025-08-15",
130 flags: ["nodejs_compat"],
131 check: (url) => expectText(url, "OK"),
132 },
133 {
134 // `pg` over `cloudflare:sockets`: deployed, the Worker can't reach the
135 // test's local server, so only dev sends a query.
136 name: "postgres",
137 date: "2024-12-30",
138 flags: ["nodejs_compat"],
139 env: (_mode, { pgPort }) => ({
140 DB_HOSTNAME: "127.0.0.1",
141 DB_PORT: String(pgPort),
142 DB_NAME: "testdb",
143 DB_USERNAME: "testuser",
144 DB_PASSWORD: "testpassword",
145 }),
146 check: (url, mode) =>
147 Effect.gen(function* () {
148 yield* expectText(url, "127.0.0.1");
149 if (mode === "dev") {
150 yield* expectJson(`${url}/send-query`, (body) =>
151 expect(body).toEqual(expect.objectContaining({ id: "21" })),
152 );
153 }
154 }),
155 },
156 {
157 name: "process",
158 date: "2024-12-30",
159 flags: ["nodejs_compat", "nodejs_compat_do_not_populate_process_env"],
160 env: () => ({ FOO: "foo value" }),
161 check: (url) => expectText(url, "OK!"),
162 },
163 {
164 name: "process-populated-env",
165 date: "2024-12-30",
166 flags: ["nodejs_compat", "nodejs_compat_populate_process_env"],
167 env: () => ({ FOO: "foo value", BAR: Redacted.make("bar secret") }),
168 check: (url) => expectText(url, "OK!"),
169 },
170 {
171 name: "random",
172 date: "2024-12-30",
173 flags: ["nodejs_compat"],
174 check: (url) =>
175 expectJson(url, (body) =>
176 expect(body).toEqual([
177 expect.any(String),
178 expect.any(String),
179 expect.any(String),
180 expect.any(String),
181 ]),
182 ),
183 },
184 {
185 // A plugin resolving a Node.js built-in through the Worker environment's
186 // plugin container gets its external id (dev only, as the plugin's spec).
187 name: "resolve-externals",
188 date: "2024-12-30",
189 flags: ["nodejs_compat"],
190 config: "resolve-externals",
191 modes: ["dev"],
192 check: (url, _mode, devLog) =>
193 Effect.gen(function* () {
194 yield* expectText(url, "OK!");
195 const log = yield* devLog.pipe(
196 Effect.filterOrFail((log) => log.includes("__node:dns__")),
197 Effect.retry({ times: 10, schedule: Schedule.spaced("1 second") }),
198 );
199 expect(log).toContain("__node:dns__");
200 }),
201 },
202 ];
203
204 const id = (variant: Variant, mode: Mode) =>
205 `ViteNodeCompat${mode}${variant.name.replace(/(^|-)(\w)/g, (_, _dash, c: string) => c.toUpperCase())}`;
206
207 const deployVariant = (stack: Test.ScratchStack, variant: Variant, mode: Mode, pgPort: number) =>
208 Effect.gen(function* () {
209 const rootDir = yield* cloneFixture(fixtureDir, {
210 prefix: `alchemy-vite-node-compat-${variant.name}-`,
211 tempRoot,
212 entries: ["package.json", "configs", "src"],
213 });
214 if (variant.config) {
215 const fs = yield* FileSystem.FileSystem;
216 yield* fs.copyFile(
217 pathe.join(rootDir, `configs/${variant.config}.ts`),
218 pathe.join(rootDir, "vite.config.ts"),
219 );
220 }
221 return yield* stack.deploy(
222 Cloudflare.Website.Vite(id(variant, mode), {
223 rootDir,
224 main: `./src/${variant.name}/index.ts`,
225 workersDev: true,
226 compatibility: { date: variant.date, flags: variant.flags },
227 memo: { include: ["**/*"] },
228 env: variant.env?.(mode, { pgPort }) as never,
229 ...(mode === "dev" ? { dev: { port: 0 } } : {}),
230 }),
231 );
232 });
233
234 // The playground's mock Postgres server: trusts every login and answers
235 // every query with one row.
236 const mockPostgres = Effect.acquireRelease(
237 Effect.promise(
238 () =>
239 new Promise<NodeNet.Server>((resolve) => {
240 const server = NodeNet.createServer((socket) => {
241 let buffer = Buffer.alloc(0);
242 let started = false;
243 const message = (type: string, body: Buffer) => {
244 const header = Buffer.alloc(5);
245 header.write(type, 0);
246 header.writeInt32BE(body.length + 4, 1);
247 return Buffer.concat([header, body]);
248 };
249 const int16 = (n: number) => {
250 const b = Buffer.alloc(2);
251 b.writeInt16BE(n);
252 return b;
253 };
254 const int32 = (n: number) => {
255 const b = Buffer.alloc(4);
256 b.writeInt32BE(n);
257 return b;
258 };
259 const cstr = (s: string) => Buffer.from(`${s}\0`);
260 const ready = message("Z", Buffer.from("I"));
261 const row = { id: "21", name: "mock-row" };
262 socket.on("data", (chunk) => {
263 buffer = Buffer.concat([buffer, chunk]);
264 while (true) {
265 if (!started) {
266 if (buffer.length < 4) return;
267 const length = buffer.readInt32BE(0);
268 if (buffer.length < length) return;
269 const code = buffer.readInt32BE(4);
270 buffer = buffer.subarray(length);
271 // SSLRequest: refuse, the client continues in plain text.
272 if (code === 80877103) {
273 socket.write("N");
274 continue;
275 }
276 started = true;
277 socket.write(Buffer.concat([message("R", int32(0)), ready]));
278 continue;
279 }
280 if (buffer.length < 5) return;
281 const type = String.fromCharCode(buffer[0]!);
282 const length = buffer.readInt32BE(1);
283 if (buffer.length < length + 1) return;
284 buffer = buffer.subarray(length + 1);
285 if (type === "X") return void socket.end();
286 if (type !== "Q") continue;
287 const columns = Object.keys(row);
288 const description = Buffer.concat([
289 int16(columns.length),
290 ...columns.map((name) =>
291 Buffer.concat([
292 cstr(name),
293 int32(0),
294 int16(0),
295 int32(25),
296 int16(-1),
297 int32(-1),
298 int16(0),
299 ]),
300 ),
301 ]);
302 const data = Buffer.concat([
303 int16(columns.length),
304 ...Object.values(row).map((value) =>
305 Buffer.concat([int32(Buffer.byteLength(value)), Buffer.from(value)]),
306 ),
307 ]);
308 socket.write(
309 Buffer.concat([
310 message("T", description),
311 message("D", data),
312 message("C", cstr("SELECT 1")),
313 ready,
314 ]),
315 );
316 }
317 });
318 socket.on("error", () => {});
319 });
320 server.listen(0, "127.0.0.1", () => resolve(server));
321 }),
322 ),
323 (server) => Effect.promise(() => new Promise<void>((resolve) => server.close(() => resolve()))),
324 ).pipe(Effect.map((server) => (server.address() as NodeNet.AddressInfo).port));
325
326 describe("Website.Vite Node.js compatibility", () => {
327 for (const variant of VARIANTS) {
328 for (const mode of variant.modes ?? (["live", "dev"] as const)) {
329 (mode === "live" ? test : devTest).provider(
330 `Vite node-compat: ${variant.name}${mode === "dev" ? " (dev)" : ""}`,
331 (stack) =>
332 Effect.gen(function* () {
333 yield* stack.destroy();
334 const pgPort = yield* mockPostgres;
335 const log = yield* Test.captureResourceLog(id(variant, mode));
336 const site = yield* deployVariant(stack, variant, mode, pgPort);
337 const url = site.url!.replace(/\/$/, "");
338 if (mode === "live") {
339 const { accountId } = yield* yield* CloudflareEnvironment;
340 yield* expectWorkerExists(site.workerName, accountId);
341 yield* variant.check(url, mode, log);
342 yield* stack.destroy();
343 yield* waitForWorkerToBeDeleted(site.workerName, accountId);
344 } else {
345 yield* variant.check(url, mode, log);
346 }
347 }).pipe(Effect.scoped, Effect.ensuring(stack.destroy().pipe(Effect.ignore)), logLevel),
348 {
349 tags: ["provider:cloudflare:worker", mode === "dev" ? "local" : "live"],
350 timeout: 300_000,
351 },
352 );
353 }
354 }
355 });