@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, 04:45 UTC

main
ts 1,577 lines 60.1 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { Dependencies } from "alchemy/Dependencies";
3 import type { HttpEffect } from "alchemy/Http";
4 import type { Input } from "alchemy/Input";
5 import * as Output from "alchemy/Output";
6 import { ALCHEMY_PHASE } from "alchemy/Phase";
7 import type { MainRpc, PlatformServices } from "alchemy/Platform";
8 import type { RuntimeContext } from "alchemy/RuntimeContext";
9 import { effectClass, taggedFunction } from "alchemy/Util/effect";
10 import { asEffect } from "alchemy/Util/types";
11 import * as Context from "effect/Context";
12 import * as Effect from "effect/Effect";
13 import type { HttpServerError } from "effect/http/HttpServerError";
14 import * as HttpServerRequest from "effect/http/HttpServerRequest";
15 import * as HttpServerResponse from "effect/http/HttpServerResponse";
16 import * as Layer from "effect/Layer";
17 import * as Predicate from "effect/Predicate";
18 import type { Scope } from "effect/Scope";
19 import type { Container } from "../Containers/Container.ts";
20 import { DurableObjectState, fromDurableObjectState } from "./DurableObjectState.ts";
21 import { makeRpcStub, type RpcErrorClass } from "./Rpc.ts";
22 import { type WebSocket } from "./WebSocket.ts";
23 import { isWorker, Worker, WorkerEnvironment, type WorkerServices } from "./Worker.ts";
24
25 export interface DurableObjectExport {
26 readonly kind: "durableObject";
27 readonly constructor: Effect.Effect<
28 Effect.Effect<DurableObjectShape, never, RuntimeContext>,
29 never,
30 DurableObjectState
31 >;
32 readonly services: Context.Context<never>;
33 }
34
35 export const isDurableObjectExport = (value: unknown): value is DurableObjectExport =>
36 typeof value === "object" && (value as any)?.kind === "durableObject";
37
38 export type DurableObjectId = cf.DurableObjectId;
39 export type DurableObjectJurisdiction = cf.DurableObjectJurisdiction;
40 export type DurableObjectGetDurableObjectOptions = cf.DurableObjectNamespaceGetDurableObjectOptions;
41 /**
42 * The regions a Durable Object can be *hinted* toward at creation —
43 * `"wnam"`, `"enam"`, `"sam"`, `"weur"`, `"eeur"`, `"apac"`, `"oc"`, … See
44 * the "Placing a Durable Object in a Region" section on {@link DurableObject}.
45 */
46 export type DurableObjectLocationHint = cf.DurableObjectLocationHint;
47
48 export type AlarmInvocationInfo = cf.AlarmInvocationInfo;
49
50 type TypeId = "Cloudflare.DurableObject";
51 const TypeId = "Cloudflare.DurableObject";
52
53 export const isDurableObjectLike = (value: unknown): value is DurableObjectLike =>
54 typeof value === "object" && (value as any)?.kind === TypeId;
55
56 export interface DurableObjectLike<Shape = any> {
57 kind: TypeId;
58 name: string;
59 /** @internal phantom */
60 className?: string;
61 /** @internal phantom */
62 scriptName?: Input<string>;
63 /** @internal phantom */
64 transferredFrom?: DurableObjectTransferSource | DurableObjectTransferSource[];
65 /** @internal phantom */
66 storage?: "sqlite" | "legacy-kv";
67 /** @internal Durable Object-managed Containers attached to the class. */
68 containers?: ReadonlyArray<Container.Decl.Any>;
69 /** @internal phantom */
70 Shape?: Shape;
71 }
72
73 export interface DurableObject<Shape = unknown> extends DurableObjectLike<Shape> {
74 Type: TypeId;
75 /** The namespace's logical id. */
76 LogicalId: string;
77 name: string;
78 namespaceId: Output.Output<string>;
79 getByName: (
80 name: string,
81 options?: DurableObjectGetDurableObjectOptions,
82 ) => DurableObjectStub<Shape>;
83 newUniqueId: () => DurableObjectId;
84 idFromName: (name: string) => DurableObjectId;
85 idFromString: (id: string) => DurableObjectId;
86 get: (
87 id: DurableObjectId,
88 options?: DurableObjectGetDurableObjectOptions,
89 ) => DurableObjectStub<Shape>;
90 /**
91 * A view of this namespace whose objects are created and stored only inside
92 * the given jurisdiction (e.g. `"eu"`). The same name addresses a different
93 * object than it does in the unrestricted namespace.
94 *
95 * Enforced when deployed, not emulated in `alchemy dev`: local workerd does
96 * not implement jurisdictions, so there this returns the unrestricted
97 * namespace, and the same name addresses the same object in both.
98 *
99 * @example
100 * ```typescript
101 * const room = rooms.jurisdiction("eu").getByName(roomId);
102 * ```
103 */
104 jurisdiction: (jurisdiction: DurableObjectJurisdiction) => DurableObject<Shape>;
105 }
106
107 export interface DurableObjectShape {
108 fetch?: HttpEffect<DurableObjectState | RuntimeContext>;
109 alarm?: (alarmInfo?: AlarmInvocationInfo) => Effect.Effect<void, never, RuntimeContext>;
110 webSocketMessage?: (socket: WebSocket, message: string | ArrayBuffer) => Effect.Effect<void>;
111 webSocketClose?: (
112 socket: WebSocket,
113 code: number,
114 reason: string,
115 wasClean: boolean,
116 ) => Effect.Effect<void>;
117 /**
118 * Called when a hibernatable WebSocket errors. The runtime closes the
119 * socket after this handler; use it to drop the peer's session state.
120 */
121 webSocketError?: (socket: WebSocket, error: unknown) => Effect.Effect<void>;
122 }
123
124 export type DurableObjectServices =
125 | DurableObject
126 | DurableObjectState
127 | DurableObjectScope
128 | WorkerServices
129 | WorkerEnvironment
130 | PlatformServices;
131
132 /**
133 * A reference to the Worker that previously hosted a Durable Object class,
134 * accepted by {@link DurableObjectProps.transferredFrom}:
135 *
136 * - the Worker's **logical id** (same stack + stage) or **physical script
137 * name** (cross-stack) as a string
138 * - the Worker **resource** (`const b = yield* Cloudflare.Worker(...)`)
139 * - the Worker **class** (`transferredFrom: WorkerA`)
140 * - a **thunk** of any of the above (`() => WorkerA`) — use this for
141 * forward references and import cycles; it is evaluated lazily at plan
142 * time, after all modules have loaded
143 * - a string `Output` (e.g. a cross-stack `stackRef`'s worker name)
144 *
145 * Every form is normalized at plan time to a plain identifier: a Worker
146 * reference contributes its logical id, and a same-stack `workerName`
147 * Output contributes its source resource's logical id rather than the
148 * Output itself. Keeping the former host's *value* out of the binding data
149 * matters — consuming its Output would add a dependency edge from the new
150 * host onto the former host, inverting the deploy order the transfer
151 * requires (the new host must upload first).
152 */
153 export type DurableObjectTransferSource =
154 | Input<string>
155 | Worker
156 | Effect.Effect<Worker, any, any>
157 | (() => DurableObjectTransferSource);
158
159 const resolveTransferSourceRef = (
160 source: DurableObjectTransferSource,
161 depth = 0,
162 ): Input<string> => {
163 if (typeof source === "string") {
164 return source;
165 }
166 // A Worker resource — contribute its logical id.
167 if (isWorker(source)) {
168 return source.LogicalId;
169 }
170 // A Worker platform class — carries its logical id statically. (On an
171 // Output proxy this property access yields another Output, never a
172 // string, so the check cannot misfire there.)
173 const logicalId = (source as { LogicalId?: unknown }).LogicalId;
174 if (typeof logicalId === "string") {
175 return logicalId;
176 }
177 // A same-stack Output on a Worker (e.g. `b.workerName`): take the
178 // identity from its provenance, not the value.
179 if (Output.isPropExpr(source)) {
180 const expr = (source as Output.PropExpr<any, any>).expr;
181 if (Output.isResourceExpr(expr) && isWorker(expr.src)) {
182 return expr.src.LogicalId;
183 }
184 }
185 if (Output.isResourceExpr(source) && isWorker(source.src)) {
186 return source.src.LogicalId;
187 }
188 if (Output.isOutput(source)) {
189 // No local resource to take identity from (e.g. a cross-stack
190 // `stackRef`) — the engine resolves the string at deploy time.
191 return source as Input<string>;
192 }
193 if (typeof source === "function" && depth < 8) {
194 return resolveTransferSourceRef((source as () => DurableObjectTransferSource)(), depth + 1);
195 }
196 throw new Error(
197 "Invalid transferredFrom entry: pass the former host's logical id or script name, its Worker class or resource, a thunk of one of those, or a string Output.",
198 );
199 };
200
201 /**
202 * Normalize a `transferredFrom` declaration to plain host identifiers at
203 * plan time. See {@link DurableObjectTransferSource} for the accepted forms
204 * and why Worker references reduce to logical ids instead of Outputs.
205 *
206 * @internal
207 */
208 export const normalizeTransferredFrom = (
209 value: DurableObjectTransferSource | readonly DurableObjectTransferSource[] | undefined,
210 ): Input<string>[] | undefined =>
211 value === undefined
212 ? undefined
213 : (Array.isArray(value)
214 ? (value as readonly DurableObjectTransferSource[])
215 : [value as DurableObjectTransferSource]
216 ).map((source) => resolveTransferSourceRef(source));
217
218 /**
219 * `ns` restricted to `jurisdiction`. Local workerd (`alchemy dev`) does not
220 * implement jurisdictions and throws on `jurisdiction()`, so there the
221 * unrestricted namespace is used, the same way a D1 database, R2 bucket or
222 * Queue declared with a jurisdiction runs unrestricted on the local simulator.
223 */
224 const restrictToJurisdiction = (
225 ns: cf.DurableObjectNamespace | undefined,
226 jurisdiction: DurableObjectJurisdiction,
227 ): cf.DurableObjectNamespace | undefined => {
228 try {
229 return ns?.jurisdiction(jurisdiction);
230 } catch (error) {
231 // workerd's message; a deployed Worker never throws it.
232 if (
233 Predicate.hasProperty(error, "message") &&
234 String(error.message).includes("Jurisdiction restrictions are not implemented")
235 ) {
236 return ns;
237 }
238 throw error;
239 }
240 };
241
242 export interface DurableObjectProps {
243 /**
244 * Name of the exported `DurableObject` class.
245 *
246 * @default name
247 */
248 className?: string;
249 /**
250 * Worker script that hosts the Durable Object class. Omit this when the
251 * namespace is hosted by the Worker that declares the binding.
252 */
253 scriptName?: Input<string> | undefined;
254 /**
255 * The Worker(s) that previously hosted this Durable Object class. When one
256 * of them still holds the namespace, the deploy transfers it — including
257 * all stored objects — from that script to this Worker: this Worker
258 * declares the class `expecting-transfer` in its `exports`, and the former
259 * host commits the move with a `transferred` tombstone.
260 *
261 * Each entry names a former host — see
262 * {@link DurableObjectTransferSource} for the accepted forms: a string
263 * (Worker logical id in this stack + stage, or physical script name for
264 * cross-stack moves), the Worker class or resource itself, or a thunk
265 * (`() => WorkerA`) for forward references. Moving a class is always
266 * declared this way — there is no inference. A list is a host *history*:
267 * as the class moves again, append the previous host so stages that lag
268 * behind (or skipped an intermediate release) still transfer from
269 * wherever their namespace currently lives.
270 *
271 * When no listed host holds the namespace — a fresh stage, or every
272 * transfer already completed — the property is inert and the class is
273 * created fresh (or left as-is), so it is safe to leave in place
274 * indefinitely.
275 */
276 transferredFrom?: DurableObjectTransferSource | DurableObjectTransferSource[] | undefined;
277 /**
278 * Storage backend of the class, as Wrangler's `storage` declares it.
279 * `"legacy-kv"` describes a class created before SQLite-backed Durable
280 * Objects: deploys keep an existing namespace's backend, and Cloudflare
281 * no longer creates new key-value backed namespaces. In `alchemy dev` a
282 * `"legacy-kv"` class has no SQL storage, as on Cloudflare.
283 *
284 * @default "sqlite"
285 */
286 storage?: "sqlite" | "legacy-kv" | undefined;
287 /**
288 * Tagged-error classes this Durable Object's RPC methods can fail with.
289 *
290 * Effect failures crossing the Worker↔DO RPC boundary are serialized to
291 * plain `{ _tag, ...fields }` objects; declaring the classes here lets
292 * the calling side reconstruct real instances (both sides import this
293 * same class declaration, so the schema is shared by construction) —
294 * `Effect.catchTag`, `instanceof`, and schema encoders (e.g. HttpApi
295 * error responses) then all see the class the DO actually failed with.
296 *
297 * ```typescript
298 * export class Repo extends Cloudflare.DurableObject<Repo, RepoShape>()(
299 * "Repo",
300 * { errors: [RepoNotFound, StoreError] },
301 * ) {}
302 * ```
303 */
304 errors?: ReadonlyArray<RpcErrorClass> | undefined;
305 // environment?: string | undefined;
306 // sqlite?: boolean | undefined;
307 // namespaceId?: string | undefined;
308 }
309
310 /**
311 * Props of an async Worker's Durable Object binding,
312 * `Cloudflare.DurableObject(className, props)` in `env`.
313 */
314 export interface DurableObjectBindingProps extends DurableObjectProps {
315 /**
316 * Durable Object-managed Containers (`schedulingPolicy: "durable_object"`)
317 * this class starts. Each adds its image to the class's container
318 * application under the Container's id, read at runtime from
319 * `ctx.container.images`. A Container may be listed by several classes.
320 *
321 * Only for a plain (async) Durable Object class the Worker hosts.
322 * Effect-native Durable Objects `yield*` their Containers instead; listing
323 * Containers for one fails with `DurableObjectContainersOnEffectNativeClass`.
324 *
325 * ```typescript
326 * env: {
327 * AGENT: Cloudflare.DurableObject("Agent", { containers: [Node, Python] }),
328 * }
329 * ```
330 */
331 containers?: ReadonlyArray<Container.Decl.Any> | undefined;
332 }
333
334 export interface DurableObjectClass extends Effect.Effect<DurableObject, never, DurableObject> {
335 <Self, Shape>(): {
336 <Name extends string>(
337 name: Name,
338 props?: Pick<DurableObjectProps, "transferredFrom" | "errors">,
339 ): Effect.Effect<DurableObject<Self>, never, Worker | Self> & {
340 new (_: never): Shape & {
341 /** @internal */
342 "~alchemy/name": Name;
343 };
344 from(scriptName: Input<string>): Effect.Effect<DurableObject<Self>, never, Worker>;
345 from<Req = never>(
346 worker: Dependencies<Self> | Effect.Effect<Dependencies<Self>, never, Req>,
347 ): Effect.Effect<DurableObject<Self>, never, Worker | Req>;
348 make<Req = never>(
349 impl: Effect.Effect<
350 Effect.Effect<Shape, never, RuntimeContext | DurableObjectState | Scope>,
351 never,
352 Req
353 >,
354 // `Exclude` (rather than `DurableObjectServices | Req` inference)
355 // so ambient DO services resolved in the outer init effect never
356 // leak into the host Worker's requirements — mirrors Worker.make's
357 // `Exclude<InitReq, Self | WorkerServices>`.
358 ): Layer.Layer<Self, never, Worker | Exclude<Req, DurableObjectServices>>;
359 };
360 };
361 <Self>(): {
362 <
363 Shape extends MainRpc<DurableObjectState>,
364 Req extends DurableObjectServices | Container.Application<any> = never,
365 >(
366 name: string,
367 impl: Effect.Effect<
368 Effect.Effect<Shape, never, RuntimeContext | DurableObjectState | Scope>,
369 never,
370 Req
371 >,
372 ): Effect.Effect<
373 DurableObject<Self>,
374 never,
375 Worker | Extract<Req, Container.Application<any>>
376 > & {
377 new (_: never): Shape;
378 };
379 };
380 <Shape>(name: string, props?: DurableObjectBindingProps): DurableObjectLike<Shape>;
381 <Shape, InitReq = never>(
382 name: string,
383 impl: Effect.Effect<Shape, never, DurableObjectServices | InitReq>,
384 ): Effect.Effect<DurableObject<Shape>, never, Worker | Exclude<InitReq, DurableObjectServices>>;
385 }
386
387 export class DurableObjectScope extends Context.Service<DurableObjectScope, DurableObject>()(
388 "Cloudflare.DurableObject",
389 ) {}
390
391 /**
392 * A Cloudflare Durable Object namespace that manages globally unique, stateful
393 * instances with WebSocket hibernation support.
394 *
395 * A Durable Object uses a two-phase pattern with two nested `Effect.gen`
396 * blocks. The outer Effect resolves shared dependencies (other DOs,
397 * containers, etc.) and the instance state *reference*
398 * (`Cloudflare.DurableObjectState`). The inner Effect returns the
399 * object's public methods and WebSocket handlers — and is the only
400 * place the state's `RuntimeContext`-colored methods (`storage.get`,
401 * `storage.put`, …) can actually run.
402 *
403 * ```typescript
404 * Effect.gen(function* () {
405 * // Phase 1: resolve shared dependencies + the instance state ref
406 * const db = yield* Cloudflare.D1.QueryDatabase(MyDatabase);
407 * const state = yield* Cloudflare.DurableObjectState;
408 *
409 * return Effect.gen(function* () {
410 * // Phase 2: per-instance setup and public API. `state`'s methods
411 * // (storage.get/put, …) are RuntimeContext-colored, so the actual
412 * // I/O happens here, in the runtime closure.
413 * return {
414 * save: (data: string) => db.exec("INSERT ..."),
415 * fetch: Effect.gen(function* () { ... }),
416 * webSocketMessage: Effect.fn(function* (ws, msg) { ... }),
417 * };
418 * });
419 * })
420 * ```
421 *
422 * There are two ways to define a Durable Object. See the
423 * [Runtime](/infrastructure-as-effects/runtime) page
424 * for the full explanation.
425 *
426 * - **Inline** — Effect implementation passed directly, single file.
427 * - **Modular** — class and implementation in separate files for tree-shaking.
428 *
429 *
430 * ### Inline Durable Objects
431 * Pass the Effect implementation as the second argument. This is the
432 * simplest approach — everything lives in one file. Convenient when
433 * the DO doesn't need to be referenced by other Workers or DOs that
434 * would pull in its runtime dependencies.
435 *
436 * **Example:** Inline Durable Object
437 * ```typescript
438 * export default class Counter extends Cloudflare.DurableObject<Counter>()(
439 * "Counter",
440 * Effect.gen(function* () {
441 * // init: bind resources + resolve the instance state ref
442 * const db = yield* Cloudflare.D1.QueryDatabase(MyDatabase);
443 * const state = yield* Cloudflare.DurableObjectState;
444 *
445 * return Effect.gen(function* () {
446 * // runtime: state's storage methods are RuntimeContext-colored,
447 * // so the reads/writes live here
448 * const count = (yield* state.storage.get<number>("count")) ?? 0;
449 *
450 * return {
451 * increment: () =>
452 * Effect.gen(function* () {
453 * const next = count + 1;
454 * yield* state.storage.put("count", next);
455 * return next;
456 * }),
457 * get: () => Effect.succeed(count),
458 * };
459 * });
460 * }),
461 * ) {}
462 * ```
463 *
464 * ### Modular Durable Objects
465 * When a Worker and a DO reference each other, or multiple Workers
466 * bind the same DO, define the class separately from its `.make()`
467 * call. The class is a lightweight identifier; `.make()` provides
468 * the runtime implementation as an `export default`. Rolldown treats
469 * `.make()` as pure, so the bundler tree-shakes it and all its
470 * runtime dependencies out of any consumer's bundle.
471 *
472 * The class and `.make()` can live in the same file. This is the
473 * same pattern used by `Worker` and `Container`.
474 *
475 * **Example:** Modular Durable Object (class + .make() in one file)
476 * ```typescript
477 * // src/Counter.ts
478 * export class Counter extends Cloudflare.DurableObject<Counter>()(
479 * "Counter",
480 * ) {}
481 *
482 * export default Counter.make(
483 * Effect.gen(function* () {
484 * // init: bind resources + resolve the instance state ref
485 * const db = yield* Cloudflare.D1.QueryDatabase(MyDatabase);
486 * const state = yield* Cloudflare.DurableObjectState;
487 *
488 * return Effect.gen(function* () {
489 * // runtime: state's storage methods are RuntimeContext-colored,
490 * // so the reads/writes live here
491 * const count = (yield* state.storage.get<number>("count")) ?? 0;
492 *
493 * return {
494 * increment: () =>
495 * Effect.gen(function* () {
496 * const next = count + 1;
497 * yield* state.storage.put("count", next);
498 * yield* db.prepare("INSERT INTO logs (count) VALUES (?)").bind(next).run();
499 * return next;
500 * }),
501 * get: () => Effect.succeed(count),
502 * };
503 * });
504 * }),
505 * );
506 * ```
507 *
508 * **Example:** Binding a modular DO from a Worker
509 * ```typescript
510 * // imports Counter; bundler tree-shakes .make()
511 * import Counter from "./Counter.ts";
512 *
513 * // init
514 * const counters = yield* Counter;
515 *
516 * return {
517 * fetch: Effect.gen(function* () {
518 * const counter = counters.getByName("user-123");
519 * return HttpServerResponse.text(String(yield* counter.get()));
520 * }),
521 * };
522 * ```
523 *
524 * ### Cross-Worker Binding
525 * A Durable Object is _hosted_ by exactly one Worker, but any
526 * number of other Workers can bind to the same DO. This is how
527 * you share state across Workers: one Worker hosts the DO, every
528 * other Worker addresses it by `scriptName` and gets a typed stub.
529 *
530 * To make this type-safe, the **host Worker** must declare the DO
531 * as part of its public contract via the third type argument to
532 * `Cloudflare.Worker<Self, Bindings, Deps>()`. `Deps` is the set
533 * of DO classes (or other Workers) the script exposes for other
534 * scripts to bind to.
535 *
536 * **Example:** Host Worker declares the DO in its contract
537 * ```typescript
538 * // workerA.ts — hosts Counter
539 * import { Counter, CounterLive } from "./object.ts";
540 *
541 * // ^^^^^^^ declared as part of WorkerA's public contract
542 * export class WorkerA extends Cloudflare.Worker<WorkerA, {}, Counter>()(
543 * "WorkerA",
544 * { main: import.meta.url },
545 * ) {}
546 *
547 * // WorkerA's Layer also provides the DO's Live implementation.
548 * export default WorkerA.make(
549 * Effect.gen(function* () {
550 * const counter = yield* Counter;
551 * return { fetch: Effect.gen(function* () { ... }) };
552 * }).pipe(Effect.provide(CounterLive)),
553 * );
554 * ```
555 *
556 * **Example:** Consumer Worker binds the DO via `Counter.from(WorkerA)`
557 * ```typescript
558 * // workerB.ts — binds to the same Counter, hosted by WorkerA
559 * import { Counter } from "./object.ts";
560 * import { WorkerA } from "./workerA.ts";
561 *
562 * export default class WorkerB extends Cloudflare.Worker<WorkerB>()(
563 * "WorkerB",
564 * { main: import.meta.url },
565 * Effect.gen(function* () {
566 * // ^^^^^^^^^^^^ scriptName-bound stub of WorkerA's Counter
567 * const counter = yield* Counter.from(WorkerA);
568 * return {
569 * fetch: Effect.gen(function* () {
570 * const value = yield* counter.getByName("shared").get();
571 * return HttpServerResponse.text(String(value));
572 * }),
573 * };
574 * }),
575 * ) {}
576 * ```
577 *
578 * :::tip
579 * The `, Counter` in `Worker<WorkerA, {}, Counter>` is what makes
580 * `Counter.from(WorkerA)` type-check. You can still bind across
581 * scripts without it (the runtime works either way), but consumers
582 * will get a TypeScript error because `WorkerA` doesn't declare
583 * `Counter` as part of its public contract.
584 * :::
585 *
586 * Only the host Worker's Stack provides `CounterLive` — the
587 * consumer Worker just imports the `Counter` class as a typed
588 * identifier. Rolldown tree-shakes `CounterLive` (and its
589 * dependencies) out of WorkerB's bundle.
590 *
591 * ### Using `.from(Self)` Inside the Host
592 * Inside the host Worker, `yield* Counter` and
593 * `yield* Counter.from(Self)` resolve to the same local namespace.
594 * The `.from(Self)` form is preferred — especially in code that
595 * may be extracted into a reusable Layer — because it makes the
596 * scriptName explicit and lets the same Layer shape work whether
597 * the consumer is the host or another script.
598 *
599 * **Example:** `Counter.from(WorkerA)` inside WorkerA itself
600 * ```typescript
601 * // workerA.ts — host uses `.from(Self)` instead of bare `yield* Counter`
602 * export default WorkerA.make(
603 * Effect.gen(function* () {
604 * const counter = yield* Counter.from(WorkerA); // same as `yield* Counter`
605 * return { fetch: Effect.gen(function* () { ... }) };
606 * }).pipe(Effect.provide(CounterLive)),
607 * );
608 * ```
609 *
610 * A Worker can also host its **own isolated** namespace this way.
611 * If a second host Worker declares `Counter` in its contract and
612 * provides `CounterLive`, the DO instances under that script are
613 * separate from the original host's — same class, two namespaces.
614 *
615 * **Example:** Two hosts, two isolated namespaces
616 * ```typescript
617 * // workerC.ts — another host of Counter, isolated from WorkerA
618 * export class WorkerC extends Cloudflare.Worker<WorkerC, {}, Counter>()(
619 * "WorkerC",
620 * { main: import.meta.url },
621 * ) {}
622 *
623 * export default WorkerC.make(
624 * Effect.gen(function* () {
625 * // .from(WorkerC) binds to WorkerC's own Counter namespace —
626 * // writes here are NOT visible from WorkerA's Counter.
627 * const counter = yield* Counter.from(WorkerC);
628 * return { fetch: Effect.gen(function* () { ... }) };
629 * }).pipe(Effect.provide(CounterLive)),
630 * );
631 * ```
632 *
633 * ### RPC Methods
634 * Any function you return from the inner Effect becomes an RPC method
635 * that Workers can call through a stub. Methods must return an `Effect`.
636 * The caller gets a fully typed stub — if your DO returns `increment`
637 * and `get`, the stub exposes `counter.increment()` and `counter.get()`.
638 *
639 * **Example:** Defining RPC methods
640 * ```typescript
641 * return {
642 * increment: () => Effect.succeed(++count),
643 * get: () => Effect.succeed(count),
644 * reset: () => Effect.sync(() => { count = 0; }),
645 * };
646 * ```
647 *
648 * ### Redeploying a Busy Durable Object
649 * A redeploy reaches your Workers right away, but Cloudflare moves each
650 * Durable Object onto the new code separately. An object idle for about
651 * 10 seconds starts on the new code at its next call. An object that keeps
652 * receiving traffic (requests, an open WebSocket, or a recurring alarm)
653 * keeps running its previous code for up to about 5 minutes after the
654 * deploy, until Cloudflare restarts it; open WebSockets disconnect (code
655 * 1006) when that happens. Until then a new Worker calling a method that
656 * only the new code defines fails with `RpcCallError` ("The RPC receiver
657 * does not implement the method"). Keep RPC changes backward compatible
658 * across a deploy: add a method, ship the callers in a later deploy, and
659 * remove old methods last.
660 *
661 * **Example:** Tolerate an object that has not picked up a new method yet
662 * ```typescript
663 * const result = yield* counter.incrementBy(5).pipe(
664 * // Older code is still serving this object: use the old method.
665 * Effect.catchCause((cause) =>
666 * Cause.squash(cause) instanceof Cloudflare.RpcCallError
667 * ? counter.increment()
668 * : Effect.failCause(cause),
669 * ),
670 * );
671 * ```
672 *
673 * ### Returning Streams from RPC
674 * RPC methods can return an Effect `Stream` and the caller will see
675 * the chunks as they're produced. Combine with `Stream.schedule` to
676 * pace emission, or with `Stream.fromQueue` to bridge an inbound
677 * subscription.
678 *
679 * **Example:** Streaming sequential numbers
680 * ```typescript
681 * import * as Schedule from "effect/Schedule";
682 * import * as Stream from "effect/Stream";
683 *
684 * return {
685 * tick: (n: number) =>
686 * Stream.iterate(0, (i) => i + 1).pipe(
687 * Stream.take(n),
688 * Stream.schedule(Schedule.spaced("100 millis")),
689 * ),
690 * };
691 * ```
692 *
693 * **Example:** Forwarding the stream as a chunked HTTP response
694 * ```typescript
695 * // in a Worker fetch handler
696 * const counter = counters.getByName("tick");
697 * const stream = counter.tick(5).pipe(
698 * Stream.map((i) => `${i}\n`),
699 * Stream.encodeText,
700 * );
701 * return HttpServerResponse.stream(stream, {
702 * headers: { "content-type": "text/plain" },
703 * });
704 * ```
705 *
706 * ### Worker → DO HTTP forwarding
707 * In addition to RPC methods, the typed stub exposes a `fetch`
708 * method that forwards an `HttpServerRequest` straight to the DO.
709 * The DO's own `fetch` Effect produces the response — useful for
710 * WebSocket upgrades and other request-shaped interactions.
711 *
712 * **Example:** Forwarding an HTTP request to a DO
713 * ```typescript
714 * const room = rooms.getByName(roomId);
715 * return yield* room.fetch(request);
716 * ```
717 *
718 * ### Placing a Durable Object in a Region
719 * A Durable Object is created wherever its *first-ever* request
720 * came from, and it stays there for life. That default is right for
721 * an instance whose traffic all comes from the user who created it,
722 * and wrong for one whose name is derived from something other than
723 * geography (a shard index, a hash, a fixed roster) — a Sydney user
724 * routed onto an instance that some Frankfurt request happened to
725 * create first pays a cross-planet round trip on every call.
726 *
727 * Pass a `locationHint` to place the instance near the traffic you
728 * expect instead. It only applies to *creation*: an instance that
729 * already exists is unaffected, so a hint can't move a live DO.
730 *
731 * **Example:** Sharding instances by region
732 * ```typescript
733 * // Both the name and the hint derive from the caller's region, so
734 * // each shard is created in the region whose users address it.
735 * const region = hintFor(request.cf?.continent); // "apac", "weur", …
736 * const shard = shards.getByName(`pool:${region}:${index}`, {
737 * locationHint: region,
738 * });
739 * ```
740 *
741 * :::caution
742 * A hint is a hint: Cloudflare places the instance in the nearest
743 * location it *can*, which may not be the hinted one, and only the
744 * first request to a given name has any say. Derive the name from
745 * the same region you hint with — otherwise two regions race to
746 * create one shared instance and the loser is stuck with it.
747 * :::
748 *
749 * ### Accessing Instance State
750 * Each Durable Object instance has its own transactional key-value
751 * storage via `Cloudflare.DurableObjectState`. Resolve the `state`
752 * *reference* in the outer (init) Effect, but call its methods —
753 * `storage.get`, `storage.put`, … — only from the inner (runtime)
754 * Effect: those methods are `RuntimeContext`-colored, so the type
755 * system only allows them inside the runtime closure.
756 *
757 * **Example:** Reading and writing durable storage
758 * ```typescript
759 * // inner (runtime) Effect — `state` was resolved in the outer Effect
760 * yield* state.storage.put("counter", 42);
761 * const value = yield* state.storage.get("counter");
762 * ```
763 *
764 * ### Background Work & Scopes
765 * Every RPC call and fetch into a Durable Object gets its own Effect
766 * `Scope`. When the method finishes, the bridge closes that scope and
767 * registers the close promise with workerd's `state.waitUntil` — so
768 * finalizers added with `Effect.addFinalizer` inside a method run *after*
769 * the result is returned to the caller, without blocking it, and the
770 * object stays alive until they settle.
771 *
772 * For ad-hoc background work, `state.waitUntil(effect)` forks an Effect
773 * with the caller's full context and keeps the object alive until it
774 * settles.
775 *
776 * Attach cleanup to method scopes, not the constructor (init) closure —
777 * the constructor runs once per in-memory instance under
778 * `blockConcurrencyWhile`, and its scope is not tied to any call.
779 *
780 * **Example:** Responding before finishing the work
781 * ```typescript
782 * return {
783 * record: Effect.fn(function* (entry: string) {
784 * // runs after `record` returns; the DO stays alive until it settles
785 * yield* Effect.addFinalizer(() =>
786 * state.storage.put(`audit:${entry}`, Date.now()).pipe(Effect.ignore),
787 * );
788 * return "accepted" as const;
789 * }),
790 *
791 * refresh: Effect.fn(function* () {
792 * // same idea, explicit form
793 * yield* state.waitUntil(recomputeExpensiveView());
794 * return "scheduled" as const;
795 * }),
796 * };
797 * ```
798 *
799 * ### WebSocket Hibernation
800 * Durable Objects support WebSocket hibernation — the runtime can
801 * evict the object from memory while keeping connections open. Use
802 * `Cloudflare.upgrade()` to accept a connection, and return
803 * `webSocketMessage` / `webSocketClose` / `webSocketError` handlers to
804 * process events when the object wakes back up.
805 *
806 * **Example:** Accepting a WebSocket connection
807 * ```typescript
808 * return {
809 * fetch: Effect.gen(function* () {
810 * const [response, socket] = yield* Cloudflare.upgrade();
811 * socket.serializeAttachment({ id: crypto.randomUUID() });
812 * return response;
813 * }),
814 * };
815 * ```
816 *
817 * **Example:** Handling messages and close events
818 * ```typescript
819 * return {
820 * webSocketMessage: Effect.fn(function* (
821 * socket: Cloudflare.WebSocket,
822 * message: string | Uint8Array,
823 * ) {
824 * const text = typeof message === "string"
825 * ? message
826 * : new TextDecoder().decode(message);
827 * // process the message
828 * }),
829 * webSocketClose: Effect.fn(function* (
830 * ws: Cloudflare.WebSocket,
831 * code: number,
832 * reason: string,
833 * ) {
834 * yield* ws.close(code, reason);
835 * }),
836 * webSocketError: Effect.fn(function* (
837 * ws: Cloudflare.WebSocket,
838 * error: unknown,
839 * ) {
840 * // the runtime closes the socket afterwards; clear its session here
841 * ws.serializeAttachment(null);
842 * }),
843 * };
844 * ```
845 *
846 * **Example:** Recovering sessions after hibernation
847 * Resolve the `state` reference in the outer Effect, but place the
848 * rehydration loop (`state.getWebSockets()` is `RuntimeContext`-colored)
849 * **inside the inner `Effect.gen`** so it runs every time the DO
850 * instance is reconstructed (including after Cloudflare wakes the DO
851 * from hibernation).
852 *
853 * ```typescript
854 * Effect.gen(function* () {
855 * const state = yield* Cloudflare.DurableObjectState;
856 *
857 * return Effect.gen(function* () {
858 * const sessions = new Map<string, Cloudflare.WebSocket>();
859 *
860 * // Rehydrate the in-memory session map after hibernation.
861 * for (const socket of yield* state.getWebSockets()) {
862 * const data = socket.deserializeAttachment<{ id: string }>();
863 * if (data) sessions.set(data.id, socket);
864 * }
865 *
866 * return {
867 * fetch: Effect.gen(function* () {
868 * const [response, socket] = yield* Cloudflare.upgrade();
869 * const id = crypto.randomUUID();
870 * socket.serializeAttachment({ id });
871 * sessions.set(id, socket);
872 * return response;
873 * }),
874 * webSocketMessage: Effect.fn(function* (socket, message) {
875 * const text =
876 * typeof message === "string" ? message : new TextDecoder().decode(message);
877 * for (const peer of sessions.values()) {
878 * yield* peer.send(text);
879 * }
880 * }),
881 * };
882 * });
883 * });
884 * ```
885 *
886 * ### Durable Callbacks
887 * Register `Alchemy.makeCallback` handlers in the inner, per-instance Effect.
888 * Durable Objects supply callback registration on their instance RuntimeContext
889 * using SQLite and native alarms. Scheduling participates in the current storage
890 * transaction, and each job is acknowledged only after its handler succeeds.
891 * No explicit `alarm` handler is needed.
892 *
893 * **Example:** Save state and schedule a typed callback atomically
894 * ```typescript
895 * const state = yield* Cloudflare.DurableObjectState;
896 * return Effect.gen(function* () {
897 * const onArchive = yield* Alchemy.makeCallback(
898 * "archive",
899 * Effect.fn(function* (payload: { key: string; body: string }) {
900 * yield* archive.put(payload.key, payload.body);
901 * }),
902 * );
903 * return {
904 * save: Effect.fn(function* (id: string, body: string) {
905 * yield* state.storage.transaction(
906 * Effect.gen(function* () {
907 * yield* state.storage.put(id, body);
908 * yield* onArchive.schedule(id, {
909 * after: "30 seconds",
910 * payload: { key: id, body },
911 * });
912 * }),
913 * );
914 * }),
915 * };
916 * });
917 * ```
918 *
919 * Callbacks receive JSON-serializable payloads and deliver at least once, so
920 * external writes must be idempotent. A recovery wake is persisted before each
921 * attempt. Failures use exponential backoff with a 30-second initial delay and
922 * park after eight attempts without progress, retaining work for hourly recovery.
923 * Configure these with the third argument, `{ retry: { delay: "1 second",
924 * maxAttempts: 8, parkedDelay: "1 hour" } }`. The retry floor is one second;
925 * parked retries are at least one hour apart. Scheduling the same callback name
926 * and ID replaces the pending job; `onArchive.cancel(id)` cancels it. Retain
927 * handlers for old callback names while their jobs are pending. Each native
928 * alarm processes up to 100 due jobs; direct `setAlarm`/`deleteAlarm` calls
929 * bypass the scheduler's coordination.
930 * Leave native alarm retries enabled when aborting an instance. Passing
931 * `{ retryAlarm: false }` removes the automatic-recovery guarantee: Cloudflare
932 * can suppress a replacement wake even after its timestamp is persisted. Jobs
933 * remain stored, but may need an explicitly rearmed native alarm.
934 *
935 * Self-rescheduling inherits the invocation's budget, even when cancelling or
936 * changing IDs. Commit application state and an increasing `progress` cursor
937 * in the same storage transaction to reset that budget. Replayed external
938 * cursors cannot replace newer work; an external schedule without a cursor
939 * explicitly starts a fresh budget. Detached fibers cannot mutate callbacks
940 * after their invocation ends.
941 *
942 * **Example:** Inspect and recover a parked job from an incoming request
943 * ```typescript
944 * const status = yield* onArchive.getStatus("revision-42");
945 * if (status?.parked) {
946 * yield* onArchive.schedule("revision-42", {
947 * after: 0,
948 * payload: { key: "42.txt", body: "hello" },
949 * });
950 * }
951 * ```
952 *
953 * Status includes the original `scheduledAt`, separate `retryAt`, attempt count,
954 * parked flag, and latest progress cursor without decoding the payload. Parking
955 * emits a warning without job identifiers or payloads. Status remains durable
956 * across instance reconstruction.
957 *
958 * The scheduler migrates its unversioned and version-one SQLite schemas to
959 * version two atomically, preserving existing events and callback deadlines.
960 * Old events still use the explicit `alarm` handler below; their rows have no
961 * callback name to infer. Both APIs coordinate the same native alarm. Unknown
962 * newer schema versions fail closed.
963 *
964 * ### Scheduled Alarms
965 * Each Durable Object can have a single alarm timestamp. Alchemy
966 * layers a small SQLite-backed scheduler on top via
967 * `Cloudflare.Workers.scheduleEvent` and `Cloudflare.Workers.processScheduledEvents`,
968 * so you can register many named events with arbitrary payloads and
969 * fire them from a single `alarm` handler.
970 *
971 * **Example:** Scheduling and processing events
972 * ```typescript
973 * // schedule from a request or message handler
974 * yield* Cloudflare.Workers.scheduleEvent(
975 * "reminder-1",
976 * new Date(Date.now() + 60_000),
977 * { message: "your meeting starts in a minute" },
978 * );
979 *
980 * return {
981 * alarm: () =>
982 * Effect.gen(function* () {
983 * const fired = yield* Cloudflare.Workers.processScheduledEvents;
984 * for (const event of fired) {
985 * const payload = event.payload as { message: string };
986 * // dispatch / broadcast / persist...
987 * }
988 * }),
989 * };
990 * ```
991 *
992 * ### Aborting a Durable Object
993 * `state.abort(reason?, options?)` forcibly resets the isolate. By
994 * default an in-progress alarm retries after the reset. Pass
995 * `{ retryAlarm: false }` when the alarm should stop instead — for
996 * example an alarm that deletes storage so the constructor does not
997 * recreate it.
998 *
999 * **Example:** Stop alarm retries after cleanup
1000 * ```typescript
1001 * export class CleanupTask extends Cloudflare.DurableObject<CleanupTask>()(
1002 * "CleanupTask",
1003 * Effect.gen(function* () {
1004 * const state = yield* Cloudflare.DurableObjectState;
1005 *
1006 * return Effect.gen(function* () {
1007 * // This won't be re-run after the alarm is aborted
1008 * yield* state.storage.sql.exec(`
1009 * CREATE TABLE IF NOT EXISTS foo (
1010 * id INTEGER PRIMARY KEY
1011 * )
1012 * `);
1013 *
1014 * return {
1015 * alarm: () =>
1016 * Effect.gen(function* () {
1017 * yield* state.storage.sql.exec("DROP TABLE foo");
1018 * yield* state.abort("Cleanup complete", { retryAlarm: false });
1019 * }),
1020 * };
1021 * });
1022 * }),
1023 * ) {}
1024 * ```
1025 *
1026 * ### Using from a Worker
1027 * Yield the DO class in your Worker's init phase to get a namespace
1028 * handle. Call `getByName` or `getById` to get a typed stub, then
1029 * call any RPC method or forward an HTTP request with `fetch`.
1030 *
1031 * **Example:** Calling RPC methods
1032 * ```typescript
1033 * // init
1034 * const counters = yield* Counter;
1035 *
1036 * return {
1037 * fetch: Effect.gen(function* () {
1038 * const counter = counters.getByName("user-123");
1039 * yield* counter.increment();
1040 * const value = yield* counter.get();
1041 * return HttpServerResponse.text(String(value));
1042 * }),
1043 * };
1044 * ```
1045 *
1046 * **Example:** Forwarding an HTTP request
1047 * ```typescript
1048 * // init
1049 * const rooms = yield* Room;
1050 *
1051 * return {
1052 * fetch: Effect.gen(function* () {
1053 * const request = yield* HttpServerRequest;
1054 * const room = rooms.getByName(roomId);
1055 * return yield* room.fetch(request);
1056 * }),
1057 * };
1058 * ```
1059 *
1060 * ### Binding in an Async Worker
1061 * When using an Async Worker (plain `async fetch` handler, no Effect
1062 * runtime), declare Durable Objects in the `bindings` prop of the
1063 * Worker resource. Pass a `DurableObject` reference with a
1064 * `className` matching the exported `DurableObject` subclass in your
1065 * worker source file. If `className` is omitted, it defaults to the
1066 * namespace name. Use `Cloudflare.InferEnv` to get a fully typed
1067 * `env` object that includes the namespace.
1068 *
1069 * **Example:** Declaring a DO binding in the stack
1070 * ```typescript
1071 * // alchemy.run.ts
1072 * import type { Counter } from "./src/worker.ts";
1073 *
1074 * export type WorkerEnv = Cloudflare.InferEnv<typeof Worker>;
1075 *
1076 * export const Worker = Cloudflare.Worker("Worker", {
1077 * main: "./src/worker.ts",
1078 * bindings: {
1079 * Counter: Cloudflare.DurableObject<Counter>("Counter"),
1080 * },
1081 * });
1082 * ```
1083 *
1084 * **Example:** Using the DO from a plain async handler
1085 * ```typescript
1086 * // src/worker.ts
1087 * import { DurableObject } from "cloudflare:workers";
1088 * import type { WorkerEnv } from "../alchemy.run.ts";
1089 *
1090 * export default {
1091 * async fetch(request: Request, env: WorkerEnv) {
1092 * const counter = env.Counter.getByName("my-counter");
1093 * const count = await counter.increment();
1094 * return new Response(JSON.stringify({ count }));
1095 * },
1096 * };
1097 *
1098 * export class Counter extends DurableObject {
1099 * private counter = 0;
1100 * async increment() {
1101 * return ++this.counter;
1102 * }
1103 * }
1104 * ```
1105 *
1106 * ### Cross-Script Binding in an Async Worker
1107 * Async Workers can also bind to a Durable Object hosted by another
1108 * Worker script. The host Worker declares and exports the DO class. The
1109 * consumer Worker declares a `DurableObject` with `scriptName`
1110 * set to the host Worker's script name.
1111 *
1112 * Cross-script async bindings are references only: the consumer uploads
1113 * the binding metadata, but Alchemy does not drive class migrations for
1114 * the foreign class. Deploy the host first so Cloudflare can verify that
1115 * the target script exports the requested class.
1116 *
1117 * **Example:** Host Worker owns the Durable Object class
1118 * ```typescript
1119 * const host = yield* Cloudflare.Worker("Host", {
1120 * main: "./src/host.ts",
1121 * bindings: {
1122 * Counter: Cloudflare.DurableObject<Counter>("Counter"),
1123 * },
1124 * });
1125 * ```
1126 *
1127 * **Example:** Consumer Worker binds to the host script
1128 * ```typescript
1129 * const consumer = yield* Cloudflare.Worker("Consumer", {
1130 * main: "./src/consumer.ts",
1131 * bindings: {
1132 * Counter: Cloudflare.DurableObject<Counter>("Counter", {
1133 * scriptName: host.workerName,
1134 * }),
1135 * },
1136 * });
1137 * ```
1138 *
1139 * **Example:** Binding to a different exported class name
1140 * ```typescript
1141 * const consumer = yield* Cloudflare.Worker("Consumer", {
1142 * main: "./src/consumer.ts",
1143 * bindings: {
1144 * Counter: Cloudflare.DurableObject<Counter>("Counter", {
1145 * className: "CounterV2",
1146 * scriptName: host.workerName,
1147 * }),
1148 * },
1149 * });
1150 * ```
1151 *
1152 * ### Container-Backed Durable Objects in an Async Worker
1153 * A container-backed class is declared by binding a `Cloudflare.Container`
1154 * directly in the async Worker's `env` — the Container *is* the Durable
1155 * Object binding plus its ContainerApplication. See the Async Workers
1156 * section on {@link Container} for the full walkthrough.
1157 *
1158 * **Example:** A Container binding declares the container-backed class
1159 * ```typescript
1160 * // `Sandbox` is the container-backed DO class exported by the worker
1161 * // script (extends `@cloudflare/containers`' `Container`).
1162 * import type { Sandbox } from "./src/worker.ts";
1163 *
1164 * export const Worker = Cloudflare.Worker("Worker", {
1165 * main: "./src/worker.ts",
1166 * env: {
1167 * Sandbox: Cloudflare.Container<Sandbox>("Sandbox", {
1168 * image: "docker.io/cloudflare/sandbox:0.1.3",
1169 * }),
1170 * },
1171 * });
1172 * ```
1173 *
1174 * ### Native Containers in an Async Worker
1175 * A plain Durable Object class can start Durable Object-managed Containers
1176 * (`schedulingPolicy: "durable_object"`). List them in its binding's
1177 * `containers`: each adds its image to the class's container application,
1178 * keyed by the Container's id in `ctx.container.images`. A Container may be
1179 * shared by several classes.
1180 *
1181 * **Example:** Two classes, one shared image
1182 * ```typescript
1183 * const Node = Cloudflare.Container("Node", {
1184 * schedulingPolicy: "durable_object",
1185 * image: "node:24-slim",
1186 * });
1187 * const Python = Cloudflare.Container("Python", {
1188 * schedulingPolicy: "durable_object",
1189 * image: "python:3.13-slim",
1190 * });
1191 * const Rust = Cloudflare.Container("Rust", {
1192 * schedulingPolicy: "durable_object",
1193 * image: "rust:1.90-slim",
1194 * });
1195 *
1196 * export const Worker = Cloudflare.Worker("App", {
1197 * main: "./src/worker.ts",
1198 * env: {
1199 * AGENT: Cloudflare.DurableObject("Agent", { containers: [Node, Python] }),
1200 * REVIEWER: Cloudflare.DurableObject("Reviewer", { containers: [Node, Rust] }),
1201 * },
1202 * });
1203 * ```
1204 *
1205 * **Example:** Starting a Container's image from the class
1206 * ```typescript
1207 * // src/worker.ts
1208 * export class Agent extends DurableObject {
1209 * async run(cmd: string[]) {
1210 * const container = this.ctx.container!;
1211 * if (!container.running) {
1212 * container.start({
1213 * image: container.images.Node,
1214 * entrypoint: ["sleep", "infinity"],
1215 * enableInternet: false,
1216 * });
1217 * }
1218 * return (await container.exec(cmd)).output();
1219 * }
1220 * }
1221 * ```
1222 *
1223 * ### Moving a Class Between Workers
1224 * A Durable Object class can move from one Worker to another with its
1225 * data intact. The move is always **declared** — a class that disappears
1226 * from one worker and appears on another is otherwise ambiguous between
1227 * "transfer the data" and "delete it, start fresh", so Alchemy never
1228 * guesses (removing a DO deletes it; that is the default). Declare
1229 * `transferredFrom` on the Durable Object at its **new host**, naming the
1230 * former host, and the new host's deploy moves the namespace with its
1231 * data (Cloudflare's `expecting-transfer` / `transferred` exports
1232 * entries). The former host's deploy converges on its own — nothing is
1233 * deleted for a class that moved away.
1234 *
1235 * Each `transferredFrom` entry is either the former host's Worker
1236 * **logical id** (same stack + stage, resolved via alchemy's ownership
1237 * tags) or its **physical script name** (required for cross-stack moves).
1238 * When no listed host holds the namespace — a fresh stage, or the
1239 * transfer already completed — the declaration is inert, so it is safe to
1240 * leave in place indefinitely.
1241 *
1242 * **Example:** Move a class from WorkerB to WorkerA
1243 * ```typescript
1244 * // BEFORE: worker-b hosts the class
1245 * const b = yield* Cloudflare.Worker("WorkerB", {
1246 * main: "./src/worker-b.ts", // exports MyDOClass
1247 * bindings: {
1248 * MyDO: Cloudflare.DurableObject("MyDO", { className: "MyDOClass" }),
1249 * },
1250 * });
1251 *
1252 * // AFTER: worker-a hosts it and declares where it came from;
1253 * // worker-b keeps a cross-script reference.
1254 * const a = yield* Cloudflare.Worker("WorkerA", {
1255 * main: "./src/worker-a.ts", // now exports MyDOClass
1256 * bindings: {
1257 * MyDO: Cloudflare.DurableObject("MyDO", {
1258 * className: "MyDOClass",
1259 * transferredFrom: "WorkerB", // logical id (or its script name)
1260 * }),
1261 * },
1262 * });
1263 * const b = yield* Cloudflare.Worker("WorkerB", {
1264 * main: "./src/worker-b.ts", // no longer exports MyDOClass
1265 * bindings: {
1266 * MyDO: Cloudflare.DurableObject("MyDO", {
1267 * className: "MyDOClass",
1268 * scriptName: a.workerName,
1269 * }),
1270 * },
1271 * });
1272 * ```
1273 *
1274 * Forgetting the declaration is safe: when the former host still
1275 * references the class cross-script, its deploy fails before any upload
1276 * with `DurableObjectTransferRequired`, telling you exactly what to
1277 * declare — data is never silently destroyed or forked.
1278 *
1279 * **Example:** Chained moves keep the host history
1280 * ```typescript
1281 * // The class moved WorkerB → WorkerA last release and WorkerA →
1282 * // WorkerC this release. Keep the full history so a stage that lagged
1283 * // behind (or skipped the intermediate release) still transfers from
1284 * // wherever its namespace currently lives.
1285 * Cloudflare.DurableObject("MyDO", {
1286 * className: "MyDOClass",
1287 * transferredFrom: ["WorkerB", "WorkerA"],
1288 * })
1289 * ```
1290 *
1291 * Two rules for multi-worker migrations:
1292 *
1293 * - **Pure moves (the former host drops the DO entirely, keeping no
1294 * cross-script reference) must be two deploys**: first add the class to
1295 * the new host with `transferredFrom` and deploy; then remove it from
1296 * the former host and deploy. In a single deploy nothing orders the
1297 * transfer before the former host's delete.
1298 * - **Cross-stack moves deploy the new host's stack first**, naming the
1299 * former host by physical script name; the former host's stack deploys
1300 * after and converges.
1301 *
1302 * ### Adopting an Existing Durable Object
1303 * When you adopt a Worker that already exists on Cloudflare — created
1304 * outside Alchemy via Wrangler, the dashboard, or the raw API — its
1305 * Durable Object classes are adopted along with it. You opt in to the
1306 * takeover the same way you adopt any foreign resource: with
1307 * `adopt(true)` (or the `--adopt` CLI flag), since `Worker.read` reports
1308 * a worker with no Alchemy ownership tags as `Unowned`.
1309 *
1310 * Alchemy normally tracks which class backs each binding through an
1311 * `alchemy:dos:` metadata tag it writes on the script (mapping each
1312 * binding's logical id to its class name). A
1313 * foreign worker has no such tag, so on the **adopting deploy** Alchemy
1314 * falls back to matching your binding to the live class **by binding
1315 * name**. The class is then reused in place — not recreated — so
1316 * Cloudflare's migration engine doesn't reject the upload for creating a
1317 * class that already exists.
1318 *
1319 * The consequence is a one-time constraint: **on the adopting deploy the
1320 * binding's `className` must match the class that already exists on the
1321 * worker.** You cannot rename the class in the same deploy that adopts
1322 * it. Once the deploy completes, Alchemy owns the worker and has written
1323 * the `alchemy:dos:` tag, so subsequent renames are driven by logical id
1324 * and work normally.
1325 *
1326 * **Example:** Adopting a worker whose `Counter` class already exists
1327 * ```typescript
1328 * // The worker + `Counter` class were created outside Alchemy.
1329 * // `className` must match the existing class on this first deploy.
1330 * const worker = yield* Cloudflare.Worker("Worker", {
1331 * name: "existing-worker",
1332 * main: "./src/worker.ts",
1333 * bindings: {
1334 * Counter: Cloudflare.DurableObject<Counter>("Counter"),
1335 * },
1336 * }).pipe(adopt(true));
1337 * ```
1338 *
1339 * **Example:** Renaming the class — only after adoption
1340 * ```typescript
1341 * // A SECOND deploy, after the one above. Alchemy now owns the worker
1342 * // and maps the binding by logical id, so the class can be renamed.
1343 * const worker = yield* Cloudflare.Worker("Worker", {
1344 * name: "existing-worker",
1345 * main: "./src/worker.ts",
1346 * bindings: {
1347 * Counter: Cloudflare.DurableObject<Counter>("Counter", {
1348 * className: "CounterV2",
1349 * }),
1350 * },
1351 * });
1352 * ```
1353 *
1354 * @resource
1355 * @product Workers
1356 * @category Workers & Compute
1357 */
1358 export const DurableObject: DurableObjectClass = taggedFunction(
1359 DurableObjectScope,
1360 function (
1361 ...args:
1362 | []
1363 | [
1364 name: string,
1365 props?: DurableObjectProps,
1366 // phantom argument
1367 isClassForm?: true,
1368 ]
1369 | [
1370 name: string,
1371 impl: Effect.Effect<Effect.Effect<DurableObject<any>, never, DurableObjectState>>,
1372 // phantom argument
1373 isClassForm?: true,
1374 ]
1375 ) {
1376 if (args.length === 0) {
1377 return (name: string, propsOrImpl?: any) =>
1378 // @ts-expect-error
1379 DurableObject(name, propsOrImpl, true);
1380 }
1381 const namespace = args[0];
1382 const isClassForm = args[2] === true;
1383 const propsOrImpl = args[1];
1384 const tag = Context.Service(namespace);
1385
1386 const binding = (
1387 scriptName?: Input<string>,
1388 transferredFrom?: DurableObjectTransferSource | DurableObjectTransferSource[],
1389 errors?: ReadonlyArray<RpcErrorClass>,
1390 ) =>
1391 Effect.gen(function* () {
1392 const worker = yield* Worker;
1393
1394 yield* worker.bind`${namespace}`({
1395 bindings: [
1396 {
1397 type: "durable_object_namespace",
1398 name: namespace,
1399 className: namespace,
1400 scriptName,
1401 transferredFrom: normalizeTransferredFrom(transferredFrom),
1402 },
1403 ],
1404 });
1405
1406 const binding = yield* Effect.all([WorkerEnvironment, ALCHEMY_PHASE]).pipe(
1407 Effect.flatMap(([env, phase]) => {
1408 if (env === undefined || phase === "plan") {
1409 // should be fine to return undefined here (it is only undefined at plantime)
1410 return Effect.undefined;
1411 }
1412 const ns = env[namespace];
1413 if (!ns) {
1414 return Effect.die(new Error(`DurableObject '${namespace}' not found`));
1415 } else if (typeof ns.getByName === "function") {
1416 return Effect.succeed(ns);
1417 } else {
1418 return Effect.die(new Error(`DurableObject '${namespace}' is not a DurableObject`));
1419 }
1420 }),
1421 );
1422
1423 // `undefined` at plan time; every method is only called at runtime.
1424 // A function because `jurisdiction` wraps the sub-namespace it returns.
1425 // The return annotation checks the value against the interface, so a
1426 // method missing here is a compile error.
1427 // Without a `scriptName` the class is hosted by this Worker, so its
1428 // `DurableObjectBridge` ships in this bundle and strips the trace
1429 // context a stub appends. A class in another script may be plain JS
1430 // or an older deploy, so its calls carry only the caller's arguments.
1431 const stubOptions = { errors, traceContext: scriptName === undefined };
1432 const makeNamespace = (ns: cf.DurableObjectNamespace | undefined): DurableObject<any> => ({
1433 // `kind` + `scriptName`/`transferredFrom` let a namespace passed in
1434 // a Worker's `env` bind as the `durable_object_namespace` it is.
1435 kind: TypeId,
1436 scriptName,
1437 transferredFrom,
1438 Type: TypeId,
1439 LogicalId: namespace,
1440 name: namespace,
1441 namespaceId: worker.durableObjectNamespaces.pipe(
1442 Output.map((durableObjectNamespaces) => durableObjectNamespaces?.[namespace]),
1443 ),
1444 getByName: (name: string, options?: DurableObjectGetDurableObjectOptions) =>
1445 makeRpcStub(ns!.getByName(name, options), stubOptions),
1446 newUniqueId: () => ns!.newUniqueId(),
1447 idFromName: (name: string) => ns!.idFromName(name),
1448 idFromString: (id: string) => ns!.idFromString(id),
1449 get: (id: DurableObjectId, options?: DurableObjectGetDurableObjectOptions) =>
1450 makeRpcStub(ns!.get(id, options), stubOptions),
1451 jurisdiction: (jurisdiction: DurableObjectJurisdiction) =>
1452 makeNamespace(restrictToJurisdiction(ns, jurisdiction)),
1453 });
1454
1455 return makeNamespace(binding);
1456 });
1457
1458 // Class-form declarations (`DurableObject<Self>()("Name", props?)`) can
1459 // carry `transferredFrom` so the host's local binding drives a
1460 // data-preserving transfer migration.
1461 const classProps =
1462 isClassForm && !Effect.isEffect(propsOrImpl)
1463 ? (propsOrImpl as Pick<DurableObjectProps, "transferredFrom" | "errors"> | undefined)
1464 : undefined;
1465
1466 const make = Effect.fn(function* (
1467 impl: Effect.Effect<Effect.Effect<DurableObjectShape>, never, DurableObjectState>,
1468 ) {
1469 // Register the local DO binding (no `scriptName`) and obtain the
1470 // namespace handle. We provide this same handle as
1471 // `DurableObjectScope` to the user's constructor effect
1472 // and also return it so a `Layer.effect(tag, make(impl))` Layer
1473 // resolves the tag to a concrete namespace value.
1474 const self = yield* binding(undefined, classProps?.transferredFrom, classProps?.errors);
1475 const phase = yield* ALCHEMY_PHASE;
1476 const constructor = impl.pipe(Effect.provideService(DurableObjectScope, self as any));
1477 if (phase === "plan") {
1478 // during plan time, we evaluate the constructor with a mock DurableObjectState
1479 // to trigger discovery of bindings
1480 yield* constructor.pipe(
1481 Effect.provide(
1482 Layer.succeed(
1483 DurableObjectState,
1484 // mock during plan time
1485 fromDurableObjectState({ storage: {} } as any),
1486 ),
1487 ),
1488 Effect.asVoid,
1489 );
1490 }
1491 yield* (yield* Worker).export(namespace, {
1492 kind: "durableObject",
1493 // initialize the object's constructor (apply infra dependencies)
1494 constructor,
1495 // grab the object's infra dependencies so we can apply them when calling the instance's methods
1496 services: yield* Effect.context<Effect.Services<typeof impl>>(),
1497 } satisfies DurableObjectExport);
1498 return self;
1499 });
1500
1501 if (!isClassForm && !Effect.isEffect(args[1])) {
1502 // this is an in-line, async only DO (no implementation, props only)
1503 return {
1504 kind: TypeId,
1505 name: namespace,
1506 className: (args[1] as DurableObjectProps)?.className || namespace,
1507 scriptName: (args[1] as DurableObjectProps)?.scriptName,
1508 transferredFrom: (args[1] as DurableObjectProps)?.transferredFrom,
1509 storage: (args[1] as DurableObjectProps)?.storage,
1510 containers: (args[1] as DurableObjectBindingProps)?.containers,
1511 };
1512 } else if (Effect.isEffect(propsOrImpl)) {
1513 // inline Effect DO
1514 return effectClass(
1515 Effect.tap(binding(), () =>
1516 make(propsOrImpl as any).pipe(
1517 Effect.provideService(
1518 DurableObjectState,
1519 fromDurableObjectState(
1520 // everything is lazy, so this should build a proper mock
1521 {
1522 storage: {},
1523 } as any,
1524 ),
1525 ),
1526 ),
1527 ),
1528 );
1529 } else {
1530 // Tagged Effect DO. Yielding the class resolves the `tag`, which
1531 // forces the `CounterLive` Layer (built by `Counter.make(impl)`) to
1532 // run so `worker.export(namespace, …)` is invoked — without this,
1533 // the class would never be registered with the Worker's exports
1534 // map and the deployed bundle would have no DO class for
1535 // Cloudflare to instantiate.
1536 return class extends effectClass(tag as Effect.Effect<any, never, any>) {
1537 static make = <Req = never>(
1538 impl: Effect.Effect<Effect.Effect<DurableObjectShape, never, DurableObjectState | Req>>,
1539 ) => Layer.effect(tag, make(impl as any));
1540
1541 static from = (worker: string | Worker | Effect.Effect<Worker, any, any>) => {
1542 // Resolve `worker` to an Effect that yields the actual Worker
1543 // instance (or a plain string scriptName).
1544 //
1545 // A class produced by `Cloudflare.Worker<T>()(...)` exposes
1546 // `asEffect()` returning the Self tag — yielding that tag
1547 // resolves to the live Worker instance whose `workerName`
1548 // is a `PropExpr`, which is what we need so the engine can:
1549 // 1) Track WorkerB → WorkerA as a binding-level upstream
1550 // dependency (so WorkerA reconciles first).
1551 // 2) Persist `scriptName` as a real value (not `undefined`)
1552 // on the cross-script binding so the migration code in
1553 // Worker.ts can detect it and skip emitting class
1554 // migrations for the foreign class.
1555 // Plain Effects and string literals are passed through as-is.
1556 const resolved: Effect.Effect<Worker | string, any, any> =
1557 typeof worker === "string" ? Effect.succeed(worker) : asEffect(worker);
1558
1559 return resolved.pipe(
1560 Effect.flatMap((w) =>
1561 binding(typeof w === "string" ? w : w.workerName, undefined, classProps?.errors),
1562 ),
1563 );
1564 };
1565 };
1566 }
1567 },
1568 ) as any;
1569
1570 export type DurableObjectStub<Shape> = {
1571 // TODO(sam): do we need to transform? hopefully not
1572 [key in keyof Shape]: Shape[key];
1573 } & {
1574 fetch: (
1575 request: HttpServerRequest.HttpServerRequest,
1576 ) => Effect.Effect<HttpServerResponse.HttpServerResponse, HttpServerError, never>;
1577 };