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

main
ts 151 lines 5.74 KB
Raw
1 import { DEFAULT_COMPATIBILITY_DATE } from "@alchemy.run/cloudflare-runtime/core/internal/constants";
2 import { Credentials } from "@distilled.cloud/cloudflare/Credentials";
3 import * as workers from "@distilled.cloud/cloudflare/workers";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as HttpClient from "effect/http/HttpClient";
7 import { Access } from "./Access.ts";
8 import { CloudflareEnvironment } from "./CloudflareEnvironment.ts";
9
10 /**
11 * A "remote binding" as understood by the Cloudflare Workers
12 * edge-preview API. We reuse the distilled request schema so the
13 * shape tracks Cloudflare's surface.
14 */
15 type EdgeMetadata = NonNullable<NonNullable<workers.CreateScriptEdgePreviewRequest["metadata"]>>;
16 export type EdgeBinding = NonNullable<NonNullable<EdgeMetadata["bindings"]>>[number];
17
18 export class EdgeSessionError extends Data.TaggedError("EdgeSessionError")<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export interface EdgeSessionOptions {
24 /**
25 * Name used as the preview script identifier on Cloudflare's side.
26 * Shows up as the hostname: `{scriptName}.{subdomain}.workers.dev`.
27 */
28 readonly scriptName: string;
29 /** ES-module worker script(s). The first file is the entrypoint. */
30 readonly files: ReadonlyArray<File>;
31 /** Remote bindings attached to the preview worker. */
32 readonly bindings: ReadonlyArray<EdgeBinding>;
33 /** @default "2026-08-31" */
34 readonly compatibilityDate?: string;
35 /**
36 * Serve the preview on a custom domain or route host in a zone instead of
37 * `{scriptName}.{subdomain}.workers.dev`. The script must already serve
38 * that host.
39 */
40 readonly route?: { readonly zoneId: string; readonly host: string };
41 }
42
43 /**
44 * Information needed to call a running edge-preview worker. Attach
45 * `headers` (including the `cf-workers-preview-token`) and fetch
46 * `url` or a path under it.
47 */
48 export interface EdgeSessionHandle {
49 readonly url: string;
50 readonly headers: Record<string, string>;
51 }
52
53 const wrap = <A, E, R>(effect: Effect.Effect<A, E, R>, message: string) =>
54 effect.pipe(Effect.mapError((cause) => new EdgeSessionError({ message, cause })));
55
56 /**
57 * Ask Cloudflare for a preview upload token. Some accounts return an
58 * `exchangeUrl` that must be GET'd to swap the session token for a
59 * short-lived upload token; when present we do the swap, falling back
60 * to the original if the exchange fails.
61 */
62 const createUploadToken = Effect.fn(function* (route: EdgeSessionOptions["route"]) {
63 const env = yield* yield* CloudflareEnvironment;
64 const http = yield* HttpClient.HttpClient;
65 const { token, exchangeUrl } = route
66 ? yield* workers.createZoneEdgePreviewSession({ zoneId: route.zoneId })
67 : yield* workers.createSubdomainEdgePreviewSession({ accountId: env.accountId });
68 if (!exchangeUrl) return token;
69 const json = yield* http.get(exchangeUrl).pipe(
70 Effect.flatMap((r) => r.json),
71 Effect.timeout(30_000),
72 Effect.orElseSucceed(() => null as unknown),
73 );
74 if (
75 typeof json === "object" &&
76 json !== null &&
77 "token" in json &&
78 typeof (json as Record<string, unknown>).token === "string"
79 ) {
80 return (json as { token: string }).token;
81 }
82 return token;
83 });
84
85 const uploadScript = (options: EdgeSessionOptions, uploadToken: string) =>
86 Effect.gen(function* () {
87 const env = yield* yield* CloudflareEnvironment;
88 const createScriptEdgePreview = yield* workers.createScriptEdgePreview;
89 return yield* createScriptEdgePreview({
90 accountId: env.accountId,
91 scriptName: options.scriptName,
92 cfPreviewUploadConfigToken: uploadToken,
93 wranglerSessionConfig: options.route
94 ? { routes: [`${options.route.host}/*`], minimalMode: true }
95 : { workersDev: true, minimalMode: true },
96 metadata: {
97 compatibilityDate: options.compatibilityDate ?? DEFAULT_COMPATIBILITY_DATE,
98 bindings: options.bindings as EdgeMetadata["bindings"],
99 mainModule: options.files[0]!.name,
100 },
101 // Distilled's generated schema expects a mutable array; our
102 // public surface keeps `readonly` so callers can pass a frozen
103 // tuple without a cast on their side.
104 files: options.files.slice(),
105 }).pipe(Effect.timeout(30_000));
106 });
107
108 const workerHost = (scriptName: string) =>
109 Effect.gen(function* () {
110 const env = yield* yield* CloudflareEnvironment;
111 const { subdomain } = yield* workers.getSubdomain({
112 accountId: env.accountId,
113 });
114 return `${scriptName}.${subdomain}.workers.dev`;
115 });
116
117 /**
118 * Upload a short-lived preview worker to Cloudflare's edge and
119 * return its URL plus the headers needed to reach it.
120 *
121 * Preview workers are ephemeral: they live only while a client keeps
122 * sending requests with the returned preview token and expire soon
123 * after. Nothing is deployed or billed.
124 */
125 export const createEdgeSession = (
126 options: EdgeSessionOptions,
127 ): Effect.Effect<
128 EdgeSessionHandle,
129 EdgeSessionError,
130 CloudflareEnvironment | HttpClient.HttpClient | Credentials | Access
131 > =>
132 Effect.gen(function* () {
133 const [{ previewToken }, { url, headers }] = yield* Effect.all(
134 [
135 createUploadToken(options.route).pipe(Effect.flatMap((t) => uploadScript(options, t))),
136 (options.route ? Effect.succeed(options.route.host) : workerHost(options.scriptName)).pipe(
137 Effect.flatMap(
138 Effect.fn(function* (host) {
139 const headers = yield* Access.use((access) => access.getAccessHeaders(host));
140 return { url: `https://${host}`, headers };
141 }),
142 ),
143 ),
144 ],
145 { concurrency: "unbounded" },
146 );
147 return {
148 url,
149 headers: { ...headers, "cf-workers-preview-token": previewToken },
150 } satisfies EdgeSessionHandle;
151 }).pipe((e) => wrap(e, "Failed to create edge preview session"));