@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 193 lines 8.26 KB
Raw
1 import * as CoreBinding from "alchemy/Binding";
2 import { ProviderModePolicy } from "alchemy/ProviderMode";
3 import { taggedFunction } from "alchemy/Util/effect";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import { SingleShotGen } from "effect/Utils";
7 import type { WorkerBinding } from "./WorkerBinding.ts";
8
9 /**
10 * A Cloudflare **Worker-only binding** — the plain data value produced by
11 * calling a {@link Service} (e.g. `Cloudflare.Images.Images(name)`).
12 *
13 * These bindings (`Browser`, `Images`, `VersionMetadata`, `RateLimit`,
14 * `Artifacts.Namespace`, …) have **no backing cloud resource**; they are only
15 * configuration on a Worker's script metadata. A binding value is therefore
16 * both:
17 *
18 * - **declarable on a Worker's `env`** — `InferEnv` maps the per-binding type to
19 * its native runtime type, and {@link bindWorkerAsyncBindings} emits its wire
20 * spec via {@link toWorkerBinding}, and
21 * - **`yield*`-able inside an Effect-native Worker** — its iterator attaches the
22 * binding to the surrounding Worker and resolves to the runtime client.
23 */
24 export interface Binding<Kind extends string = string, Client = unknown, Service = unknown> {
25 readonly kind: Kind;
26 /** Binding name; the object key when declared on `env`. */
27 readonly name: string;
28 /**
29 * Alchemy-internal: opt this binding out of local emulation in
30 * `alchemy dev` — the `Alchemy.remote()` decoration captured by
31 * {@link pipe} on capabilities with a local simulator (Browser, Images,
32 * Stream). Registered on the host Worker via the binding-data `devRemote`
33 * channel, never on the wire binding itself.
34 */
35 readonly devRemote?: boolean;
36 /** Attach the binding to the surrounding Worker and resolve to the client. */
37 asEffect(): Effect.Effect<Client, never, Service>;
38 [Symbol.iterator](): Generator<Effect.Effect<Client, never, Service>, Client>;
39 /** Wire metadata emitted into the Worker script's `metadata.bindings`. */
40 toWorkerBinding(): WorkerBinding;
41 /**
42 * Lift the binding into an Effect ({@link BindingEffect}) so registration
43 * aspects can decorate it — most notably `Alchemy.remote()`, which opts
44 * the binding out of local emulation in `alchemy dev`:
45 *
46 * ```ts
47 * // Effect-native Worker — resolves to the runtime client:
48 * const browser = yield* Cloudflare.Browser("BROWSER").pipe(Alchemy.remote());
49 *
50 * // async Worker env — declares the decorated binding:
51 * env: { IMAGES: Cloudflare.Images.Images("IMAGES").pipe(Alchemy.remote()) }
52 * ```
53 */
54 pipe(): BindingEffect<this>;
55 pipe<A>(ab: (self: BindingEffect<this>) => A): A;
56 pipe<A, B>(ab: (self: BindingEffect<this>) => A, bc: (a: A) => B): B;
57 pipe<A, B, C>(ab: (self: BindingEffect<this>) => A, bc: (a: A) => B, cd: (b: B) => C): C;
58 }
59
60 /**
61 * A Worker-only {@link Binding} lifted into an Effect by {@link Binding.pipe},
62 * with the ambient {@link ProviderModePolicy} (`Alchemy.remote()`) captured
63 * when it runs.
64 *
65 * Context-adaptive resolution: inside an Effect-native Worker (where the
66 * binding's implementation layer is provided) it registers the binding on the
67 * host and resolves to the runtime `Client` — same one-`yield*` shape as the
68 * bare binding value. Anywhere else (an async Worker's `env`, resolved by the
69 * engine) it resolves to the decorated binding *value*; the
70 * `"~alchemy/Binding"` brand lets `InferEnv` map it to the native runtime
71 * type.
72 */
73 export interface BindingEffect<B extends Binding<any, any, any>> extends Effect.Effect<
74 B extends Binding<any, infer Client, any> ? Client : never,
75 never,
76 B extends Binding<any, any, infer Service> ? Service : never
77 > {
78 readonly "~alchemy/Kind": "Cloudflare.Workers.BindingEffect";
79 readonly "~alchemy/Binding": B;
80 }
81
82 /** Any {@link BindingEffect} — the arm admitted by a Worker's `env`. */
83 export type AnyBindingEffect = BindingEffect<Binding<any, any, any>>;
84
85 /**
86 * The fused tag + callable + type for a Worker-only binding — the same
87 * single-identifier shape as core {@link CoreBinding.Service}, specialized so
88 * the callable produces a {@link Binding} value instead of binding a resource.
89 *
90 * `interface X extends Binding.Service<X, Id, Client>` declares the type;
91 * `const X = Binding.Service<X>({ … })` produces the value that is at once the
92 * Context tag (usable in `Layer.effect(X, …)` / `Effect.provide`), the callable
93 * (`X(props)` → a {@link Binding}), and carries the type.
94 *
95 * ```ts
96 * import * as Binding from "../Workers/Binding.ts";
97 *
98 * export interface Images extends Binding.Service<Images, typeof Id, Client> {
99 * (props?: ImagesProps): Binding.Binding<typeof Id, Client, Images>;
100 * }
101 *
102 * export const Images = Binding.Service<Images>({
103 * id: Id,
104 * defaultName: "IMAGES",
105 * toWorkerBinding: (b) => ({ type: "images", name: b.name }),
106 * });
107 * ```
108 */
109 export interface Service<Self, Id extends string, Client> extends CoreBinding.Service<
110 Self,
111 Id,
112 (binding: Binding<Id, Client, Self>) => Effect.Effect<Client>
113 > {}
114
115 type AnyService = { readonly key: string } & ((...args: any[]) => any);
116
117 /**
118 * Build the fused tag + callable value for a Worker-only binding.
119 *
120 * `Self` (the per-binding interface) supplies the tag `id` (`Self["key"]`); the
121 * binding's `Payload` (extra fields beyond `name`, e.g. RateLimit's
122 * `namespaceId`/`simple`) is inferred from `parse`. Omit `parse` for name-only
123 * bindings — `name` is read from the first arg's `.name` property.
124 */
125 export const Service = <
126 Self extends AnyService,
127 Payload extends object = Record<never, never>,
128 >(config: {
129 /** Tag key + binding `kind` (one identifier for both). */
130 readonly id: Self["key"] & string;
131 /** Default binding name when `props` omits one. */
132 readonly defaultName: string;
133 /**
134 * Derive `name` + payload from the constructor args. Omit for name-only
135 * bindings — `name` is then the first (string) arg, the binding's logical id.
136 */
137 readonly parse?: (...args: any[]) => { name?: string } & Payload;
138 /** Build the wire binding spec from the resolved binding value. */
139 readonly toWorkerBinding: (binding: { readonly name: string } & Payload) => WorkerBinding;
140 }): Self => {
141 const tag = CoreBinding.Service<Self & { kind: "Service"; key: string }>(config.id as never);
142 const bind = tag as unknown as (binding: unknown) => Effect.Effect<unknown>;
143
144 const make = (data: Record<PropertyKey, unknown>) => {
145 const self: Record<PropertyKey, unknown> = { ...data };
146 self.toWorkerBinding = () =>
147 config.toWorkerBinding(self as never as { name: string } & Payload);
148 self.asEffect = () => bind(self);
149 self[Symbol.iterator] = () => new SingleShotGen(bind(self));
150 // The lifted form (`BindingEffect`): capture the ambient
151 // `ProviderModePolicy` (`Alchemy.remote()` decoration), then resolve
152 // context-adaptively — to the runtime client when the binding's layer is
153 // in context (inside an Effect-native Worker), to the decorated binding
154 // value otherwise (an async Worker's `env`, resolved by the engine).
155 const lifted = Effect.gen(function* () {
156 const policy = yield* ProviderModePolicy;
157 const decorated =
158 policy === undefined || policy === !!data.devRemote
159 ? self
160 : make({ ...data, devRemote: policy || undefined });
161 const impl = yield* Effect.serviceOption(tag as never);
162 return Option.isSome(impl)
163 ? yield* (impl.value as (b: unknown) => Effect.Effect<unknown>)(decorated)
164 : decorated;
165 });
166 self.pipe = (...fns: Array<(value: unknown) => unknown>) =>
167 fns.reduce((acc, fn) => fn(acc), lifted as unknown);
168 return self;
169 };
170
171 const construct = (...args: unknown[]) => {
172 const { name, ...payload } =
173 config.parse?.(...args) ??
174 ({ name: args[0] as string | undefined } as {
175 name?: string;
176 } & Payload);
177 return make({
178 kind: config.id,
179 name: name ?? config.defaultName,
180 ...payload,
181 });
182 };
183
184 return taggedFunction(tag as never, construct as never) as unknown as Self;
185 };
186
187 /** Structural guard for any Worker-only {@link Binding}. */
188 export const isBinding = (value: unknown): value is Binding =>
189 typeof value === "object" &&
190 value !== null &&
191 "kind" in value &&
192 typeof (value as { toWorkerBinding?: unknown }).toWorkerBinding === "function" &&
193 typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === "function";