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, 04:45 UTC
| 1 | import type { WorkerLoader as _WorkerLoader } from "@cloudflare/workers-types"; |
| 2 | import { ALCHEMY_PHASE } from "alchemy/Phase"; |
| 3 | import type { RuntimeContext } from "alchemy/RuntimeContext"; |
| 4 | import { asEffect } from "alchemy/Util"; |
| 5 | import { taggedFunction } from "alchemy/Util/effect"; |
| 6 | import * as Context from "effect/Context"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import { fromCloudflareFetcher, type Fetcher } from "../Fetcher.ts"; |
| 10 | import { makeRpcStub } from "./Rpc.ts"; |
| 11 | import { Worker, WorkerEnvironment } from "./Worker.ts"; |
| 12 | |
| 13 | type WorkerLoaderTypeId = "Cloudflare.DynamicWorker"; |
| 14 | const WorkerLoaderTypeId: WorkerLoaderTypeId = "Cloudflare.DynamicWorker"; |
| 15 | |
| 16 | export interface WorkerLoaderWorkerCode { |
| 17 | compatibilityDate: string; |
| 18 | compatibilityFlags?: string[]; |
| 19 | allowExperimental?: boolean; |
| 20 | limits?: workerdResourceLimits; |
| 21 | mainModule: string; |
| 22 | modules: Record<string, WorkerLoaderModule | string>; |
| 23 | env?: any; |
| 24 | globalOutbound?: Fetcher | null; |
| 25 | tails?: Fetcher[]; |
| 26 | streamingTails?: Fetcher[]; |
| 27 | } |
| 28 | |
| 29 | export type DynamicWorkerEntrypoint<Shape = unknown> = Fetcher & { |
| 30 | [K in keyof Shape]: Shape[K]; |
| 31 | }; |
| 32 | |
| 33 | export interface WorkerStub extends Fetcher { |
| 34 | getEntrypoint<Shape = unknown>(name?: string): DynamicWorkerEntrypoint<Shape>; |
| 35 | } |
| 36 | |
| 37 | export type WorkerLoader = { |
| 38 | Type: WorkerLoaderTypeId; |
| 39 | name: string; |
| 40 | get<Err = never, Req = never>( |
| 41 | name: string | null, |
| 42 | getCode: () => WorkerLoaderWorkerCode | Effect.Effect<WorkerLoaderWorkerCode, Err, Req>, |
| 43 | ): Effect.Effect<WorkerStub, Err, Req>; |
| 44 | load(code: WorkerLoaderWorkerCode): Effect.Effect<WorkerStub, never, RuntimeContext>; |
| 45 | }; |
| 46 | |
| 47 | /** |
| 48 | * Effect returned by `WorkerLoader(name)`. |
| 49 | * |
| 50 | * It is a real `Effect` — `yield* WorkerLoader(name)` inside a Worker init |
| 51 | * attaches the binding and resolves the runtime handle — but it also carries |
| 52 | * the `~alchemy/Kind` marker statically, so when it is declared on a Worker's |
| 53 | * `env` the binding machinery recognises it as a `worker_loader` binding |
| 54 | * (`isWorkerLoader`) instead of running it. Every env-resolution site that |
| 55 | * branches on "is this a runnable Effect?" therefore checks `~alchemy/Kind` |
| 56 | * (via `isWorkerLoader` or `isYieldableEffectLike`) before `Effect.isEffect`. |
| 57 | */ |
| 58 | export interface WorkerLoaderEffect extends Effect.Effect< |
| 59 | WorkerLoader, |
| 60 | never, |
| 61 | WorkerEnvironment | Worker |
| 62 | > { |
| 63 | "~alchemy/Kind": WorkerLoaderTypeId; |
| 64 | "~alchemy/Name": string; |
| 65 | name: string; |
| 66 | } |
| 67 | |
| 68 | export const isWorkerLoader = (value: unknown): value is WorkerLoader => |
| 69 | typeof value === "object" && |
| 70 | value !== null && |
| 71 | "~alchemy/Kind" in value && |
| 72 | (value as WorkerLoaderEffect)["~alchemy/Kind"] === WorkerLoaderTypeId; |
| 73 | |
| 74 | export interface WorkerLoaderClass extends Context.Service<WorkerLoader, WorkerLoader> { |
| 75 | (name?: string): WorkerLoaderEffect; |
| 76 | layer(loader: WorkerLoader): Layer.Layer<WorkerLoader>; |
| 77 | layer(id: string): Layer.Layer<WorkerLoader>; |
| 78 | } |
| 79 | |
| 80 | /** |
| 81 | * Load and run ephemeral Workers at runtime from inline JavaScript |
| 82 | * modules. |
| 83 | * |
| 84 | * `WorkerLoader` registers a `worker_loader` binding on the |
| 85 | * parent Worker at deploy time. At runtime you call `.load()` with |
| 86 | * inline module source code and get back a fully typed Worker |
| 87 | * instance you can `fetch` or call RPC methods on. Each loaded |
| 88 | * Worker runs in its own isolate with full sandboxing. |
| 89 | * |
| 90 | * This is useful for evaluating user-provided code, running |
| 91 | * untrusted plugins, or dynamically generating Workers from |
| 92 | * templates. |
| 93 | * |
| 94 | * |
| 95 | * ### Creating a Loader |
| 96 | * Yield `Cloudflare.WorkerLoader(name)` in your Worker's init |
| 97 | * phase to register the binding and get back a runtime handle. The |
| 98 | * string argument becomes the binding name on the deployed Worker. |
| 99 | * |
| 100 | * **Example:** Registering a loader (effect-native Worker) |
| 101 | * ```typescript |
| 102 | * import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 103 | * import * as Effect from "effect/Effect"; |
| 104 | * import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 105 | * import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 106 | * import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 107 | * |
| 108 | * export default class EvalWorker extends Cloudflare.Worker<EvalWorker>()( |
| 109 | * "EvalWorker", |
| 110 | * { main: import.meta.url }, |
| 111 | * Effect.gen(function* () { |
| 112 | * // Registers the `worker_loader` binding on this Worker |
| 113 | * const loader = yield* Cloudflare.WorkerLoader("LOADER"); |
| 114 | * |
| 115 | * return { |
| 116 | * fetch: Effect.gen(function* () { |
| 117 | * const request = yield* HttpServerRequest; |
| 118 | * const code = yield* request.text; |
| 119 | * |
| 120 | * // Spin up an isolated, sandboxed Worker from inline source. |
| 121 | * const worker = yield* loader.load({ |
| 122 | * compatibilityDate: "2026-08-31", |
| 123 | * mainModule: "worker.js", |
| 124 | * modules: { |
| 125 | * "worker.js": `export default { |
| 126 | * async fetch(req) { |
| 127 | * const result = (0, eval)(await req.text()); |
| 128 | * return new Response(String(result)); |
| 129 | * } |
| 130 | * }`, |
| 131 | * }, |
| 132 | * globalOutbound: null, // block outbound network access |
| 133 | * }); |
| 134 | * |
| 135 | * // Call the loaded Worker over Effect-native HTTP. |
| 136 | * const response = yield* worker.fetch( |
| 137 | * HttpClientRequest.post("https://worker/").pipe( |
| 138 | * HttpClientRequest.bodyText(code), |
| 139 | * ), |
| 140 | * ); |
| 141 | * return HttpServerResponse.fromClientResponse(response); |
| 142 | * }), |
| 143 | * }; |
| 144 | * }), |
| 145 | * ) {} |
| 146 | * ``` |
| 147 | * |
| 148 | * **Example:** Declaring on env (async Worker) |
| 149 | * ```typescript |
| 150 | * export const Worker = Cloudflare.Worker("Worker", { |
| 151 | * main: "./src/worker.ts", |
| 152 | * env: { LOADER: Cloudflare.WorkerLoader() }, |
| 153 | * }); |
| 154 | * |
| 155 | * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>; |
| 156 | * |
| 157 | * // worker.ts |
| 158 | * export default { |
| 159 | * async fetch(req: Request, env: WorkerEnv) { |
| 160 | * const worker = env.LOADER.load({ |
| 161 | * compatibilityDate: "2026-08-31", |
| 162 | * mainModule: "worker.js", |
| 163 | * modules: { "worker.js": "export default { fetch: () => new Response('ok') }" }, |
| 164 | * }); |
| 165 | * return worker.getEntrypoint().fetch(req); |
| 166 | * }, |
| 167 | * }; |
| 168 | * ``` |
| 169 | * |
| 170 | * ### Loading a Worker |
| 171 | * Call `loader.load()` with a compatibility date, a main module |
| 172 | * name, and a map of module names to source code strings. The |
| 173 | * returned instance exposes `.fetch()` for HTTP and RPC methods |
| 174 | * for named entrypoints. |
| 175 | * |
| 176 | * **Example:** Loading and calling a dynamic Worker |
| 177 | * ```typescript |
| 178 | * const worker = loader.load({ |
| 179 | * compatibilityDate: "2026-08-31", |
| 180 | * mainModule: "worker.js", |
| 181 | * modules: { |
| 182 | * "worker.js": `export default { |
| 183 | * async fetch(request) { |
| 184 | * return new Response("Hello from dynamic worker!"); |
| 185 | * } |
| 186 | * }`, |
| 187 | * }, |
| 188 | * }); |
| 189 | * |
| 190 | * const response = yield* worker.fetch( |
| 191 | * HttpClientRequest.get("https://worker/"), |
| 192 | * ); |
| 193 | * ``` |
| 194 | * |
| 195 | * ### Caching a Worker |
| 196 | * Call `loader.get(id, getCode)` to address a dynamic Worker by |
| 197 | * name. If an isolate with that id is already warm it is reused; |
| 198 | * `getCode` runs only on a cold start. The returned stub is a |
| 199 | * `WorkerStub`: call `.fetch()` on it directly, or |
| 200 | * `.getEntrypoint()` for a named export. |
| 201 | * |
| 202 | * **Example:** Loading a cached dynamic Worker |
| 203 | * ```typescript |
| 204 | * const worker = yield* loader.get("eval", () => ({ |
| 205 | * compatibilityDate: "2026-08-31", |
| 206 | * mainModule: "worker.js", |
| 207 | * modules: { |
| 208 | * "worker.js": `export default { |
| 209 | * async fetch() { |
| 210 | * return new Response("cached"); |
| 211 | * } |
| 212 | * }`, |
| 213 | * }, |
| 214 | * })); |
| 215 | * |
| 216 | * const response = yield* worker.fetch( |
| 217 | * HttpClientRequest.get("https://worker/"), |
| 218 | * ); |
| 219 | * ``` |
| 220 | * |
| 221 | * ### Sandboxing |
| 222 | * Set `globalOutbound` to `null` to block all outbound network |
| 223 | * access from the dynamic Worker, or pass an RPC stub to intercept |
| 224 | * and proxy outbound requests. |
| 225 | * |
| 226 | * **Example:** Blocking outbound access |
| 227 | * ```typescript |
| 228 | * const worker = loader.load({ |
| 229 | * compatibilityDate: "2026-08-31", |
| 230 | * mainModule: "worker.js", |
| 231 | * modules: { |
| 232 | * "worker.js": `export default { |
| 233 | * async fetch(req) { |
| 234 | * // fetch() calls from here will fail |
| 235 | * return new Response("sandboxed"); |
| 236 | * } |
| 237 | * }`, |
| 238 | * }, |
| 239 | * globalOutbound: null, |
| 240 | * }); |
| 241 | * ``` |
| 242 | * |
| 243 | * ### Named Entrypoints |
| 244 | * If the dynamic Worker exports named entrypoints, use |
| 245 | * `.getEntrypoint(name)` to get a typed stub for calling its |
| 246 | * methods. |
| 247 | * |
| 248 | * **Example:** Calling a named entrypoint |
| 249 | * ```typescript |
| 250 | * const worker = loader.load({ ... }); |
| 251 | * const api = worker.getEntrypoint<{ greet: (name: string) => Effect.Effect<string> }>("api"); |
| 252 | * const greeting = yield* api.greet("world"); |
| 253 | * ``` |
| 254 | * |
| 255 | * @resource |
| 256 | * @product Workers |
| 257 | * @category Workers & Compute |
| 258 | */ |
| 259 | export const WorkerLoader: WorkerLoaderClass = Object.assign( |
| 260 | taggedFunction(Context.Service()("Cloudflare.WorkerLoader"), (name = "LOADER") => |
| 261 | Object.assign( |
| 262 | Effect.gen(function* () { |
| 263 | yield* (yield* Worker).bind`${name}`({ |
| 264 | bindings: [{ type: "worker_loader", name }], |
| 265 | }); |
| 266 | |
| 267 | const loader: _WorkerLoader = yield* Effect.all([WorkerEnvironment, ALCHEMY_PHASE]).pipe( |
| 268 | Effect.flatMap(([env, phase]) => { |
| 269 | if (env === undefined || phase === "plan") { |
| 270 | return Effect.succeed(undefined as any); |
| 271 | } |
| 272 | const loader = env[name]; |
| 273 | if (!loader) { |
| 274 | return Effect.die(new Error(`WorkerLoader '${name}' not found in env`)); |
| 275 | } |
| 276 | return Effect.succeed(loader); |
| 277 | }), |
| 278 | ); |
| 279 | |
| 280 | return { |
| 281 | Type: WorkerLoaderTypeId, |
| 282 | name, |
| 283 | load: (options) => |
| 284 | Effect.sync(() => wrapWorkerStub(loader.load(unwrapWorkerLoader(options)))), |
| 285 | get: <Err = never, Req = never>( |
| 286 | name: string | null, |
| 287 | getCode: () => WorkerLoaderWorkerCode | Effect.Effect<WorkerLoaderWorkerCode, Err, Req>, |
| 288 | ) => |
| 289 | Effect.flatMap(Effect.context<Req>(), (context) => |
| 290 | Effect.sync(() => |
| 291 | // Native get() returns a WorkerStub, not a Fetcher. The |
| 292 | // stub's fetcher is getEntrypoint(); wrapping the stub |
| 293 | // itself as a Fetcher makes worker.fetch throw |
| 294 | // "fetcher.fetch is not a function" (#1382). |
| 295 | wrapWorkerStub( |
| 296 | loader.get(name, () => |
| 297 | asEffect(getCode()).pipe( |
| 298 | Effect.provide(context), |
| 299 | Effect.map(unwrapWorkerLoader), |
| 300 | Effect.runPromise, |
| 301 | ), |
| 302 | ), |
| 303 | ), |
| 304 | ), |
| 305 | ), |
| 306 | } satisfies WorkerLoader; |
| 307 | }), |
| 308 | { |
| 309 | "~alchemy/Name": name, |
| 310 | "~alchemy/Kind": WorkerLoaderTypeId, |
| 311 | name, |
| 312 | }, |
| 313 | ), |
| 314 | ), |
| 315 | { |
| 316 | layer: (loader: WorkerLoader) => |
| 317 | Layer.succeed(Context.Service()("Cloudflare.WorkerLoader"), loader), |
| 318 | }, |
| 319 | ) as any; |
| 320 | |
| 321 | /** |
| 322 | * Convert the Effect-level worker code into the shape the native |
| 323 | * `env.LOADER.get()` API expects, unwrapping wrapped `Fetcher`s to their raw |
| 324 | * Cloudflare fetchers. `globalOutbound: null` (disable network access for the |
| 325 | * dynamic worker) must survive as `null` — `?.raw` alone would coerce it to |
| 326 | * `undefined`, which the runtime treats as "default outbound", silently |
| 327 | * re-enabling network access for workers meant to be sandboxed (#746). |
| 328 | */ |
| 329 | const unwrapWorkerLoader = (loader: WorkerLoaderWorkerCode) => ({ |
| 330 | ...loader, |
| 331 | globalOutbound: loader.globalOutbound === null ? null : loader.globalOutbound?.raw, |
| 332 | tails: loader.tails?.map((t) => t.raw), |
| 333 | streamingTails: loader.streamingTails?.map((t) => t.raw), |
| 334 | }); |
| 335 | |
| 336 | const wrapDynamicWorkerEntrypoint = <Shape>(raw: any): DynamicWorkerEntrypoint<Shape> => |
| 337 | Object.assign(makeRpcStub<any>(raw), fromCloudflareFetcher(raw)); |
| 338 | |
| 339 | const wrapWorkerStub = (raw: any): WorkerStub => { |
| 340 | const defaultEntrypoint = fromCloudflareFetcher(raw.getEntrypoint()); |
| 341 | return { |
| 342 | ...defaultEntrypoint, |
| 343 | getEntrypoint: <Shape>(name?: string) => |
| 344 | wrapDynamicWorkerEntrypoint<Shape>(name ? raw.getEntrypoint(name) : raw.getEntrypoint()), |
| 345 | }; |
| 346 | }; |