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

main
ts 147 lines 5.86 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare/Bridge";
2 import { createFileRoute } from "@tanstack/react-router";
3 import * as Effect from "effect/Effect";
4 import * as HttpClientRequest from "effect/http/HttpClientRequest";
5 import * as HttpServerResponse from "effect/http/HttpServerResponse";
6 import type Backend from "../backend.ts";
7 import { env } from "../env.ts";
8
9 const VIAS = ["binding", "fetch", "rpc", "http-client"] as const;
10 type Via = (typeof VIAS)[number];
11
12 const parseRequest = (request: Request): { via: Via; key: string | null } => {
13 const url = new URL(request.url);
14 const raw = url.searchParams.get("via") ?? "binding";
15 const via = (VIAS as readonly string[]).includes(raw) ? (raw as Via) : "binding";
16 return { via, key: url.searchParams.get("key") };
17 };
18
19 // Surface the actual error in BOTH the response body and the worker logs —
20 // otherwise TanStack Start's outer boundary swallows it and you only ever
21 // see "HTTPError" in `bun alchemy logs`.
22 const trace = async (label: string, fn: () => Promise<Response>) => {
23 try {
24 return await fn();
25 } catch (err) {
26 const message = err instanceof Error ? (err.stack ?? err.message) : String(err);
27 console.error(`[api.hello] ${label} failed:`, message);
28 return new Response(`${label} failed: ${message}`, { status: 500 });
29 }
30 };
31
32 export const Route = createFileRoute("/api/hello")({
33 server: {
34 handlers: {
35 // GET /api/hello?key=<key>&via=binding|fetch|rpc
36 GET: async ({ request }) => {
37 const { via, key } = parseRequest(request);
38 if (!key) {
39 return new Response("Missing 'key' query parameter", { status: 400 });
40 }
41
42 switch (via) {
43 // option 1 — use the async binding directly
44 case "binding":
45 return trace("GET option 1 (env.BUCKET.get)", async () => {
46 const object = await env.BUCKET.get(key);
47 if (!object) return new Response("Not found", { status: 404 });
48 return new Response(object.body);
49 });
50
51 // option 2 — bind to your effect worker and call fetch
52 case "fetch":
53 return trace("GET option 2 (env.BACKEND.fetch)", async () => {
54 const res = await env.BACKEND.fetch(
55 `https://backend/?key=${encodeURIComponent(key)}`,
56 );
57 return new Response(res.body, {
58 status: res.status,
59 headers: res.headers,
60 });
61 });
62
63 // option 3 — bind to your effect worker and call rpc method
64 case "rpc":
65 return trace("GET option 3 (backend.hello rpc)", async () => {
66 // Wrap the raw wire-shape binding into a Promise<T> view that
67 // throws on Effect.fail and unwraps stream envelopes.
68 const backend = Cloudflare.toRpcAsync<Backend>(env.BACKEND);
69 const value = await backend.hello(key);
70 if (value === null) return new Response("Not found", { status: 404 });
71 return new Response(value);
72 });
73
74 // option 4 — bind to your effect worker and call http client
75 case "http-client":
76 return trace("GET option 4 (env.BACKEND.httpClient)", async () => {
77 const client = Cloudflare.toHttpClient(Cloudflare.fromCloudflareFetcher(env.BACKEND));
78 const res = await client
79 .get(`https://backend/?key=${encodeURIComponent(key)}`)
80 .pipe(Effect.runPromise);
81 return HttpServerResponse.toWeb(HttpServerResponse.fromClientResponse(res));
82 });
83 }
84 },
85
86 // PUT /api/hello?key=<key>&via=binding|fetch
87 // (option 3 is GET-only — `hello` is a read RPC for demonstration.)
88 PUT: async ({ request }) => {
89 const { via, key } = parseRequest(request);
90 if (!key) {
91 return new Response("Missing 'key' query parameter", { status: 400 });
92 }
93 if (!request.body) {
94 return new Response("Missing request body", { status: 400 });
95 }
96
97 switch (via) {
98 // option 1 — use the async binding directly
99 case "binding":
100 return trace("PUT option 1 (env.BUCKET.put)", async () => {
101 await env.BUCKET.put(key, request.body, {
102 httpMetadata: {
103 contentType: request.headers.get("content-type") ?? "application/octet-stream",
104 },
105 });
106 return new Response(null, { status: 204 });
107 });
108
109 // option 2 — bind to your effect worker and call fetch
110 case "fetch":
111 return trace("PUT option 2 (env.BACKEND.fetch)", async () => {
112 const res = await env.BACKEND.fetch(
113 `https://backend/?key=${encodeURIComponent(key)}`,
114 {
115 method: "PUT",
116 body: request.body,
117 headers: request.headers,
118 },
119 );
120 return new Response(res.body, {
121 status: res.status,
122 headers: res.headers,
123 });
124 });
125
126 // option 3 — RPC `hello` is read-only
127 case "rpc":
128 return new Response("PUT is not supported via=rpc", {
129 status: 400,
130 });
131
132 // option 4 — bind to your effect worker and call http client
133 case "http-client":
134 return trace("PUT option 4 (env.BACKEND.httpClient)", async () => {
135 const client = Cloudflare.toHttpClient(Cloudflare.fromCloudflareFetcher(env.BACKEND));
136 const res = await client
137 .execute(HttpClientRequest.fromWeb(request))
138 .pipe(Effect.runPromise);
139 return HttpServerResponse.toWeb(HttpServerResponse.fromClientResponse(res), {
140 withoutBody: res.status === 204,
141 });
142 });
143 }
144 },
145 },
146 },
147 });