@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 369 lines 14.1 KB
Raw
1 import type { BindingHook, BindingServices } from "@alchemy.run/cloudflare-runtime/core";
2 import {
3 Ai,
4 AiSearch,
5 AnalyticsEngine,
6 Artifacts,
7 Assets,
8 Browser,
9 D1,
10 Data,
11 DispatchNamespace,
12 DurableObjectNamespace,
13 Flagship,
14 Hyperdrive,
15 Images,
16 Json,
17 KvNamespace,
18 MtlsCertificate,
19 Pipelines,
20 Queue,
21 R2Bucket,
22 RateLimit,
23 SecretKey,
24 SecretsStore,
25 SendEmail,
26 Service,
27 Stream as StreamSim,
28 Text,
29 Vectorize,
30 VersionMetadata,
31 VpcService,
32 WasmModule,
33 WorkerLoader,
34 Workflows,
35 } from "@alchemy.run/cloudflare-runtime/core/bindings";
36 import * as Effect from "effect/Effect";
37 import * as Redacted from "effect/Redacted";
38 import * as Schema from "effect/Schema";
39 import { isInstantNamespaceLocalId } from "../KV/InstantNamespaceLocal.ts";
40 import { isLocalId } from "../LocalRuntime.ts";
41 import { LOCAL_R2_S3_CREDENTIALS, LOCAL_R2_S3_PATH } from "../R2/LocalS3.ts";
42 import type { WorkerBinding } from "./WorkerBinding.ts";
43
44 export class WorkerValidationError extends Schema.TaggedError<WorkerValidationError>()(
45 "WorkerValidationError",
46 {
47 message: Schema.String,
48 hint: Schema.optional(Schema.String),
49 value: Schema.Unknown,
50 },
51 ) {}
52
53 export const toRuntimeBinding = Effect.fn(function* (
54 b: WorkerBinding,
55 /**
56 * Dev-only channel from the Worker's binding data (see the `devRemote`
57 * member of the Worker binding contract): binding name → opt-out of local
58 * emulation for the capabilities that support it (browser / images /
59 * stream / send_email).
60 */
61 devRemote?: Record<string, boolean>,
62 ) {
63 const unsupported = () =>
64 WorkerValidationError.make({
65 message: `${b.type} bindings are not supported in local mode`,
66 value: b,
67 });
68 switch (b.type) {
69 case "ai":
70 return Ai.remote(b.name);
71 case "ai_search":
72 return AiSearch.remote(b.name, b.instanceName);
73 case "ai_search_namespace":
74 return AiSearch.remoteNamespace(b.name, b.namespace);
75 case "analytics_engine":
76 return AnalyticsEngine.local(b.name, b.dataset);
77 case "artifacts":
78 return Artifacts.remote(b.name, b.namespace);
79 case "assets":
80 return Assets.local(b.name);
81 case "browser":
82 // Local emulation launches a real headless Chrome on this machine and
83 // proxies the Browser Rendering session protocol to its CDP endpoint;
84 // `Alchemy.remote()` opts into the real service instead.
85 return devRemote?.[b.name] ? Browser.remote(b.name) : Browser.local({ binding: b.name });
86 case "d1":
87 // A `dev:` id belongs to a locally-emulated database (local D1
88 // provider); a real id is a live database the dev worker proxies to
89 // (e.g. the resource opted out of emulation via `Alchemy.remote()`).
90 return isLocalId(b.databaseId)
91 ? D1.local({ binding: b.name, id: b.databaseId })
92 : D1.remote(b.name, b.databaseId);
93 case "data_blob":
94 return Data.local(b.name, Buffer.from(b.part));
95 case "dispatch_namespace":
96 return DispatchNamespace.remote({
97 binding: b.name,
98 namespace: b.namespace,
99 });
100 case "durable_object_namespace":
101 return DurableObjectNamespace.local({
102 binding: b.name,
103 className: b.className,
104 scriptName: b.scriptName,
105 uniqueKey: b.namespaceId ?? encodeURIComponent(`${b.scriptName!}-${b.className}`),
106 });
107 case "flagship":
108 // A `dev:` id belongs to a locally-emulated app (the local Flag
109 // provider seeds its definitions into the simulator); a real id is a
110 // live app the dev worker proxies to (`Alchemy.remote()`).
111 return isLocalId(b.appId)
112 ? Flagship.local({ binding: b.name, appId: b.appId })
113 : Flagship.remote(b.name, b.appId);
114 case "hyperdrive":
115 return Hyperdrive.local(b.name, b.id);
116 case "images":
117 // Local emulation runs transforms via Sharp on this machine and stores
118 // hosted images in a local KV-backed store; `Alchemy.remote()`
119 // opts into the real Images service instead.
120 return devRemote?.[b.name] ? Images.remote(b.name) : Images.local({ binding: b.name });
121 case "inherit":
122 return yield* unsupported();
123 case "json":
124 return Json.local(b.name, b.json);
125 case "k2":
126 // Miniflare has no K2 simulation and no remote proxy for it yet.
127 return yield* WorkerValidationError.make({
128 message: `K2 binding "${b.name}" is not supported in local mode: K2 has no local simulation.`,
129 hint: "Run K2 producers against a deployed Worker (alchemy deploy).",
130 value: b,
131 });
132 case "kv_namespace":
133 // A `dev:` id belongs to a locally-emulated namespace; a real id is
134 // a live namespace the dev worker proxies to.
135 return isLocalId(b.namespaceId)
136 ? KvNamespace.local({
137 binding: b.name,
138 id: b.namespaceId,
139 mode: isInstantNamespaceLocalId(b.namespaceId) ? "instant" : undefined,
140 })
141 : KvNamespace.remote(b.name, b.namespaceId);
142 case "mtls_certificate":
143 return MtlsCertificate.remote(b.name, b.certificateId);
144 case "pipelines":
145 return Pipelines.remote(b.name, b.pipeline);
146 case "plain_text":
147 return Text.local(b.name, b.text);
148 case "queue": {
149 // A real queueId belongs to an `Alchemy.remote()` queue. Queue bindings
150 // are NOT supported in Cloudflare's remote/preview sessions — a
151 // platform limitation (cloudflare/workers-sdk#9929) — so live
152 // production goes through the deployed shim worker registered at
153 // eval time (see `Queues/QueueShim.ts`): the local binding targets a
154 // forwarder service that relays the queue wire protocol to the shim
155 // over HTTPS with a bearer token.
156 if (b.queueId !== undefined && !isLocalId(b.queueId)) {
157 const url = b.shim?.url;
158 const token = b.shim?.token;
159 if (url === undefined || token === undefined) {
160 // Defensive: binding data produced by current eval always carries
161 // the shim for this mode combination.
162 return yield* WorkerValidationError.make({
163 message:
164 `Queue binding "${b.name}" targets a live queue ` +
165 "(Alchemy.remote()) but no producer shim was registered for it — " +
166 "re-deploy, or remove remote() from the queue (local emulation).",
167 value: b,
168 });
169 }
170 return Queue.remote({
171 binding: b.name,
172 queueName: b.queueName,
173 url,
174 token: typeof token === "string" ? token : Redacted.value(token),
175 });
176 }
177 return Queue.local({
178 binding: b.name,
179 queueName: b.queueName,
180 });
181 }
182 case "r2_bucket":
183 // A `dev:`-prefixed bucket name belongs to a locally-emulated bucket
184 // (R2 has no opaque id — the name is the identity); a real name is a
185 // live bucket the dev worker proxies to. Local buckets are also served
186 // on the Worker's local S3 endpoint, so presigned URLs and S3 clients
187 // work in dev without extra configuration.
188 return isLocalId(b.bucketName)
189 ? R2Bucket.local({
190 binding: b.name,
191 id: b.bucketName,
192 s3Credentials: LOCAL_R2_S3_CREDENTIALS,
193 })
194 : R2Bucket.remote(b.name, b.bucketName, b.jurisdiction);
195 case "ratelimit":
196 return RateLimit.local({
197 binding: b.name,
198 simple: b.simple,
199 namespaceId: b.namespaceId,
200 });
201 case "secret_key":
202 // workerd imports the key natively: raw material passes through as
203 // base64, pkcs8/spki base64 DER is PEM-wrapped, and JWK objects are
204 // serialized — all handled by the hook.
205 return SecretKey.local({
206 binding: b.name,
207 format: b.format,
208 algorithm: b.algorithm,
209 usages: b.usages,
210 keyBase64: b.keyBase64,
211 keyJwk: b.keyJwk,
212 });
213 case "secret_text":
214 return Text.local(b.name, b.text);
215 case "secrets_store_secret":
216 // A `dev:` store id belongs to a locally-emulated Secrets Store
217 // (local Store/Secret providers seed the simulator); a real id is a
218 // live secret the dev worker proxies to (`Alchemy.remote()`).
219 return isLocalId(b.storeId)
220 ? SecretsStore.local({
221 binding: b.name,
222 storeId: b.storeId,
223 secretName: b.secretName,
224 })
225 : SecretsStore.remote(b.name, b.storeId, b.secretName);
226 case "send_email":
227 // Local emulation validates and persists sent mail as `.eml` files
228 // under the local storage's `email/` dir; `Alchemy.remote()` on the
229 // descriptor opts into the real Email service instead.
230 return SendEmail[devRemote?.[b.name] ? "remote" : "local"]({
231 binding: b.name,
232 destinationAddress: b.destinationAddress,
233 allowedDestinationAddresses: b.allowedDestinationAddresses,
234 allowedSenderAddresses: b.allowedSenderAddresses,
235 });
236 case "self_service":
237 // A service binding to the worker itself: served in-process by the
238 // runtime's self service (bypasses the assets middleware), matching
239 // the production `service: <own name>` lowering.
240 return Service.self(b.name, { entrypoint: b.entrypoint, props: b.props });
241 case "service":
242 return Service.local({
243 binding: b.name,
244 scriptName: b.service,
245 entrypoint: b.entrypoint,
246 props: b.props,
247 });
248 case "stream":
249 // Local emulation stores videos in a local simulator (no transcoding,
250 // no signed URLs) and serves each video's `preview` URL at
251 // /cdn-cgi/mf/stream/<id>/watch on the dev URL; `Alchemy.remote()`
252 // opts into the real Stream service instead.
253 return devRemote?.[b.name] ? StreamSim.remote(b.name) : StreamSim.local({ binding: b.name });
254 case "text_blob":
255 return Data.local(b.name, Buffer.from(b.part));
256 case "vectorize":
257 return Vectorize.remote(b.name, b.indexName);
258 case "version_metadata":
259 return VersionMetadata.local(b.name);
260 case "vpc_service":
261 // A VPC service tunnels into a private network — nothing to emulate
262 // locally, so the dev worker always proxies to the real service
263 // through the remote-binding bridge.
264 return VpcService.remote(b.name, b.serviceId);
265 case "wasm_module":
266 return WasmModule.local(b.name, Buffer.from(b.part));
267 case "worker_loader":
268 return WorkerLoader.local(b.name);
269 case "workflow":
270 return Workflows.local({
271 binding: b.name,
272 workflowName: b.workflowName,
273 className: b.className,
274 scriptName: b.scriptName,
275 });
276 default:
277 return yield* unsupported();
278 }
279 });
280
281 /**
282 * Turns the serializable half of a local Worker configuration into the
283 * cloudflare-runtime binding hooks consumed by `Runtime.start`.
284 *
285 * Kept in a leaf module, independent of the provider, so a Vite child
286 * process can reconstruct the hooks after receiving plain binding
287 * descriptors from its parent without evaluating the provider's module
288 * graph. Binding hooks themselves are Effects and cannot cross a process
289 * boundary.
290 *
291 * `config.env` must already be resolved to plain values — `Worker.URL`
292 * sentinels substituted with the actual dev-proxy URL by the caller.
293 */
294 export const materializeRuntimeBindings = Effect.fn(function* (
295 config: {
296 name: string;
297 env?: Record<string, unknown>;
298 hasAssets: boolean;
299 bindingDescriptors: WorkerBinding[];
300 /** Binding name → opt-out of local emulation (`Alchemy.remote()`). */
301 devRemote?: Record<string, boolean>;
302 /**
303 * Simulated Cloudflare Access config (`dev: { access: ... }`), lowered
304 * into the `ALCHEMY_DEV_ACCESS` env binding the worker bridge reads to
305 * serve `ctx.access` locally.
306 */
307 devAccess?: { aud?: string; identity?: Record<string, unknown> };
308 },
309 options: {
310 accountId: string;
311 selfUrl: string | undefined;
312 stack: { name: string; stage: string };
313 },
314 ) {
315 // Resource-backed env entries (e.g. `env: { KV: namespace }`) are
316 // represented by their binding descriptor (same name) — don't ALSO
317 // serialize the resolved attributes as a duplicate json binding.
318 const descriptorNames = new Set(config.bindingDescriptors.map((descriptor) => descriptor.name));
319 const workerBindings: BindingHook<BindingServices>[] = [
320 Text.local("ALCHEMY_PHASE", "runtime"),
321 Text.local("ALCHEMY_WORKER_NAME", config.name),
322 Text.local("ALCHEMY_STACK_NAME", options.stack.name),
323 Text.local("ALCHEMY_STAGE", options.stack.stage),
324 Text.local("ALCHEMY_CLOUDFLARE_ACCOUNT_ID", options.accountId),
325 ...Object.entries(config.env ?? {})
326 .filter(([key]) => !descriptorNames.has(key))
327 .map(([key, value]) => {
328 const unredacted = Redacted.isRedacted(value) ? Redacted.value(value) : value;
329 return typeof unredacted === "string"
330 ? Text.local(key, unredacted)
331 : Json.local(key, unredacted);
332 }),
333 ...(config.hasAssets ? [Assets.local("ASSETS")] : []),
334 ...(config.devAccess !== undefined ? [Json.local("ALCHEMY_DEV_ACCESS", config.devAccess)] : []),
335 ];
336 for (const descriptor of config.bindingDescriptors) {
337 if (descriptor.type === "self_url") {
338 // Lowered here rather than in `toRuntimeBinding` — only the caller
339 // knows the worker's own dev-proxy URL.
340 workerBindings.push(Text.local(descriptor.name, options.selfUrl!));
341 continue;
342 }
343 if (descriptor.type === "r2_s3_credentials") {
344 // `Cloudflare.R2.S3Credentials` over a `dev:` bucket: credentials for
345 // this Worker's local S3 endpoint (the dev-proxy URL, known only
346 // here), plus a bucket binding so the runtime serves the bucket on
347 // that endpoint.
348 workerBindings.push(
349 Text.local(
350 descriptor.name,
351 JSON.stringify({
352 endpoint: `${options.selfUrl!}${LOCAL_R2_S3_PATH}`,
353 bucketName: descriptor.bucketName,
354 region: "auto",
355 ...LOCAL_R2_S3_CREDENTIALS,
356 }),
357 ),
358 R2Bucket.local({
359 binding: `${descriptor.name}__BUCKET`,
360 id: descriptor.bucketName,
361 s3Credentials: LOCAL_R2_S3_CREDENTIALS,
362 }),
363 );
364 continue;
365 }
366 workerBindings.push(yield* toRuntimeBinding(descriptor, config.devRemote));
367 }
368 return workerBindings;
369 });