1import * as Cloudflare from "@/Cloudflare/index.ts";
2import * as Alchemy from "@/index.ts";
3import * as Test from "@/Test/Alchemy";
4import { expect } from "alchemy-test";
5import * as Data from "effect/Data";
6import * as Effect from "effect/Effect";
7import { MinimumLogLevel } from "effect/References";
8import * as Schedule from "effect/Schedule";
9import * as HttpClient from "effect/http/HttpClient";
10import * as pathe from "pathe";
11
12// `dev: true` runs local providers behind the RPC sidecar proxy by default,
13// matching the process topology of the real `alchemy dev` command.
14const { test } = Test.make({
15 providers: Cloudflare.providers(),
16 dev: true,
17});
18
19const logLevel = Effect.provideService(
20 MinimumLogLevel,
21 process.env.DEBUG ? "Debug" : "Info",
22);
23
24class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{
25 status: number;
26 body: string;
27}> {}
28
29/**
30 * Fetch a URL, retrying until the worker serves a 200 (fresh dev workers can
31 * briefly 503 while workerd boots; the first browser request may also launch
32 * Chrome). Non-200s carry the body so a persistent fixture error surfaces.
33 */
34const getReady = (url: string) =>
35 Effect.gen(function* () {
36 const client = yield* HttpClient.HttpClient;
37 return yield* client.get(url).pipe(
38 Effect.flatMap((res) =>
39 res.status === 200
40 ? Effect.succeed(res)
41 : res.text.pipe(
42 Effect.flatMap((body) =>
43 Effect.fail(new WorkerNotReady({ status: res.status, body })),
44 ),
45 ),
46 ),
47 Effect.retry({
48 while: (e): e is WorkerNotReady => e instanceof WorkerNotReady,
49 schedule: Schedule.max([
50 Schedule.min([
51 Schedule.exponential("500 millis"),
52 Schedule.spaced("2 seconds"),
53 ]),
54 Schedule.recurs(10),
55 ]),
56 }),
57 );
58 }).pipe(Effect.orDie);
59
60const fixtureMain = pathe.resolve(
61 import.meta.dirname,
62 "fixtures/browser-local-worker.ts",
63);
64
65/**
66 * Under `alchemy dev` the `browser` binding is emulated by cloudflare-runtime:
67 * a real headless Chrome is launched on this machine (downloaded on first use
68 * into the shared wrangler cache) and the Browser Rendering session protocol
69 * is proxied to its CDP endpoint. `@cloudflare/puppeteer` drives it exactly
70 * like the real service — no Cloudflare credentials or preview session are
71 * involved for the binding.
72 */
73test.provider(
74 "browser binding round-trips against the local Chrome simulator",
75 (stack) =>
76 Effect.gen(function* () {
77 yield* stack.destroy();
78
79 const deployed = yield* stack.deploy(
80 Effect.gen(function* () {
81 const worker = yield* Cloudflare.Worker("browser-local-worker", {
82 main: fixtureMain,
83 compatibility: { flags: ["nodejs_compat"] },
84 env: { BROWSER: Cloudflare.Browser("BROWSER") },
85 });
86 return { url: worker.url.as<string>() };
87 }),
88 );
89
90 // Served from the local dev proxy — proof the worker runs locally.
91 expect(deployed.url).toMatch(/^http:\/\/localhost:\d+$/);
92
93 // Render an inline page through puppeteer over the emulated binding.
94 // The first request may download Chrome, so it gets a long retry rope.
95 const titleRes = yield* getReady(`${deployed.url}/title`);
96 const body = (yield* titleRes.json) as {
97 title: string;
98 heading: string;
99 };
100 expect(body.title).toBe("Local Browser Test");
101 expect(body.heading).toBe("Hello from the local browser");
102
103 // A screenshot of the same page is a real PNG (magic bytes).
104 const shotRes = yield* getReady(`${deployed.url}/screenshot`);
105 const bytes = new Uint8Array(yield* shotRes.arrayBuffer);
106 expect(bytes.length).toBeGreaterThan(1000);
107 expect(Array.from(bytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]);
108
109 yield* stack.destroy();
110 }).pipe(logLevel),
111 {
112 tags: ["provider:cloudflare", "provider:cloudflare:worker", "local"],
113 timeout: 180_000,
114 },
115);
116
117/**
118 * `Alchemy.remote()` opts the binding OUT of local emulation: the
119 * locally-served worker drives the real Browser Rendering service through
120 * the remote-bindings preview session. The live suite
121 * (test/Cloudflare/Browser/Browser.test.ts) covers deployed-binding
122 * behavior; this leg pins the dev-mode remote lowering path.
123 */
124test.provider(
125 "Alchemy.remote() proxies the binding to the real Browser Rendering service",
126 (stack) =>
127 Effect.gen(function* () {
128 yield* stack.destroy();
129
130 const deployed = yield* stack.deploy(
131 Effect.gen(function* () {
132 const worker = yield* Cloudflare.Worker("browser-remote-worker", {
133 main: fixtureMain,
134 compatibility: { flags: ["nodejs_compat"] },
135 env: {
136 BROWSER: Cloudflare.Browser("BROWSER").pipe(Alchemy.remote()),
137 },
138 });
139 return { url: worker.url.as<string>() };
140 }),
141 );
142
143 // Still served locally — only the binding is remote.
144 expect(deployed.url).toMatch(/^http:\/\/localhost:\d+$/);
145
146 const titleRes = yield* getReady(`${deployed.url}/title`);
147 const body = (yield* titleRes.json) as { title: string };
148 expect(body.title).toBe("Local Browser Test");
149
150 yield* stack.destroy();
151 }).pipe(logLevel),
152 {
153 tags: ["provider:cloudflare", "provider:cloudflare:worker", "live"],
154 timeout: 180_000,
155 },
156);