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
| 1 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 2 | import { expect } from "@alchemy.run/test"; |
| 3 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as FileSystem from "effect/FileSystem"; |
| 7 | import * as HttpClient from "effect/http/HttpClient"; |
| 8 | import * as Path from "effect/Path"; |
| 9 | import { MinimumLogLevel } from "effect/References"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as pathe from "pathe"; |
| 12 | import LocalSendEmailWorker from "./fixtures/local-worker.ts"; |
| 13 | import RemoteEmailWorker from "./fixtures/remote-email-worker.ts"; |
| 14 | |
| 15 | // `dev: true` runs local providers behind the RPC sidecar proxy by default, |
| 16 | // matching the process topology of the real `alchemy dev` command (see |
| 17 | // MakeOptions.sidecar in Test/Core.ts). |
| 18 | const { test } = Test.make({ |
| 19 | providers: Cloudflare.providers(), |
| 20 | dev: true, |
| 21 | }); |
| 22 | |
| 23 | const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info"); |
| 24 | |
| 25 | class WorkerNotReady extends Data.TaggedError("WorkerNotReady")<{ |
| 26 | status: number; |
| 27 | }> {} |
| 28 | |
| 29 | const getReady = (url: string, expected: Array<number>) => |
| 30 | Effect.gen(function* () { |
| 31 | const client = yield* HttpClient.HttpClient; |
| 32 | return yield* client.get(url).pipe( |
| 33 | Effect.flatMap((res) => |
| 34 | expected.includes(res.status) |
| 35 | ? Effect.succeed(res) |
| 36 | : Effect.fail(new WorkerNotReady({ status: res.status })), |
| 37 | ), |
| 38 | Effect.retry({ |
| 39 | while: (e): e is WorkerNotReady => e instanceof WorkerNotReady, |
| 40 | schedule: Schedule.max([ |
| 41 | Schedule.min([Schedule.exponential("500 millis"), Schedule.spaced("2 seconds")]), |
| 42 | Schedule.recurs(10), |
| 43 | ]), |
| 44 | }), |
| 45 | ); |
| 46 | }).pipe(Effect.orDie); |
| 47 | |
| 48 | class EmlNotFound extends Data.TaggedError("EmlNotFound")<{ |
| 49 | directory: string; |
| 50 | }> {} |
| 51 | |
| 52 | /** |
| 53 | * Find the persisted `.eml` under the local runtime storage directory |
| 54 | * (`.alchemy/local/email`) whose content carries `marker`. Bounded poll: the |
| 55 | * write happens before `send()` resolves, but the simulator runs in the |
| 56 | * sidecar process, so allow a few refresh rounds. |
| 57 | */ |
| 58 | const findEmlWithMarker = (marker: string) => |
| 59 | Effect.gen(function* () { |
| 60 | const fs = yield* FileSystem.FileSystem; |
| 61 | const path = yield* Path.Path; |
| 62 | const cwd = yield* Effect.sync(() => process.cwd()); |
| 63 | const emailDir = path.join(cwd, ".alchemy", "local", "email"); |
| 64 | const files = yield* fs |
| 65 | .readDirectory(emailDir) |
| 66 | .pipe(Effect.orElseSucceed(() => [] as Array<string>)); |
| 67 | for (const name of files) { |
| 68 | if (!name.endsWith(".eml")) continue; |
| 69 | const content = yield* fs |
| 70 | .readFileString(path.join(emailDir, name)) |
| 71 | .pipe(Effect.orElseSucceed(() => "")); |
| 72 | if (content.includes(`marker:${marker}`)) { |
| 73 | return content; |
| 74 | } |
| 75 | } |
| 76 | return yield* new EmlNotFound({ directory: emailDir }); |
| 77 | }).pipe( |
| 78 | Effect.retry({ |
| 79 | while: (e): e is EmlNotFound => e instanceof EmlNotFound, |
| 80 | schedule: Schedule.spaced("500 millis"), |
| 81 | times: 10, |
| 82 | }), |
| 83 | ); |
| 84 | |
| 85 | /** |
| 86 | * Under `alchemy dev` the worker's `send_email` binding is lowered onto the |
| 87 | * local simulator: `send()` validates the message and persists it as a |
| 88 | * `.eml` under `.alchemy/local/email` instead of delivering real mail. This |
| 89 | * exercises the full local roundtrip (EmailMessage + MessageBuilder APIs) |
| 90 | * and the address validation surfacing to the caller. |
| 91 | */ |
| 92 | test.provider( |
| 93 | "send_email binding delivers to the local simulator", |
| 94 | (stack) => |
| 95 | Effect.gen(function* () { |
| 96 | yield* stack.destroy(); |
| 97 | |
| 98 | const deployed = yield* stack.deploy( |
| 99 | Effect.gen(function* () { |
| 100 | const email = yield* Cloudflare.Email.SendEmail("LocalEmail", { |
| 101 | allowedDestinationAddresses: ["allowed@example.com"], |
| 102 | }); |
| 103 | const worker = yield* Cloudflare.Worker("send-email-local-worker", { |
| 104 | main: pathe.resolve(import.meta.dirname, "fixtures/local-email-worker.ts"), |
| 105 | env: { EMAIL: email }, |
| 106 | }); |
| 107 | return { worker }; |
| 108 | }), |
| 109 | ); |
| 110 | |
| 111 | // The worker serves from the local dev proxy — proof no deployment to |
| 112 | // Cloudflare happened (send_email itself is a Worker-only descriptor; |
| 113 | // there is no cloud resource to check). |
| 114 | expect(deployed.worker.url).toMatch(/^http:\/\/localhost:\d+$/); |
| 115 | |
| 116 | // EmailMessage API: the message is validated and persisted as .eml. |
| 117 | const marker = yield* Effect.sync(() => crypto.randomUUID()); |
| 118 | const rawRes = yield* getReady(`${deployed.worker.url}/send-raw?marker=${marker}`, [200]); |
| 119 | const rawBody = (yield* rawRes.json) as { |
| 120 | ok: boolean; |
| 121 | messageId: string; |
| 122 | }; |
| 123 | expect(rawBody.ok).toBe(true); |
| 124 | // The simulator synthesizes a production-shaped Message-ID. |
| 125 | expect(rawBody.messageId).toMatch(/^<[A-Za-z0-9]{36}@example\.com>$/); |
| 126 | |
| 127 | // The .eml landed in the local storage directory with the full MIME |
| 128 | // message. |
| 129 | const eml = yield* findEmlWithMarker(marker); |
| 130 | expect(eml).toContain("From: sender <sender@example.com>"); |
| 131 | expect(eml).toContain(`Message-ID: <${marker}@example.com>`); |
| 132 | |
| 133 | // MessageBuilder API round-trips too. |
| 134 | const builderRes = yield* getReady(`${deployed.worker.url}/send-builder`, [200]); |
| 135 | const builderBody = (yield* builderRes.json) as { |
| 136 | ok: boolean; |
| 137 | messageId: string; |
| 138 | }; |
| 139 | expect(builderBody.ok).toBe(true); |
| 140 | expect(builderBody.messageId).toMatch(/^<[A-Za-z0-9]{36}@example\.com>$/); |
| 141 | |
| 142 | // A disallowed destination surfaces the simulator's validation error |
| 143 | // to the caller. |
| 144 | const blockedRes = yield* getReady( |
| 145 | `${deployed.worker.url}/send-builder?to=blocked@example.com`, |
| 146 | [500], |
| 147 | ); |
| 148 | const blockedBody = (yield* blockedRes.json) as { |
| 149 | ok: boolean; |
| 150 | message: string; |
| 151 | }; |
| 152 | expect(blockedBody.ok).toBe(false); |
| 153 | expect(blockedBody.message).toContain("email to blocked@example.com not allowed"); |
| 154 | |
| 155 | yield* stack.destroy(); |
| 156 | }).pipe(logLevel), |
| 157 | { |
| 158 | tags: [ |
| 159 | "provider:cloudflare", |
| 160 | "provider:cloudflare:email", |
| 161 | "provider:cloudflare:worker", |
| 162 | "local", |
| 163 | ], |
| 164 | timeout: 120_000, |
| 165 | }, |
| 166 | ); |
| 167 | |
| 168 | /** |
| 169 | * `Alchemy.remote()` on the descriptor opts a `send_email` binding OUT of |
| 170 | * local emulation, per binding: one dev worker binds a default (simulated) |
| 171 | * descriptor and a `remote()`-piped one side by side. The simulator accepts |
| 172 | * an unrestricted send from an arbitrary address, while the live Email |
| 173 | * service enforces sender/destination verification and rejects the same |
| 174 | * pair — proof the call was served by the real binding, with no mail |
| 175 | * delivered on either route. |
| 176 | */ |
| 177 | test.provider( |
| 178 | "Alchemy.remote() binds the live service alongside a simulated one", |
| 179 | (stack) => |
| 180 | Effect.gen(function* () { |
| 181 | yield* stack.destroy(); |
| 182 | |
| 183 | const deployed = yield* stack.deploy( |
| 184 | Effect.gen(function* () { |
| 185 | const worker = yield* LocalSendEmailWorker; |
| 186 | return { url: worker.url.as<string>() }; |
| 187 | }), |
| 188 | ); |
| 189 | |
| 190 | // The worker itself is served by the local dev proxy. |
| 191 | expect(deployed.url).toMatch(/^http:\/\/localhost:\d+$/); |
| 192 | |
| 193 | const params = "from=noreply%40alchemy-local-test.invalid&to=nobody%40example.com"; |
| 194 | |
| 195 | // The simulator accepts the unrestricted send without delivering. |
| 196 | const stubRes = yield* getReady(`${deployed.url}/send-stub?${params}`, [200]); |
| 197 | const stub = (yield* stubRes.json) as { ok: boolean }; |
| 198 | expect(stub.ok).toBe(true); |
| 199 | |
| 200 | // The remote()-opted binding reaches the live Email service, which |
| 201 | // rejects the unverified sender/destination pair. |
| 202 | const liveRes = yield* getReady(`${deployed.url}/send-live?${params}`, [200]); |
| 203 | const live = (yield* liveRes.json) as { ok: boolean; message?: string }; |
| 204 | expect(live.ok).toBe(false); |
| 205 | |
| 206 | yield* stack.destroy(); |
| 207 | }).pipe(logLevel), |
| 208 | { |
| 209 | tags: [ |
| 210 | "provider:cloudflare", |
| 211 | "provider:cloudflare:email", |
| 212 | "provider:cloudflare:worker", |
| 213 | "live", |
| 214 | ], |
| 215 | timeout: 120_000, |
| 216 | }, |
| 217 | ); |
| 218 | |
| 219 | const FROM = process.env.CLOUDFLARE_TEST_EMAIL_FROM; |
| 220 | const TO = process.env.CLOUDFLARE_TEST_EMAIL_TO; |
| 221 | const skipRemote = !FROM || !TO; |
| 222 | |
| 223 | /** |
| 224 | * `Alchemy.remote()` opts the binding OUT of local emulation: the |
| 225 | * locally-served worker proxies `send()` through the remote-bindings preview |
| 226 | * session to the real Cloudflare Email service. Requires a verified |
| 227 | * sender/destination pair (CLOUDFLARE_TEST_EMAIL_FROM / _TO), same as the |
| 228 | * live suite — delivery itself cannot be observed out-of-band, so success of |
| 229 | * the real `send()` is the assertion. |
| 230 | */ |
| 231 | test.provider.skipIf(skipRemote)( |
| 232 | "Alchemy.remote() proxies send() to the real Email service", |
| 233 | (stack) => |
| 234 | Effect.gen(function* () { |
| 235 | yield* stack.destroy(); |
| 236 | |
| 237 | const deployed = yield* stack.deploy( |
| 238 | Effect.gen(function* () { |
| 239 | const worker = yield* RemoteEmailWorker; |
| 240 | return { url: worker.url.as<string>() }; |
| 241 | }), |
| 242 | ); |
| 243 | |
| 244 | // Still served locally — only the binding is remote. |
| 245 | expect(deployed.url).toMatch(/^http:\/\/localhost:\d+$/); |
| 246 | |
| 247 | const sendUrl = `${deployed.url}/send?from=${encodeURIComponent(FROM!)}&to=${encodeURIComponent(TO!)}`; |
| 248 | const res = yield* getReady(sendUrl, [200]); |
| 249 | const body = (yield* res.json) as { ok: boolean; message?: string }; |
| 250 | if (!body.ok) { |
| 251 | throw new Error(`remote send_email failed: ${body.message}`); |
| 252 | } |
| 253 | expect(body.ok).toBe(true); |
| 254 | |
| 255 | yield* stack.destroy(); |
| 256 | }).pipe(logLevel), |
| 257 | { |
| 258 | tags: [ |
| 259 | "provider:cloudflare", |
| 260 | "provider:cloudflare:email", |
| 261 | "provider:cloudflare:worker", |
| 262 | "live", |
| 263 | ], |
| 264 | timeout: 180_000, |
| 265 | }, |
| 266 | ); |