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

main
ts 142 lines 4.75 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import { DESTINATION, INBOX, SendEmail, SENDER, ZONE } from "./Email.ts";
6
7 interface ReceivedMessage {
8 from: string;
9 to: string;
10 subject: string | null;
11 bodySize: number;
12 receivedAt: number;
13 }
14
15 /**
16 * Durable Object that records every message the Worker's `email` handler
17 * sees so the integ test can confirm an inbound message round-tripped
18 * through Cloudflare's email routing.
19 */
20 export class Inbox extends Cloudflare.DurableObject<Inbox>()(
21 "Inbox",
22 Effect.gen(function* () {
23 return Effect.gen(function* () {
24 const state = yield* Cloudflare.DurableObjectState;
25 let received = (yield* state.storage.get<ReceivedMessage[]>("received")) ?? [];
26 return {
27 record: Effect.fn(function* (msg: ReceivedMessage) {
28 received = [...received, msg];
29 yield* state.storage.put("received", received);
30 }),
31 snapshot: () => Effect.succeed({ received }),
32 reset: Effect.fn(function* () {
33 received = [];
34 yield* state.storage.put("received", received);
35 }),
36 };
37 });
38 }),
39 ) {}
40
41 /**
42 * Email service Worker. Demonstrates both halves of a Cloudflare Email
43 * Worker:
44 *
45 * - **Inbound** — `Cloudflare.email({ zone, matchers }).subscribe(...)`
46 * auto-creates an `EmailRouting` toggle on the zone and an `EmailRule`
47 * whose `actions: [{ type: "worker", … }]` targets this Worker. The
48 * handler records each message on the `Inbox` DO.
49 * - **Outbound** — the `send_email` binding from `Email.ts` lets the
50 * Worker emit mail from the configured sender to the verified
51 * destination.
52 *
53 * Routes:
54 *
55 * - `GET /healthz` — liveness probe; reports the configured addresses.
56 * - `POST /send` body `{ subject, text }` — sends mail from sender to
57 * destination via the `send_email` binding.
58 * - `GET /received` — snapshot of messages the `email` handler has seen.
59 * - `POST /reset` — clear the recorded inbox (used by the integ test).
60 */
61 export default class Api extends Cloudflare.Worker<Api>()(
62 "Api",
63 {
64 main: import.meta.filename,
65 },
66 Effect.gen(function* () {
67 const email = yield* Cloudflare.Email.Send(SendEmail);
68 const inboxes = yield* Inbox;
69
70 // Subscribe to inbound mail addressed to INBOX on ZONE. The event
71 // source yields a sibling `Email.Routing` + `Email.Rule` at deploy
72 // time so no hand-rolled routing wiring is needed in `alchemy.run.ts`.
73 yield* Cloudflare.email({
74 zone: ZONE,
75 matchers: [{ type: "literal", field: "to", value: INBOX }],
76 }).subscribe((message) =>
77 inboxes.getByName("default").record({
78 from: message.from,
79 to: message.to,
80 subject: message.headers.get("subject"),
81 bodySize: message.bodySize,
82 receivedAt: Date.now(),
83 }),
84 );
85
86 return {
87 fetch: Effect.gen(function* () {
88 const request = yield* HttpServerRequest;
89 const url = new URL(request.url, "http://x");
90
91 if (url.pathname === "/healthz") {
92 return yield* HttpServerResponse.json({
93 ok: true,
94 from: SENDER,
95 to: DESTINATION,
96 inbox: INBOX,
97 });
98 }
99
100 if (url.pathname === "/received" && request.method === "GET") {
101 const snapshot = yield* inboxes.getByName("default").snapshot();
102 return yield* HttpServerResponse.json(snapshot);
103 }
104
105 if (url.pathname === "/reset" && request.method === "POST") {
106 yield* inboxes.getByName("default").reset();
107 return yield* HttpServerResponse.json({ ok: true });
108 }
109
110 if (url.pathname === "/send" && request.method === "POST") {
111 const body = (yield* request.json) as {
112 subject?: string;
113 text?: string;
114 to?: string;
115 };
116 const result = yield* email
117 .send({
118 from: SENDER,
119 to: body.to ?? DESTINATION,
120 subject: body.subject ?? "alchemy email example",
121 text: body.text ?? `sent at ${new Date().toISOString()}`,
122 })
123 .pipe(
124 Effect.match({
125 onSuccess: () => ({ ok: true as const }),
126 onFailure: (err) => ({
127 ok: false as const,
128 message: err.message,
129 }),
130 }),
131 );
132 return yield* HttpServerResponse.json(result);
133 }
134
135 return HttpServerResponse.text("not found", { status: 404 });
136 }),
137 };
138 }).pipe(
139 Effect.provide(Cloudflare.EmailEventSourceLive),
140 Effect.provide(Cloudflare.Email.SendBinding),
141 ),
142 ) {}