返回源码地图

packages/chord/src/object.ts

v1.3.0 · 71023aec1546 · 22:activation、引用与方法分派

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import type { Static, TSchema } from "typebox";
2import { Value } from "typebox/value";
3import {
4 Cell,
5 Derived,
6 HYDRATION,
7 type Hydration,
8 hydrationOf,
9 isSource,
10 notReady,
11 type Sources,
12 type SourceValues,
13 unhydrated,
14} from "./cell.ts";
15import {
16 type Accepts,
17 type Adapter,
18 type AnyContract,
19 bind,
20 type ImplementationOf,
21 type InputOf,
22 LOCAL_VARIANT,
23 type LocalContract,
24 type MemberDescription,
25 type Ref,
26 takesNoArgs,
27} from "./contract.ts";
28import type { EventOf, ListenerDecl, Resource, ResourceDeclaration, Subscribable, ValueOf } from "./declare.ts";
29import { asChordError, ChordError, invalid, runAll } from "./errors.ts";
30import { enqueue } from "./publish.ts";
31import type { Registration, Registry } from "./registry.ts";
32import type { RemoteHost } from "./remote.ts";
33import { assertValid, normalize } from "./schema.ts";
34import type { Ctx, Exposed, GetOptions, Readable, RefStatus, Shape, StateEvent } from "./types.ts";
35
36const noop = (): void => {};
37
38// ─── Services ────────────────────────────────────────────────────────────────
39
40/**
41 * `serve` options. `lifetime` says how long objects of the type live. `"referenced"` (default): created at the first
42 * `get` of an address, disposed after the last reference is released (plus `linger`). `"host"`: one object, created when
43 * its facet loads (loading waits until it is live) and kept until the host closes or a reload removes its facet. Only
44 * local types whose input accepts `{}` may have it (`ServeOptionsFor` checks that at compile time, `serve` again at
45 * runtime); every `get` reaches that one object, created for the host principal. Only such objects may register into
46 * registries.
47 */
48export type ServeOptions = ReferencedServeOptions | HostServeOptions;
49
50export interface ReferencedServeOptions {
51 readonly lifetime?: "referenced";
52 /** Milliseconds an object stays alive after its last reference is released. */
53 readonly linger?: number;
54 /** Adapters for consumers built against older contract versions. */
55 readonly accepts?: Accepts;
56}
57
58export interface HostServeOptions {
59 readonly lifetime: "host";
60 /** An object of lifetime `"host"` lives as long as the host: it does not linger. */
61 readonly linger?: undefined;
62 /** Adapters for consumers built against older contract versions. */
63 readonly accepts?: Accepts;
64}
65
66/**
67 * The options `serve` accepts for `C`: `lifetime: "host"` only for a local type whose input has no required fields
68 * (the type's one object has the empty input).
69 */
70export type ServeOptionsFor<C extends AnyContract> = C extends LocalContract
71 ? Record<never, never> extends InputOf<C>
72 ? ServeOptions
73 : ReferencedServeOptions
74 : ReferencedServeOptions;
75
76export type Lifetime = "referenced" | "host";
77
78/** A type's factory. `P` is the app's principal type: `principal` is the caller the object is created for. */
79export type Factory<C extends AnyContract, P = unknown> = (
80 input: InputOf<C>,
81 principal: P,
82 self: Self<P>,
83) => ImplementationOf<C, P>;
84type AnyFactory = (input: unknown, principal: unknown, self: Self) => unknown;
85
86export interface Service {
87 readonly contract: AnyContract;
88 readonly factory: AnyFactory;
89 readonly options: ServeOptions;
90 readonly facet: string;
91}
92
93export const makeService = <C extends AnyContract>(
94 contract: C,
95 factory: Factory<C>,
96 options: ServeOptions,
97 facet: string,
98): Service => {
99 checkLifetime(contract, options);
100 return {
101 contract,
102 factory: factory as unknown as AnyFactory,
103 options: options as ServeOptions,
104 facet,
105 };
106};
107
108/** Whether objects of `service` have `lifetime: "host"`. */
109export const hostLifetime = (service: Service): boolean => service.options.lifetime === "host";
110
111/** Refuses lifetimes the type cannot have, when it is served. */
112function checkLifetime(contract: AnyContract, options: ServeOptions): void {
113 const lifetime = options.lifetime ?? "referenced";
114 if (lifetime !== "referenced" && lifetime !== "host")
115 throw new TypeError(`${contract.name}: unknown lifetime ${String(lifetime)}`);
116 if (lifetime !== "host") return;
117 if (contract.scope !== "local")
118 throw new TypeError(`${contract.name}: lifetime "host" needs a local type (remote types are referenced)`);
119 if (options.linger !== undefined)
120 throw new TypeError(
121 `${contract.name}: an object of lifetime "host" does not linger (it lives as long as the host)`,
122 );
123 try {
124 normalize(contract.input, {}, `${contract.name} input`);
125 } catch {
126 throw new TypeError(
127 `${contract.name}: lifetime "host" needs an input that accepts {} (the object's one address)`,
128 );
129 }
130}
131
132// ─── Declarations ────────────────────────────────────────────────────────────
133
134/** Options of `self.state`. */
135export interface StateOptions<T> {
136 /** The meaning of the cell's value (default 1). A reload that raises it runs `migrate`. */
137 readonly version?: number;
138 /**
139 * Maps the value of an older version (`from`) to this version's, at the reload that raised the version. The cell
140 * may be several versions behind. Without it, the value is kept and must fit the new schema.
141 */
142 readonly migrate?: (old: unknown, from: number) => T;
143}
144
145/**
146 * A cell's first value from its source: `init` runs after the object's resources are open and its references are live,
147 * before the object goes live, so no call, listener or subscriber sees a value that is not from the source. It runs in
148 * a root of its own (acting as the host principal) and may be async; the inits of one object run in parallel. Its
149 * value is validated against the schema; a throw or an invalid value fails the activation.
150 */
151export interface StateInit<T, P = unknown> {
152 readonly init: (ctx: Ctx<P>) => T | Promise<T>;
153}
154
155/** What a factory declares through. `P` is the app's principal type (`ctx.principal` of its listeners and tasks). */
156export interface Self<P = unknown> {
157 /**
158 * A state cell named `name`: its schema (required: there is no TypeScript at runtime) and its initial value
159 * (validated), or `{ init }` to read the first value from its source before the object goes live. The name identifies
160 * the cell across reloads: a reload keeps the cell and its value (`initial` is ignored, `init` does not run), migrates
161 * it when its version rises, and refuses a schema change without a version bump. A cell a reload adds runs its `init`
162 * while the reload prepares.
163 */
164 state<S extends TSchema>(
165 name: string,
166 schema: S,
167 initial: Static<S> | StateInit<Static<S>, P>,
168 options?: StateOptions<Static<S>>,
169 ): Cell<Static<S>>;
170 /** An object-owned reference, identified by its address. */
171 get<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions<P>): Ref<C>;
172 /**
173 * A resource named `name`: opened before the object goes live, closed after it is disposed. A reload keeps it unless
174 * its `version`, `deps` or `exclusive` changed.
175 */
176 resource<T>(name: string, declaration: ResourceDeclaration<T>): Resource<T>;
177 /**
178 * Reacts to `source` once the object is live: a readable (cell, derivation, reference state member) delivers its
179 * current value, then every new value; an event source (or a resource whose value is one) delivers its events.
180 * With `select`, subscribes to `select(value)` instead (the opened value for a resource). Each event runs `handler`
181 * in a fresh root. The name keeps the subscription across reloads while its source and `select` are unchanged; a
182 * listener on state whose source the reload replaced (a derivation is new at every reload) subscribes again and
183 * gets the current value again, so a handler of state must reconcile, not count.
184 */
185 on<S>(name: string, source: S, handler: (event: EventOf<S>, ctx: Ctx<P>) => void | Promise<void>): void;
186 on<S, E>(
187 name: string,
188 source: S,
189 select: (value: ValueOf<S>) => Subscribable<E>,
190 handler: (event: E, ctx: Ctx<P>) => void | Promise<void>,
191 ): void;
192 /** Long-running work of the live object (a code holder: its calls start fresh roots), restarted at every reload. */
193 task(fn: (ctx: Ctx<P>) => Promise<void>): void;
194 /** A synchronous projection of readables, recomputed when they change; a new one at every reload. */
195 derive<const S extends Sources, T>(sources: S, fn: (...values: SourceValues<S>) => T): Readable<T>;
196 /** Objects of lifetime `"host"` only. Keys are the registry's own keys. */
197 register<V>(registry: Registry<V>, entries: Readonly<Record<string, V>>): void;
198 /**
199 * A member backed by one of this object's resources, for local contracts: references read the resource's value once
200 * the object is live (`undefined` before). Typically an `opaque` member: `{ harness: self.expose(durable) }`.
201 */
202 expose<T>(resource: Resource<T>): Exposed<T>;
203}
204
205/** Runtime form of `Exposed<T>`. */
206class ExposedImpl {
207 readonly resource: ResourceImpl;
208 constructor(resource: ResourceImpl) {
209 this.resource = resource;
210 }
211}
212
213export class ResourceImpl<T = unknown> implements Resource<T> {
214 readonly key: string;
215 /** The declaration of the factory run whose code is current: a kept resource adopts the new one at commit. */
216 spec: ResourceDeclaration<T>;
217 readonly deps: readonly (RefCore | ResourceImpl)[];
218 /** `unavailable`: a close/reopen failed during a reload rollback; the value is gone for good. */
219 state: "closed" | "opening" | "open" | "unavailable" = "closed";
220 #value: T | undefined;
221
222 constructor(key: string, spec: ResourceDeclaration<T>, deps: readonly (RefCore | ResourceImpl)[]) {
223 this.key = key;
224 this.spec = spec;
225 this.deps = deps;
226 }
227
228 get value(): T {
229 if (this.state === "unavailable")
230 throw new ChordError("unavailable", `resource ${this.key} could not be restored`);
231 if (this.state !== "open") throw notReady(`resource ${this.key}`);
232 return this.#value as T;
233 }
234
235 get exclusive(): boolean {
236 return this.spec.exclusive === true;
237 }
238
239 /**
240 * Opens the resource. An open that completes after `signal` aborted (rollback, abandonment) closes the value it
241 * produced at once: nobody owns it any more.
242 */
243 async open(signal: AbortSignal, order: ResourceImpl[]): Promise<void> {
244 if (this.state !== "closed") return;
245 this.state = "opening";
246 let value: T;
247 try {
248 value = await this.spec.open({ signal });
249 } catch (error) {
250 this.state = "closed";
251 throw error;
252 }
253 if (signal.aborted) {
254 this.state = "closed";
255 await this.spec.close?.(value);
256 throw new ChordError("aborted", `resource ${this.key} opened after abort`);
257 }
258 this.#value = value;
259 this.state = "open";
260 order.push(this);
261 }
262
263 async close(order: ResourceImpl[]): Promise<void> {
264 if (this.state !== "open") return;
265 this.state = "closed";
266 const index = order.indexOf(this);
267 if (index !== -1) order.splice(index, 1);
268 const value = this.#value as T;
269 this.#value = undefined;
270 await this.spec.close?.(value);
271 }
272
273 markUnavailable(): void {
274 this.state = "unavailable";
275 this.#value = undefined;
276 }
277
278 /**
279 * A reload kept this resource (same version, deps and exclusivity): its later `close` is the new declaration's, and
280 * the old declaration (with the old code it closes over) is no longer referenced.
281 */
282 adopt(spec: ResourceDeclaration<T>): void {
283 this.spec = spec;
284 }
285}
286
287/**
288 * What `self.resources` returns: the resource, except that `.value` throws `not_ready` while any factory runs, even
289 * if the resource is open (a reload's prepare rerun must not touch the native resource the old code uses).
290 */
291class ResourceFacade<T> implements Resource<T> {
292 readonly #resource: ResourceImpl<T>;
293 readonly #host: HostCore;
294
295 constructor(resource: ResourceImpl<T>, host: HostCore) {
296 this.#resource = resource;
297 this.#host = host;
298 facades.set(this, resource as ResourceImpl);
299 }
300
301 get key(): string {
302 return this.#resource.key;
303 }
304
305 get value(): T {
306 if (this.#host.inFactory > 0) throw notReady(`resource ${this.key} (inside a factory)`);
307 return this.#resource.value;
308 }
309}
310
311const facades = new WeakMap<object, ResourceImpl>();
312const resourceOf = (value: unknown): ResourceImpl | undefined =>
313 value instanceof ResourceImpl ? value : value !== null && typeof value === "object" ? facades.get(value) : undefined;
314
315type TaskFn = (ctx: Ctx) => Promise<void>;
316
317/** Everything one factory run declared, by kind and key. */
318export class Decls {
319 readonly cells = new Map<string, Cell<unknown>>();
320 readonly cellSchemas = new Map<string, TSchema>();
321 readonly cellVersions = new Map<string, number>();
322 readonly cellMigrations = new Map<string, (old: unknown, from: number) => unknown>();
323 readonly refs = new Map<string, RefCore>();
324 readonly resources = new Map<string, ResourceImpl>();
325 /** Resources this run kept from the previous one, with this run's declarations (adopted at commit). */
326 readonly adopted = new Map<ResourceImpl, ResourceDeclaration<unknown>>();
327 readonly listeners = new Map<string, ListenerDecl>();
328 /** By position (`#0`, `#1`, …): tasks have no names. */
329 readonly tasks = new Map<string, TaskFn>();
330 /** By position: derivations have no names and are new at every run. */
331 readonly derives = new Map<string, Derived<unknown>>();
332 readonly registrations = new Map<string, Registration>();
333}
334
335type InitFn = (ctx: Ctx) => unknown;
336
337/** One factory run: its implementation, declarations and the objects it created (not reused from the previous run). */
338export interface Run {
339 readonly implementation: Record<string, unknown>;
340 readonly decls: Decls;
341 readonly created: {
342 readonly refs: RefCore[];
343 readonly resources: ResourceImpl[];
344 readonly derives: Derived<unknown>[];
345 /** Cells this run created with `init`, which fills them before they are used. */
346 readonly inits: (readonly [Cell<unknown>, InitFn])[];
347 };
348}
349
350const isStateInit = (value: unknown): value is StateInit<unknown> =>
351 value !== null && typeof value === "object" && typeof (value as { init?: unknown }).init === "function";
352
353export interface Installed {
354 readonly codeVersion: number;
355 readonly service: Service;
356 readonly implementation: Record<string, unknown>;
357 readonly decls: Decls;
358}
359
360// ─── Host interface the runtime pieces use ───────────────────────────────────
361
362export interface HostCore {
363 readonly name: string;
364 readonly dev: boolean;
365 readonly principal: unknown;
366 inFactory: number;
367 /** Set when a commit failed midway: the host admits no more work (terminal). */
368 readonly failed: unknown;
369 report(error: unknown): void;
370 currentCodeVersion(): number;
371 hasCodeVersion(codeVersion: number): boolean;
372 retainedCodeVersions(): Iterable<readonly [number, ReadonlyMap<string, Service>]>;
373 pendingCodeVersion(): number | undefined;
374 service(typeName: string): Service | undefined;
375 acquire(
376 type: AnyContract,
377 input: unknown,
378 options: GetOptions | undefined,
379 owner: RefOwner,
380 from?: ObjectImpl,
381 candidate?: boolean,
382 ): RefCore;
383 addressOf(type: AnyContract, input: unknown, principal: unknown, candidate?: boolean): string;
384 root<T>(fn: (ctx: Ctx) => T | Promise<T>, options?: { codeVersion?: number; signal?: AbortSignal }): Promise<T>;
385 touch(rootId: string, object: ObjectImpl): void;
386 forget(object: ObjectImpl): void;
387 /** The object finished its disposal. */
388 disposed(object: ObjectImpl): void;
389 /** Milliseconds a reload waits for aborted tasks to finish before starting their replacements. */
390 readonly taskStopDeadline: number;
391 /**
392 * Milliseconds an activation or a reload's prepare waits for its references to be ready and hydrated before it fails
393 * (`unavailable/ready_timeout`; a reference cycle across hosts never resolves).
394 */
395 readonly readyTimeout: number;
396 checkRegistrations(object: ObjectImpl, decls: Decls): void;
397 /** Rebuilds the current registry tables from live objects (plus `including`, which is finishing activation). */
398 registriesChanged(including?: ObjectImpl): void;
399}
400
401// ─── Contexts ────────────────────────────────────────────────────────────────
402
403export class CtxImpl implements Ctx {
404 readonly host: HostCore;
405 readonly signal: AbortSignal;
406 readonly rootId: string;
407 readonly codeVersion: number;
408 readonly principal: unknown;
409 /** Code holders (tasks): every call they make starts a fresh root. */
410 readonly holder: boolean;
411 readonly #refs: RefCore[] = [];
412 readonly #release: () => void;
413 /** Aborted when the ctx closes: awaited `get`s give up. */
414 readonly #closing = new AbortController();
415 #closed = false;
416
417 /** True after the call or root that received this ctx settled: it may no longer start work. */
418 get closed(): boolean {
419 return this.#closed;
420 }
421
422 /** Throws unless this ctx may start work on `host` (the called reference's host) now: not expired, aborted or foreign. */
423 check(host: HostCore | RemoteHost): void {
424 if (this.host !== host) throw invalid("foreign_ctx", "ctx belongs to another host");
425 if (this.#closed) throw new ChordError("aborted", "ctx expired: its call already settled", { reason: "expired" });
426 if (this.signal.aborted) {
427 const reason: unknown = this.signal.reason;
428 // A forced retirement aborted the root: its code version is gone, so the next call is `superseded` (retryable).
429 if (reason instanceof ChordError && reason.code === "superseded")
430 throw new ChordError("superseded", reason.message, { cause: reason });
431 throw new ChordError("aborted", "ctx aborted", { cause: reason });
432 }
433 }
434
435 /** `signals`: the ctx is aborted with the first of them; it stops following them when it closes. */
436 constructor(
437 host: HostCore,
438 fields: {
439 signals: readonly AbortSignal[];
440 rootId: string;
441 codeVersion: number;
442 principal: unknown;
443 holder?: boolean;
444 },
445 ) {
446 this.host = host;
447 const linked = linkedSignal(fields.signals);
448 this.signal = linked.signal;
449 this.#release = linked.release;
450 this.rootId = fields.rootId;
451 this.codeVersion = fields.codeVersion;
452 this.principal = fields.principal;
453 this.holder = fields.holder ?? false;
454 }
455
456 async get<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions): Promise<Ref<C>> {
457 this.check(this.host);
458 const ref = this.host.acquire(type, input, { principal: this.principal, ...options }, "call");
459 this.#refs.push(ref);
460 await awaitReady(ref, [this.signal, this.#closing.signal], this.host.readyTimeout);
461 return ref.proxy as Ref<C>;
462 }
463
464 /**
465 * A context for a call into `object`: same root and code version, its own call-owned references, aborted on forced
466 * disposal. Code inside an object acts as the host principal.
467 */
468 child(object: ObjectImpl): CtxImpl {
469 return new CtxImpl(this.host, {
470 signals: [this.signal, object.callAbort.signal],
471 rootId: this.rootId,
472 codeVersion: this.codeVersion,
473 principal: this.host.principal,
474 });
475 }
476
477 close(): void {
478 this.#closed = true;
479 this.#closing.abort(new ChordError("aborted", "ctx expired: its call already settled", { reason: "expired" }));
480 this.#release();
481 for (const ref of this.#refs.splice(0)) ref.release();
482 }
483}
484
485/**
486 * A signal aborted with the first of `sources` to abort, until `release()`. Not `AbortSignal.any`: Node keeps a
487 * dependant of a long-lived source (an object's or a code version's) reachable while it has abort listeners, so every
488 * call or task context would keep its listeners, and the code they close over, alive as long as the source.
489 */
490export function linkedSignal(sources: readonly AbortSignal[]): { readonly signal: AbortSignal; release(): void } {
491 const controller = new AbortController();
492 const detach: (() => void)[] = [];
493 const release = (): void => {
494 for (const remove of detach.splice(0)) remove();
495 };
496 for (const source of sources) {
497 if (source.aborted) {
498 release();
499 controller.abort(source.reason);
500 break;
501 }
502 const forward = (): void => {
503 release();
504 controller.abort(source.reason);
505 };
506 source.addEventListener("abort", forward, { once: true });
507 detach.push(() => source.removeEventListener("abort", forward));
508 }
509 return { signal: controller.signal, release };
510}
511
512/**
513 * Waits until `ref` is ready, at most `ms` and until a signal aborts; on failure the reference is released (only it: a
514 * binding other references share stays) and the error is rethrown: the activation error, `aborted`, or
515 * `unavailable/ready_timeout`.
516 */
517export async function awaitReady(ref: RefCore, signals: readonly AbortSignal[], ms: number): Promise<void> {
518 const timeout = new AbortController();
519 const timer = Number.isFinite(ms)
520 ? setTimeout(
521 () =>
522 timeout.abort(
523 new ChordError("unavailable", `${ref.address} was not ready after ${ms} ms`, {
524 reason: "ready_timeout",
525 }),
526 ),
527 ms,
528 )
529 : undefined;
530 (timer as { unref?: () => void } | undefined)?.unref?.();
531 const linked = linkedSignal([...signals, timeout.signal]);
532 try {
533 await raceSignal(ref.ready, linked.signal);
534 } catch (error) {
535 ref.release();
536 const reason: unknown = linked.signal.reason;
537 throw reason instanceof ChordError && reason.reason === "ready_timeout" ? reason : error;
538 } finally {
539 clearTimeout(timer);
540 linked.release();
541 }
542}
543
544export async function raceSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
545 if (signal.aborted) throw new ChordError("aborted", "call aborted", { cause: signal.reason });
546 let onAbort = noop;
547 const aborted = new Promise<never>((_, reject) => {
548 onAbort = () => reject(new ChordError("aborted", "call aborted", { cause: signal.reason }));
549 signal.addEventListener("abort", onAbort, { once: true });
550 });
551 try {
552 return await Promise.race([promise, aborted]);
553 } finally {
554 signal.removeEventListener("abort", onAbort);
555 }
556}
557
558// ─── References ─────────────────────────────────────────────────────────────────
559
560/** Who a reference belongs to. `connection`: a peer host over a link; `client`: a browser (not a reload participant). */
561export type RefOwner = "object" | "call" | "host" | "external" | "connection" | "client";
562
563/** A claim on an object: a local `RefImpl`, or a `RemoteRef` on another host (no object here). */
564export interface RefCore {
565 readonly address: string;
566 readonly contract: AnyContract;
567 readonly status: RefStatus;
568 readonly ready: Promise<void>;
569 readonly proxy: object;
570 readonly object: ObjectImpl | undefined;
571 release(): void;
572}
573
574export const REF_BASE: ReadonlySet<PropertyKey> = new Set([
575 "contract",
576 "status",
577 "ready",
578 "variant",
579 "shape",
580 "error",
581 "onShape",
582 "onStatus",
583 "release",
584]);
585
586export type StatusListener = (status: RefStatus, error: unknown) => void;
587
588/** Queues a status notification (after the change that caused it is complete, like every publication). */
589export function notifyStatus(
590 listeners: ReadonlySet<StatusListener>,
591 status: RefStatus,
592 error: unknown,
593 report: (error: unknown) => void,
594): void {
595 if (listeners.size === 0) return;
596 const current = [...listeners];
597 enqueue(() => {
598 for (const listener of current) {
599 try {
600 listener(status, error);
601 } catch (thrown) {
602 report(thrown);
603 }
604 }
605 });
606}
607
608/** Proxy → reference, for `deps: [ref]` and links. */
609export const refsByProxy = new WeakMap<object, RefCore>();
610export const refOf = (value: unknown): RefCore | undefined =>
611 value !== null && typeof value === "object" ? refsByProxy.get(value) : undefined;
612
613/**
614 * A reference's state member: a stable readable that follows whatever source the current implementation exposes under
615 * that name. Reading throws `not_ready` until the reference is live, `not_in_variant` while the variant lacks the
616 * member. A listener added before the member is readable gets its snapshot then. Rebinding (reload, variant) delivers a
617 * reset. Upstream is subscribed only while someone listens.
618 */
619class MemberReadable implements Readable<unknown> {
620 readonly #ref: RefImpl;
621 readonly #name: string;
622 readonly #values = new Set<(value: unknown) => void>();
623 readonly #events = new Set<(event: StateEvent<unknown>) => void>();
624 /** Event listeners that have not had their snapshot yet (added while the member was not readable). */
625 readonly #unseen = new Set<(event: StateEvent<unknown>) => void>();
626 #source: Readable<unknown> | undefined;
627 #upstream = noop;
628 /** The value listeners last saw; a first upstream snapshot equal to it is not re-announced. */
629 #seen: { readonly value: unknown } | undefined;
630
631 constructor(ref: RefImpl, name: string) {
632 this.#ref = ref;
633 this.#name = name;
634 }
635
636 get value(): unknown {
637 const ref = this.#ref;
638 if (ref.status === "released" || ref.status === "gone") throw ref.terminalError();
639 if (ref.status !== "live") throw notReady(`${ref.address}.${this.#name}`);
640 const view = ref.currentView();
641 if (view === undefined) throw notReady(`${ref.address}.${this.#name}`);
642 const source = this.#current();
643 if (source === undefined) {
644 throw new ChordError(
645 "not_in_variant",
646 `${ref.address}: ${this.#name} is not a state member of variant ${variantOf(view) ?? "(local)"}`,
647 );
648 }
649 return source.value;
650 }
651
652 /** Not hydrated while the reference is not live, or while its source (a forwarded remote member) is not. */
653 get [HYDRATION](): Hydration | undefined {
654 const ref = this.#ref;
655 if (ref.status === "live") return hydrationOf(this.#current());
656 return {
657 hydrated: false,
658 whenHydrated: async () => {
659 await ref.ready;
660 await hydrationOf(this.#current())?.whenHydrated();
661 },
662 };
663 }
664
665 subscribe(listener: (value: unknown) => void): () => void {
666 this.#values.add(listener);
667 const source = this.#readable();
668 if (source !== undefined) {
669 this.#seen = { value: source.value };
670 this.#safe(() => listener(source.value));
671 }
672 this.bind();
673 return () => this.#remove(this.#values, listener);
674 }
675
676 events(listener: (event: StateEvent<unknown>) => void): () => void {
677 this.#events.add(listener);
678 const source = this.#readable();
679 if (source !== undefined) {
680 const value = source.value;
681 this.#seen = { value };
682 this.#safe(() => listener({ type: "snap", value }));
683 } else this.#unseen.add(listener);
684 this.bind();
685 return () => {
686 this.#unseen.delete(listener);
687 this.#remove(this.#events, listener);
688 };
689 }
690
691 /** (Re)subscribes upstream to the current source; a changed source is announced as a reset. */
692 bind(): void {
693 const source = this.#values.size + this.#events.size > 0 ? this.#current() : undefined;
694 if (source === this.#source) return;
695 this.#upstream();
696 this.#upstream = noop;
697 this.#source = source;
698 if (source === undefined) return;
699 let first = true;
700 this.#upstream = source.events((event) => {
701 const isFirst = first;
702 first = false;
703 if (isFirst && this.#unseen.size === 0 && this.#seen !== undefined && event.value === this.#seen.value) return;
704 this.#seen = { value: event.value };
705 const translated: StateEvent<unknown> = isFirst ? { type: "reset", value: event.value } : event;
706 const events = [...this.#events];
707 const values = [...this.#values];
708 const unseen = new Set(this.#unseen);
709 this.#unseen.clear();
710 // Queued: a rebind during a commit must not run observers before the commit completes.
711 enqueue(() => {
712 for (const listener of events) {
713 if (!this.#events.has(listener)) continue;
714 const delivered: StateEvent<unknown> = unseen.has(listener)
715 ? { type: "snap", value: event.value }
716 : translated;
717 this.#safe(() => listener(delivered));
718 }
719 for (const listener of values) if (this.#values.has(listener)) this.#safe(() => listener(event.value));
720 });
721 });
722 }
723
724 stop(): void {
725 this.#values.clear();
726 this.#events.clear();
727 this.#unseen.clear();
728 this.bind();
729 }
730
731 #current(): Readable<unknown> | undefined {
732 const view = this.#ref.currentView();
733 if (view === undefined || !this.#ref.inVariant(view, this.#name)) return undefined;
734 const value = view[this.#name];
735 // Cells and derivations, or any readable an `accepts` adapter maps them to.
736 return isSource(value) || isReadableLike(value) ? (value as Readable<unknown>) : undefined;
737 }
738
739 /** The current source if its value can be read now (live, in the variant, hydrated). */
740 #readable(): Readable<unknown> | undefined {
741 const source = this.#current();
742 return source === undefined || hydrationOf(source)?.hydrated === false ? undefined : source;
743 }
744
745 #remove<T>(set: Set<T>, listener: T): void {
746 set.delete(listener);
747 this.bind();
748 }
749
750 #safe(fn: () => void): void {
751 try {
752 fn();
753 } catch (error) {
754 this.#ref.object.host.report(error);
755 }
756 }
757}
758
759/** One reference on an object. Exposed through a Proxy so members bind late to the current implementation. */
760export class RefImpl {
761 readonly object: ObjectImpl;
762 readonly contract: AnyContract;
763 readonly owner: RefOwner;
764 readonly address: string;
765 readonly proxy: object;
766 readonly ready: Promise<void>;
767 status: RefStatus;
768 error: unknown;
769 readonly shapeListeners = new Set<(shape: Shape) => void>();
770 /** Internal: notified when the reference becomes gone (links forward it). */
771 readonly goneListeners = new Set<(error: unknown) => void>();
772 readonly readables = new Map<string, MemberReadable>();
773 /** Weak: a retired code version's service (and the factory code it holds) must not be kept alive by its consumers. */
774 readonly bindings = new WeakMap<Service, Adapter | undefined>();
775 readonly views = new WeakMap<Record<string, unknown>, Record<string, unknown>>();
776 readonly callers = new Map<string, (...given: unknown[]) => Promise<unknown>>();
777
778 constructor(object: ObjectImpl, contract: AnyContract, owner: RefOwner) {
779 this.object = object;
780 this.contract = contract;
781 this.owner = owner;
782 this.address = object.address;
783 this.status = object.status === "live" ? "live" : "loading";
784 this.ready = object.ready.then(() => {
785 if (this.status === "gone") throw this.error;
786 if (this.status === "released") throw new ChordError("released", `reference ${this.address} released`);
787 });
788 this.ready.catch(noop);
789 this.proxy = new Proxy(this, {
790 get: (target, property) => {
791 if (REF_BASE.has(property)) {
792 const value: unknown = Reflect.get(target, property, target);
793 return typeof value === "function" ? value.bind(target) : value;
794 }
795 if (typeof property !== "string" || property === "then") return undefined;
796 return target.member(property);
797 },
798 has: (target, property) => REF_BASE.has(property) || target.member(String(property)) !== undefined,
799 });
800 refsByProxy.set(this.proxy, this);
801 }
802
803 get variant(): string | undefined {
804 const view = this.currentView();
805 return view === undefined ? undefined : variantOf(view);
806 }
807
808 get shape(): Shape | undefined {
809 const installed = this.status === "live" ? this.object.currentInstalled() : undefined;
810 const view = installed === undefined ? undefined : this.#safeView(installed);
811 if (installed === undefined || view === undefined) return undefined;
812 return {
813 variant: variantOf(view),
814 members: Object.keys(view).filter((key) => key !== "variant"),
815 contract: installed.service.contract.fingerprint,
816 };
817 }
818
819 onShape(listener: (shape: Shape) => void): () => void {
820 this.shapeListeners.add(listener);
821 return () => this.shapeListeners.delete(listener);
822 }
823
824 onStatus(listener: StatusListener): () => void {
825 this.#statusListeners.add(listener);
826 return () => this.#statusListeners.delete(listener);
827 }
828
829 readonly #statusListeners = new Set<StatusListener>();
830
831 #statusChanged(): void {
832 notifyStatus(this.#statusListeners, this.status, this.error, (error) => this.object.host.report(error));
833 }
834
835 release(): void {
836 if (this.status === "released" || this.status === "gone") return;
837 this.status = "released";
838 this.#stopReadables();
839 this.#statusChanged();
840 this.object.release(this);
841 }
842
843 // ─── internal ───
844
845 live(): void {
846 if (this.status !== "loading") return;
847 this.status = "live";
848 this.#statusChanged();
849 this.shapeChanged();
850 }
851
852 gone(error: unknown): void {
853 if (this.status === "released" || this.status === "gone") return;
854 this.status = "gone";
855 this.error = error;
856 this.#stopReadables();
857 this.#statusChanged();
858 for (const listener of [...this.goneListeners]) listener(error);
859 }
860
861 shapeChanged(): void {
862 for (const readable of this.readables.values()) readable.bind();
863 const shape = this.shape;
864 if (shape === undefined) return;
865 const listeners = [...this.shapeListeners];
866 enqueue(() => {
867 for (const listener of listeners) {
868 try {
869 listener(shape);
870 } catch (error) {
871 this.object.host.report(error);
872 }
873 }
874 });
875 }
876
877 terminalError(): unknown {
878 return this.status === "gone" ? this.error : new ChordError("released", `reference ${this.address} released`);
879 }
880
881 /** The implementation as this consumer sees it (through an accepts adapter when bound to another version). */
882 viewOf(installed: Installed): Record<string, unknown> {
883 let adapter = this.bindings.get(installed.service);
884 if (!this.bindings.has(installed.service)) {
885 adapter = bind(installed.service.contract, installed.service.options.accepts, this.contract);
886 this.bindings.set(installed.service, adapter);
887 }
888 if (adapter === undefined) return installed.implementation;
889 let view = this.views.get(installed.implementation);
890 if (view === undefined) {
891 view = adapter(installed.implementation);
892 this.views.set(installed.implementation, view);
893 }
894 return view;
895 }
896
897 currentView(): Record<string, unknown> | undefined {
898 if (this.status !== "live") return undefined;
899 const installed = this.object.currentInstalled();
900 return installed === undefined ? undefined : this.#safeView(installed);
901 }
902
903 /** The view, or undefined when this consumer no longer binds (reported; calls reject with the bind error). */
904 #safeView(installed: Installed): Record<string, unknown> | undefined {
905 try {
906 return this.viewOf(installed);
907 } catch (error) {
908 this.object.host.report(error);
909 return undefined;
910 }
911 }
912
913 describe(variant: string | undefined, member: string): MemberDescription | undefined {
914 const variants = this.contract.description.variants;
915 if (variant !== undefined) return variants[variant]?.[member];
916 for (const members of Object.values(variants)) if (members[member] !== undefined) return members[member];
917 return undefined;
918 }
919
920 /** Remote consumers see only the members their contract lists for the current variant. */
921 inVariant(view: Record<string, unknown>, name: string): boolean {
922 return this.contract.scope !== "remote" || this.describe(variantOf(view), name) !== undefined;
923 }
924
925 member(name: string): unknown {
926 const declared = this.describe(undefined, name);
927 const view = this.currentView();
928 const value = view?.[name];
929 if (declared?.kind === "method" || (declared === undefined && typeof value === "function")) {
930 return this.caller(name);
931 }
932 if (declared?.kind === "state" || (declared === undefined && (isSource(value) || isReadableLike(value)))) {
933 let readable = this.readables.get(name);
934 if (readable === undefined) {
935 readable = new MemberReadable(this, name);
936 this.readables.set(name, readable);
937 }
938 return readable;
939 }
940 if (view === undefined || !this.inVariant(view, name)) return undefined;
941 return value instanceof ExposedImpl ? value.resource.value : value;
942 }
943
944 caller(name: string): (...given: unknown[]) => Promise<unknown> {
945 let caller = this.callers.get(name);
946 if (caller === undefined) {
947 const noArgs = takesNoArgs(this.contract, name);
948 caller = (...given) => {
949 // A method without arguments is called as `ref.name(ctx)`.
950 const [args, ctx] = (noArgs ? [undefined, given[0]] : given) as [unknown, Ctx | undefined];
951 if (this.object.host.inFactory > 0) {
952 throw new ChordError("not_ready", `${this.address}.${name} called inside a factory`);
953 }
954 if (ctx !== undefined && !(ctx instanceof CtxImpl)) {
955 return Promise.reject(invalid("foreign_ctx", "ctx must come from a Chord host"));
956 }
957 if (ctx === undefined || ctx.holder) {
958 // A code holder (task) starts a fresh root per call, cancelled with the holder.
959 try {
960 ctx?.check(this.object.host);
961 } catch (error) {
962 return Promise.reject(error);
963 }
964 return this.object.host.root((root) => this.object.call(this, name, args, root as CtxImpl), {
965 signal: ctx?.signal,
966 });
967 }
968 return this.object.call(this, name, args, ctx);
969 };
970 this.callers.set(name, caller);
971 }
972 return caller;
973 }
974
975 #stopReadables(): void {
976 for (const readable of this.readables.values()) readable.stop();
977 }
978}
979
980export const variantOf = (implementation: Record<string, unknown>): string | undefined =>
981 typeof implementation.variant === "string" ? implementation.variant : undefined;
982
983// ─── Objects ─────────────────────────────────────────────────────────────────
984
985export type ObjectStatus = "activating" | "live" | "failed" | "disposing" | "disposed";
986
987interface Gate {
988 readonly grandfathered: Set<string>;
989 readonly queue: { readonly key: string; readonly event: unknown }[];
990 drained: () => void;
991}
992
993interface Subscription {
994 /** What the listener was declared on: the resource (not its facade), or the source itself. */
995 readonly origin: unknown;
996 readonly select: ListenerDecl["select"];
997 unsubscribe: () => void;
998}
999
1000/**
1001 * Two `select` functions are the same if they are identical or have the same source text: an inline arrow is a new
1002 * object on every factory run, but its code is what matters. (A select whose implementation depends on captured values
1003 * that change between runs is not detected; such a listener keeps its old subscription until its source changes.)
1004 */
1005const sameSelect = (a: ListenerDecl["select"], b: ListenerDecl["select"]): boolean =>
1006 a === b || (a !== undefined && b !== undefined && String(a) === String(b));
1007
1008/** Listener subscriptions made ahead of a commit: `activate` switches over, `discard` drops them. */
1009export interface StagedListeners {
1010 activate(): void;
1011 discard(): void;
1012}
1013
1014interface RunningTask {
1015 readonly controller: AbortController;
1016 readonly done: Promise<void>;
1017}
1018
1019export interface ObjectIdentity {
1020 readonly address: string;
1021 readonly typeName: string;
1022 readonly input: unknown;
1023 readonly principal: unknown;
1024 /** The one object of a `lifetime: "host"` type. */
1025 readonly hostLifetime: boolean;
1026}
1027
1028export class ObjectImpl {
1029 readonly host: HostCore;
1030 readonly address: string;
1031 readonly typeName: string;
1032 readonly input: unknown;
1033 readonly principal: unknown;
1034 /** The one object of a `lifetime: "host"` type: only such objects may register. */
1035 readonly hostLifetime: boolean;
1036 status: ObjectStatus = "activating";
1037 ready: Promise<void> = Promise.resolve();
1038 service: Service | undefined;
1039 /** Calls carrying an older code version are rejected upgrade_conflict (state bump or exclusive resource replaced). */
1040 minCodeVersion = 0;
1041 decls = new Decls();
1042 /** Declarations of a factory run that has not been installed yet (activation or reload candidate). */
1043 readonly pending = new Set<Decls>();
1044 readonly implementations = new Map<number, Installed>();
1045 readonly refs = new Set<RefImpl>();
1046 readonly leases = new Map<string, number>();
1047 readonly openOrder: ResourceImpl[] = [];
1048 readonly callAbort = new AbortController();
1049 readonly activationAbort = new AbortController();
1050 gate: Gate | undefined;
1051 /** Served only by a running reload's pending code version: listeners, tasks and registrations start at its commit. */
1052 deferredRuntime = false;
1053 readonly #subscriptions = new Map<string, Subscription>();
1054 readonly #invocations = new Set<Promise<unknown>>();
1055 #tasks = new Map<string, RunningTask>();
1056 /** Aborted task runs that have not finished yet. */
1057 readonly #stopped = new Set<Promise<void>>();
1058 /** Bumped by every start and stop of the tasks: a delayed start that is no longer the latest is dropped. */
1059 #taskRuns = 0;
1060 #linger: ReturnType<typeof setTimeout> | undefined;
1061 #disposal: Promise<void> | undefined;
1062
1063 constructor(host: HostCore, identity: ObjectIdentity) {
1064 this.host = host;
1065 this.address = identity.address;
1066 this.typeName = identity.typeName;
1067 this.input = identity.input;
1068 this.principal = identity.principal;
1069 this.hostLifetime = identity.hostLifetime;
1070 }
1071
1072 start(after: Promise<void> | undefined): void {
1073 this.ready = this.#activate(after).then(
1074 () => {
1075 for (const ref of this.refs) ref.live();
1076 this.#maybeIdle();
1077 },
1078 (cause: unknown) => {
1079 if (this.status === "activating") this.status = "failed";
1080 this.host.forget(this);
1081 // A ChordError (forbidden, a dependency's error, ...) keeps its code; anything else is `unavailable`.
1082 const error = asChordError(cause, `activating ${this.address}`);
1083 for (const ref of this.refs) ref.gone(error);
1084 throw error;
1085 },
1086 );
1087 this.ready.catch(noop);
1088 }
1089
1090 /**
1091 * Activation as one transaction: factory, opens, then a synchronous finalization (registry check and publication,
1092 * implementations, runtime). Every failure, including one during finalization or a release while listeners start,
1093 * unwinds everything this activation did.
1094 */
1095 async #activate(after: Promise<void> | undefined): Promise<void> {
1096 await after?.catch(noop);
1097 const signal = this.activationAbort.signal;
1098 const abandoned = (): ChordError => new ChordError("aborted", `${this.address} abandoned`);
1099 if (signal.aborted) throw abandoned();
1100 const service = this.host.service(this.typeName);
1101 if (service === undefined)
1102 throw new ChordError("unavailable", `${this.typeName} is not served`, { reason: "unknown_type" });
1103 this.service = service;
1104 const run = this.run(service, undefined);
1105 try {
1106 await this.open(run.created.resources, run.created.refs, signal);
1107 if (signal.aborted) throw abandoned();
1108 await this.waitHydrated(run);
1109 if (signal.aborted) throw abandoned();
1110 await this.initCells(run, signal);
1111 if (signal.aborted) throw abandoned();
1112 this.host.checkRegistrations(this, run.decls);
1113 this.decls = run.decls;
1114 for (const [retained, services] of this.host.retainedCodeVersions()) {
1115 if (services.get(this.typeName) === service) {
1116 this.implementations.set(retained, {
1117 codeVersion: retained,
1118 service,
1119 implementation: run.implementation,
1120 decls: run.decls,
1121 });
1122 }
1123 }
1124 const pending = this.host.pendingCodeVersion();
1125 if (
1126 !this.implementations.has(this.host.currentCodeVersion()) &&
1127 (pending === undefined || !this.implementations.has(pending))
1128 ) {
1129 throw new ChordError("superseded", `${this.address}: code changed during activation`);
1130 }
1131 for (const derived of run.created.derives) derived.attach();
1132 this.refreshSchemas();
1133 // Served only by a running reload's pending code version: new code must not run (listeners, tasks,
1134 // registrations) before that reload commits.
1135 this.deferredRuntime = !this.implementations.has(this.host.currentCodeVersion());
1136 if (!this.deferredRuntime) {
1137 if (run.decls.registrations.size > 0) this.host.registriesChanged(this);
1138 this.startRuntime();
1139 }
1140 // A listener starting up may have released the last reference synchronously: no resurrection.
1141 if (signal.aborted) throw abandoned();
1142 this.status = "live";
1143 } catch (error) {
1144 // Invocations started during finalization (listener roots) end before their resources close.
1145 this.callAbort.abort(error);
1146 this.stopListeners();
1147 this.stopTasks();
1148 const registered = this.decls.registrations.size > 0 && !this.deferredRuntime;
1149 this.implementations.clear();
1150 this.decls = new Decls();
1151 if (registered) this.host.registriesChanged();
1152 await Promise.allSettled([...this.#invocations, ...this.#stopped]);
1153 await this.unwind(run).catch((cleanup: unknown) => this.host.report(cleanup));
1154 throw error;
1155 } finally {
1156 this.pending.delete(run.decls);
1157 }
1158 }
1159
1160 /**
1161 * Runs the factory synchronously. With `previous`, runs in recording mode for a reload prepare. The run's
1162 * declarations stay in `pending` (visible to the cycle check) until the caller installs or discards them.
1163 */
1164 run(service: Service, previous: Decls | undefined): Run {
1165 const self = new SelfImpl(this, previous);
1166 const discard = (run: Run): void => {
1167 this.pending.delete(run.decls);
1168 void this.unwind(run).catch((cleanup: unknown) => this.host.report(cleanup));
1169 };
1170 this.pending.add(self.run(undefined).decls);
1171 this.host.inFactory++;
1172 let implementation: unknown;
1173 try {
1174 implementation = service.factory(this.input, this.principal, self);
1175 } catch (error) {
1176 this.host.inFactory--;
1177 discard(self.run(undefined));
1178 throw error;
1179 }
1180 this.host.inFactory--;
1181 const run = self.run(implementation);
1182 try {
1183 if (implementation instanceof Promise)
1184 throw invalid("implementation", `${this.typeName}: factories must be synchronous`);
1185 validateImplementation(service, run.implementation);
1186 } catch (error) {
1187 discard(run);
1188 throw error;
1189 }
1190 return run;
1191 }
1192
1193 /** Opens resources (dependencies first) and waits for references; settles all before failing. */
1194 async open(resources: readonly ResourceImpl[], refs: readonly RefCore[], signal: AbortSignal): Promise<void> {
1195 const opening = new Map<ResourceImpl, Promise<void>>();
1196 const openOne = (resource: ResourceImpl): Promise<void> => {
1197 let promise = opening.get(resource);
1198 if (promise === undefined) {
1199 promise = (async () => {
1200 await Promise.all(
1201 resource.deps.map((dep) =>
1202 !(dep instanceof ResourceImpl) ? dep.ready : resources.includes(dep) ? openOne(dep) : undefined,
1203 ),
1204 );
1205 await resource.open(signal, this.openOrder);
1206 })();
1207 opening.set(resource, promise);
1208 }
1209 return promise;
1210 };
1211 const ready = this.withinReadyTimeout(Promise.all(refs.map((ref) => ref.ready)), () =>
1212 refs.filter((ref) => ref.status === "loading").map((ref) => ref.address),
1213 );
1214 const results = await Promise.allSettled([...resources.map(openOne), ready]);
1215 const failure = results.find((result) => result.status === "rejected");
1216 if (failure !== undefined) throw failure.reason;
1217 }
1218
1219 /**
1220 * Waits until the state sources a run exposes or derives from have their values: a local object goes live only with
1221 * its state, also where it forwards or derives from a remote reference's member.
1222 */
1223 async waitHydrated(run: Run): Promise<void> {
1224 const exposed = Object.entries(run.implementation ?? {});
1225 const pending = unhydrated([...run.created.derives, ...exposed.map(([, value]) => value)]);
1226 if (pending.length === 0) return;
1227 await this.withinReadyTimeout(Promise.all(pending.map((hydration) => hydration.whenHydrated())), () => [
1228 ...exposed
1229 .filter(([, value]) => hydrationOf(value)?.hydrated === false)
1230 .map(([name]) => `${this.address}.${name}`),
1231 ...run.created.derives
1232 .filter((derived) => hydrationOf(derived) !== undefined)
1233 .map((derived) => `derive ${derived.key}`),
1234 ]);
1235 }
1236
1237 /** `work` within the host's `readyTimeout`; a timeout names what is still awaited. */
1238 async withinReadyTimeout<T>(work: Promise<T>, waiting: () => readonly string[]): Promise<T> {
1239 const ms = this.host.readyTimeout;
1240 if (!Number.isFinite(ms)) return work;
1241 let timer: ReturnType<typeof setTimeout> | undefined;
1242 const timeout = new Promise<never>((_, reject) => {
1243 timer = setTimeout(() => {
1244 const list = waiting();
1245 reject(
1246 new ChordError(
1247 "unavailable",
1248 `${this.address} was not ready after ${ms} ms${list.length === 0 ? "" : `, waiting on ${list.join(", ")}`} (a reference cycle across hosts?)`,
1249 { reason: "ready_timeout" },
1250 ),
1251 );
1252 }, ms);
1253 (timer as { unref?: () => void }).unref?.();
1254 });
1255 timeout.catch(noop);
1256 try {
1257 return await Promise.race([work, timeout]);
1258 } finally {
1259 clearTimeout(timer);
1260 }
1261 }
1262
1263 /**
1264 * Fills the cells `run` created with `init`, each in a root of its own, in parallel; settles all before failing. Runs
1265 * after the run's resources are open and its references live, before anything reads the cells.
1266 */
1267 async initCells(run: Run, signal: AbortSignal): Promise<void> {
1268 if (run.created.inits.length === 0) return;
1269 const results = await Promise.allSettled(
1270 run.created.inits.map(async ([cell, init]) => {
1271 const value = await this.host.root((ctx) => init(ctx), { signal });
1272 if (!signal.aborted) cell.initialize(value);
1273 }),
1274 );
1275 const failure = results.find((result) => result.status === "rejected");
1276 if (failure !== undefined) throw failure.reason;
1277 }
1278
1279 /** Undoes the objects a run created: closes its resources (reverse order) and releases its references. */
1280 async unwind(run: Run): Promise<void> {
1281 for (const derived of run.created.derives) derived.detach();
1282 const resources = [...run.created.resources].sort(
1283 (a, b) => this.openOrder.indexOf(b) - this.openOrder.indexOf(a),
1284 );
1285 await runAll(
1286 [
1287 ...resources.map((resource) => () => resource.close(this.openOrder)),
1288 ...run.created.refs.map((ref) => () => ref.release()),
1289 ],
1290 `${this.address}: cleanup failed`,
1291 );
1292 }
1293
1294 currentInstalled(): Installed | undefined {
1295 return this.implementations.get(this.host.currentCodeVersion()) ?? [...this.implementations.values()].at(-1);
1296 }
1297
1298 /** Every state source exposed as a remote state member gets that member's schema (checked per write in dev mode). */
1299 refreshSchemas(): void {
1300 const schemas = new Map<Readable<unknown>, TSchema[]>();
1301 for (const installed of this.implementations.values()) {
1302 for (const [source, list] of memberSchemas(installed.service, installed.implementation)) {
1303 schemas.set(source, [...(schemas.get(source) ?? []), ...list]);
1304 }
1305 }
1306 for (const decls of this.allDecls()) {
1307 for (const source of [...decls.cells.values(), ...decls.derives.values()])
1308 source.schemas = schemas.get(source) ?? [];
1309 }
1310 }
1311
1312 allDecls(): Set<Decls> {
1313 const result = new Set<Decls>([this.decls, ...this.pending]);
1314 for (const installed of this.implementations.values()) result.add(installed.decls);
1315 return result;
1316 }
1317
1318 // ─── runtime: listeners and tasks of the current declarations ───
1319
1320 /** The resource a listener is declared on, or its source itself. */
1321 #origin(decl: ListenerDecl): unknown {
1322 return resourceOf(decl.source) ?? decl.source;
1323 }
1324
1325 /** Resolves a listener's subscribable: `select(resource value)`, `select(source)` or the source itself. */
1326 #listenSource(key: string, decl: ListenerDecl): Subscribable<unknown> {
1327 const resource = resourceOf(decl.source);
1328 const value = resource === undefined ? decl.source : resource.value;
1329 const source = (decl.select === undefined ? value : decl.select(value as never)) as Subscribable<unknown>;
1330 if (typeof source?.subscribe !== "function")
1331 throw invalid("implementation", `listener ${key}: source has no subscribe()`);
1332 return source;
1333 }
1334
1335 /**
1336 * Subscribes the listeners of `decls` without delivering: events are buffered until `activate`. A listener declared
1337 * on the same resource (or source) with the same `select` keeps its subscription without calling `select` again
1338 * (only its function is swapped, by name), so sources that accept a single subscriber survive reloads. Throws, with
1339 * nothing left subscribed, if any source fails.
1340 */
1341 stageListeners(decls: Decls): StagedListeners {
1342 type Fresh = Subscription & { buffer: unknown[] | undefined; subscribe?: () => void };
1343 const fresh = new Map<string, Fresh>();
1344 const kept = new Set<string>();
1345 try {
1346 for (const [key, decl] of decls.listeners) {
1347 const origin = this.#origin(decl);
1348 const previous = this.#subscriptions.get(key);
1349 if (previous !== undefined && previous.origin === origin && sameSelect(previous.select, decl.select)) {
1350 kept.add(key);
1351 continue;
1352 }
1353 const source = this.#listenSource(key, decl);
1354 const entry: Fresh = {
1355 origin,
1356 select: decl.select,
1357 unsubscribe: noop,
1358 buffer: [],
1359 };
1360 fresh.set(key, entry);
1361 // State (a readable) is subscribed when the listener activates: it delivers the value current then, not one
1362 // of the candidate before the commit (a new derivation computes its value at the commit).
1363 if (isSource(source) || isReadableLike(source)) {
1364 entry.buffer = undefined;
1365 entry.subscribe = () => {
1366 entry.unsubscribe = source.subscribe((event) => this.#deliver(key, event));
1367 };
1368 continue;
1369 }
1370 entry.unsubscribe = source.subscribe((event) => {
1371 if (entry.buffer !== undefined) entry.buffer.push(event);
1372 else this.#deliver(key, event);
1373 });
1374 }
1375 } catch (error) {
1376 for (const entry of fresh.values()) entry.unsubscribe();
1377 throw error;
1378 }
1379 return {
1380 activate: () => {
1381 for (const [key, subscription] of this.#subscriptions) {
1382 if (kept.has(key)) continue;
1383 subscription.unsubscribe();
1384 this.#subscriptions.delete(key);
1385 }
1386 for (const [key, entry] of fresh) {
1387 this.#subscriptions.set(key, entry);
1388 entry.subscribe?.();
1389 const buffered = entry.buffer ?? [];
1390 entry.buffer = undefined;
1391 for (const event of buffered) this.#deliver(key, event);
1392 }
1393 },
1394 discard: () => {
1395 for (const entry of fresh.values()) entry.unsubscribe();
1396 },
1397 };
1398 }
1399
1400 startRuntime(): void {
1401 this.stageListeners(this.decls).activate();
1402 this.startTasks();
1403 }
1404
1405 /**
1406 * Starts the tasks of the current declarations. Runs aborted by `stopTasks` (a reload, a gate) may still be finishing:
1407 * their replacements start once they all finished, or after `taskStopDeadline` (reported), so the old and the new run
1408 * of a task never work side by side. A later start or stop, or the object leaving `live`, cancels a delayed start.
1409 */
1410 startTasks(): void {
1411 const run = ++this.#taskRuns;
1412 const start = (): void => {
1413 for (const key of this.decls.tasks.keys()) this.#startTask(key, this.host.currentCodeVersion());
1414 };
1415 if (this.#stopped.size === 0) {
1416 start();
1417 return;
1418 }
1419 const deadline = this.host.taskStopDeadline;
1420 let timer: ReturnType<typeof setTimeout> | undefined;
1421 const late = new Promise<boolean>((resolve) => {
1422 timer = setTimeout(() => resolve(true), deadline);
1423 });
1424 const stopped = Promise.allSettled([...this.#stopped]).then(() => false);
1425 void Promise.race([stopped, late]).then((missed) => {
1426 clearTimeout(timer);
1427 if (run !== this.#taskRuns || this.status !== "live") return;
1428 if (missed) {
1429 this.host.report(
1430 new ChordError(
1431 "aborted",
1432 `${this.address}: aborted tasks still running after ${deadline} ms; starting their replacements anyway`,
1433 ),
1434 );
1435 }
1436 start();
1437 });
1438 }
1439
1440 stopListeners(): void {
1441 for (const subscription of this.#subscriptions.values()) subscription.unsubscribe();
1442 this.#subscriptions.clear();
1443 }
1444
1445 #startTask(key: string, codeVersion: number): void {
1446 const fn = this.decls.tasks.get(key);
1447 if (fn === undefined) return;
1448 const controller = new AbortController();
1449 const ctx = new CtxImpl(this.host, {
1450 signals: [controller.signal, this.callAbort.signal],
1451 rootId: `task:${this.address}:${key}`,
1452 codeVersion,
1453 principal: this.host.principal,
1454 holder: true,
1455 });
1456 const done = (async () => {
1457 try {
1458 await fn(ctx);
1459 } catch (error) {
1460 if (!ctx.signal.aborted) this.host.report(error);
1461 } finally {
1462 ctx.close();
1463 if (this.#tasks.get(key)?.controller === controller) this.#tasks.delete(key);
1464 }
1465 })();
1466 this.#tasks.set(key, { controller, done });
1467 }
1468
1469 /**
1470 * Aborts running tasks (and cancels a delayed start). Their completion is awaited by the next `startTasks` and at
1471 * disposal; each leaves `#stopped` when it finishes.
1472 */
1473 stopTasks(): void {
1474 this.#taskRuns++;
1475 for (const task of this.#tasks.values()) {
1476 task.controller.abort(new ChordError("aborted", "task stopped"));
1477 const done = task.done;
1478 this.#stopped.add(done);
1479 void done.finally(() => this.#stopped.delete(done));
1480 }
1481 this.#tasks.clear();
1482 }
1483
1484 /**
1485 * Delivers one listener event, in publication order. The invocation is a root that references a lease on this object
1486 * (a reload gate waits for it like for any other root that touched the object), counts as an invocation (disposal
1487 * waits for it) and is cancelled by forced disposal.
1488 */
1489 #deliver(key: string, event: unknown): void {
1490 enqueue(() => {
1491 if (this.gate !== undefined) {
1492 this.gate.queue.push({ key, event });
1493 return;
1494 }
1495 const decl = this.decls.listeners.get(key);
1496 if (decl === undefined || (this.status !== "live" && this.status !== "activating")) return;
1497 const invocation = this.host.root((root) => {
1498 this.lease(root);
1499 const child = (root as CtxImpl).child(this);
1500 return this.#invoke(async () => {
1501 try {
1502 await decl.fn(event, child);
1503 } finally {
1504 child.close();
1505 }
1506 });
1507 });
1508 invocation.catch((error: unknown) => this.host.report(error));
1509 });
1510 }
1511
1512 /** Opens the object's gate and replays queued listener events through the current listeners. */
1513 openGate(): void {
1514 const gate = this.gate;
1515 this.gate = undefined;
1516 for (const { key, event } of gate?.queue ?? []) this.#deliver(key, event);
1517 }
1518
1519 // ─── calls ───
1520
1521 /** Admission for a call or write carrying `ctx`. */
1522 admit(ctx: Ctx): void {
1523 if (this.host.failed !== undefined) {
1524 throw new ChordError("unavailable", `${this.host.name} failed and admits no work`, { reason: "host_failed" });
1525 }
1526 if (!this.host.hasCodeVersion(ctx.codeVersion))
1527 throw new ChordError("superseded", `code version ${ctx.codeVersion} is retired`);
1528 if (ctx.codeVersion < this.minCodeVersion) {
1529 throw new ChordError(
1530 "upgrade_conflict",
1531 `${this.address} was upgraded in code version ${this.minCodeVersion}`,
1532 );
1533 }
1534 if (this.gate !== undefined && !this.gate.grandfathered.has(ctx.rootId)) {
1535 throw new ChordError("upgrade_conflict", `${this.address} is being upgraded`);
1536 }
1537 }
1538
1539 /** Records that the root of `ctx` touched this object (a reload gate grandfathers it). */
1540 lease(ctx: Ctx): void {
1541 if (this.leases.has(ctx.rootId)) return;
1542 this.leases.set(ctx.rootId, ctx.codeVersion);
1543 this.host.touch(ctx.rootId, this);
1544 }
1545
1546 guard = (ctx: Ctx): void => {
1547 if (this.host.inFactory > 0) throw invalid("read_only", "cells cannot be written while a factory runs");
1548 if (ctx instanceof CtxImpl) ctx.check(this.host);
1549 if (ctx.signal.aborted) throw new ChordError("aborted", "write with an aborted ctx");
1550 if (this.status === "disposed") throw new ChordError("gone", `${this.address} is disposed`);
1551 if (ctx.rootId.startsWith("task:")) return;
1552 this.admit(ctx);
1553 };
1554
1555 async call(ref: RefImpl, name: string, args: unknown, ctx: CtxImpl): Promise<unknown> {
1556 ctx.check(this.host);
1557 if (ref.status === "released" || ref.status === "gone") throw ref.terminalError();
1558 if (ref.status === "loading") await raceSignal(ref.ready, ctx.signal);
1559 if (ref.status !== "live" || this.status !== "live") {
1560 throw ref.status === "live"
1561 ? new ChordError("gone", `${this.address} is ${this.status}`)
1562 : ref.terminalError();
1563 }
1564 this.admit(ctx);
1565 const installed = this.implementations.get(ctx.codeVersion);
1566 if (installed === undefined)
1567 throw new ChordError(
1568 "superseded",
1569 `${this.address} has no implementation for code version ${ctx.codeVersion}`,
1570 );
1571 const view = ref.viewOf(installed);
1572 const variant = variantOf(view);
1573 const wanted = ref.describe(ref.contract.scope === "remote" ? variant : LOCAL_VARIANT, name);
1574 const fn = view[name];
1575 if (typeof fn !== "function" || (ref.contract.scope === "remote" && wanted?.kind !== "method")) {
1576 throw new ChordError(
1577 "not_in_variant",
1578 `${this.address}: ${name} is not a method of variant ${variant ?? "(local)"}`,
1579 );
1580 }
1581 const direct = view === installed.implementation;
1582 const schema = direct
1583 ? installed.service.contract.description.variants[variant ?? LOCAL_VARIANT]?.[name]
1584 : wanted;
1585 const method = schema?.kind === "method" ? schema : undefined;
1586 const validated = ref.contract.scope === "remote" ? method : undefined;
1587 // No arguments: the handler takes only ctx. No result (void): the caller gets undefined, whatever it returned.
1588 const takesArgs = method === undefined || method.args !== undefined;
1589 const returns = method === undefined || method.result !== undefined;
1590 let input: unknown;
1591 if (takesArgs) {
1592 // The additive rule assumes a consumer sends only what its own schema knows, and a provider sees only what its
1593 // schema knows: strip with both before validating.
1594 const own = ref.contract.scope === "remote" && wanted?.kind === "method" ? wanted.args : undefined;
1595 const sent = own === undefined ? args : Value.Clean(own, Value.Clone(args));
1596 input = validated?.args ? Value.Clean(validated.args, Value.Clone(sent)) : sent;
1597 if (validated?.args) assertValid("args", `${this.address}.${name} args`, validated.args, input);
1598 }
1599 this.lease(ctx);
1600 const child = ctx.child(this);
1601 let result: unknown;
1602 try {
1603 result = await this.#invoke(() =>
1604 takesArgs
1605 ? (fn as (args: unknown, ctx: Ctx) => unknown)(input, child)
1606 : (fn as (ctx: Ctx) => unknown)(child),
1607 );
1608 } finally {
1609 child.close();
1610 }
1611 if (!returns) return undefined;
1612 if (validated?.result) assertValid("result", `${this.address}.${name} result`, validated.result, result);
1613 return result;
1614 }
1615
1616 /** Runs an invocation (method or listener) that keeps the object alive until it settles. */
1617 #invoke<T>(fn: () => T | Promise<T>): Promise<T> {
1618 const invocation = (async () => fn())();
1619 this.#invocations.add(invocation);
1620 const done = (): void => {
1621 this.#invocations.delete(invocation);
1622 if (this.#invocations.size === 0) this.#maybeIdle();
1623 };
1624 invocation.then(done, done);
1625 return invocation;
1626 }
1627
1628 rootEnded(rootId: string): void {
1629 this.leases.delete(rootId);
1630 const gate = this.gate;
1631 if (gate?.grandfathered.delete(rootId) && gate.grandfathered.size === 0) gate.drained();
1632 }
1633
1634 // ─── lifetime ───
1635
1636 addRef(ref: RefImpl): void {
1637 this.refs.add(ref);
1638 if (this.#linger !== undefined) clearTimeout(this.#linger);
1639 this.#linger = undefined;
1640 }
1641
1642 release(ref: RefImpl): void {
1643 if (this.refs.delete(ref)) this.#maybeIdle();
1644 }
1645
1646 /** No references and no invocations: dispose (after `linger` for a live object). */
1647 #maybeIdle(): void {
1648 if (this.refs.size > 0 || this.#invocations.size > 0 || this.#linger !== undefined) return;
1649 if (this.status === "activating") {
1650 this.#background(this.dispose(false));
1651 return;
1652 }
1653 if (this.status !== "live") return;
1654 const linger = this.service?.options.linger ?? 0;
1655 if (linger <= 0) {
1656 this.#background(this.dispose(false));
1657 return;
1658 }
1659 this.#linger = setTimeout(() => {
1660 this.#linger = undefined;
1661 if (this.refs.size === 0 && this.#invocations.size === 0 && this.status === "live") {
1662 this.#background(this.dispose(false));
1663 }
1664 }, linger);
1665 this.#linger.unref?.();
1666 }
1667
1668 #background(disposal: Promise<void>): void {
1669 disposal.catch((error: unknown) => this.host.report(error));
1670 }
1671
1672 /**
1673 * Disposes the object. Forced: references become gone at once (new calls are rejected) and running invocations are
1674 * cancelled. Either way, resources close only after every invocation settled.
1675 */
1676 dispose(forced: boolean, reason?: unknown): Promise<void> {
1677 this.#disposal ??= this.#dispose(forced, reason);
1678 return this.#disposal;
1679 }
1680
1681 async #dispose(forced: boolean, reason: unknown): Promise<void> {
1682 const wasActivating = this.status === "activating";
1683 this.status = "disposing";
1684 this.host.forget(this);
1685 if (this.#linger !== undefined) clearTimeout(this.#linger);
1686 this.#linger = undefined;
1687 const error = reason ?? new ChordError("gone", `${this.address} was disposed`);
1688 if (forced) {
1689 for (const ref of this.refs) ref.gone(error);
1690 this.callAbort.abort(error);
1691 }
1692 this.activationAbort.abort(error);
1693 if (wasActivating) await this.ready.catch(noop);
1694 for (const ref of this.refs) ref.gone(error);
1695 const decls = this.allDecls();
1696 this.stopTasks();
1697 this.stopListeners();
1698 await Promise.allSettled([...this.#invocations]);
1699 const registered = [...decls].some((set) => set.registrations.size > 0) && !this.deferredRuntime;
1700 this.implementations.clear();
1701 this.decls = new Decls();
1702 if (registered) this.host.registriesChanged();
1703 const refs = new Set<RefCore>();
1704 for (const set of decls) {
1705 for (const derived of set.derives.values()) derived.detach();
1706 for (const ref of set.refs.values()) refs.add(ref);
1707 }
1708 try {
1709 await runAll(
1710 [
1711 () => Promise.allSettled([...this.#stopped]),
1712 ...[...this.openOrder].reverse().map((resource) => () => resource.close(this.openOrder)),
1713 ...[...refs].map((ref) => () => ref.release()),
1714 ],
1715 `${this.address}: disposal failed`,
1716 );
1717 } finally {
1718 this.status = "disposed";
1719 this.host.disposed(this);
1720 }
1721 }
1722}
1723
1724const isReadableLike = (value: unknown): boolean =>
1725 value !== null &&
1726 typeof value === "object" &&
1727 typeof (value as Readable<unknown>).events === "function" &&
1728 typeof (value as Readable<unknown>).subscribe === "function";
1729
1730/** The remote state-member schemas an implementation exposes, by source. */
1731export function memberSchemas(
1732 service: Service,
1733 implementation: Record<string, unknown>,
1734): Map<Readable<unknown>, TSchema[]> {
1735 const schemas = new Map<Readable<unknown>, TSchema[]>();
1736 const contract = service.contract;
1737 if (contract.scope !== "remote") return schemas;
1738 const members = contract.description.variants[variantOf(implementation) ?? ""] ?? {};
1739 for (const [name, description] of Object.entries(members)) {
1740 const source = implementation[name];
1741 if (description.kind !== "state" || !isSource(source)) continue;
1742 schemas.set(source, [...(schemas.get(source) ?? []), description.schema]);
1743 }
1744 return schemas;
1745}
1746
1747function validateImplementation(service: Service, implementation: Record<string, unknown>): void {
1748 const contract = service.contract;
1749 const fail = (message: string): never => {
1750 throw invalid("implementation", `${contract.name}: ${message}`);
1751 };
1752 if (implementation === null || typeof implementation !== "object") fail("factory must return an object");
1753 let members: Readonly<Record<string, MemberDescription>>;
1754 if (contract.scope === "remote") {
1755 const variant = implementation.variant;
1756 if (typeof variant !== "string" || contract.description.variants[variant] === undefined)
1757 fail(`unknown variant ${String(variant)}`);
1758 members = contract.description.variants[variant as string]!;
1759 for (const key of Object.keys(implementation))
1760 if (key !== "variant" && members[key] === undefined) fail(`${key} is not in variant ${String(variant)}`);
1761 } else {
1762 members = contract.description.variants[LOCAL_VARIANT] ?? {};
1763 }
1764 for (const [name, description] of Object.entries(members)) {
1765 const value = implementation[name];
1766 if (description.kind === "method" && typeof value !== "function") fail(`${name} must be a method`);
1767 if (description.kind === "state" && !isSource(value) && !isReadableLike(value)) {
1768 fail(`${name} must be a cell, a derivation or a held object's state member`);
1769 }
1770 if (description.kind === "opaque" && value === undefined) fail(`${name} is missing`);
1771 }
1772}
1773
1774// ─── The factory's `self` ────────────────────────────────────────────────────
1775
1776class SelfImpl implements Self {
1777 readonly #object: ObjectImpl;
1778 readonly #previous: Decls | undefined;
1779 readonly #decls = new Decls();
1780 readonly #created: Run["created"] = { refs: [], resources: [], derives: [], inits: [] };
1781
1782 constructor(object: ObjectImpl, previous: Decls | undefined) {
1783 this.#object = object;
1784 this.#previous = previous;
1785 }
1786
1787 run(implementation: unknown): Run {
1788 return { implementation: implementation as Record<string, unknown>, decls: this.#decls, created: this.#created };
1789 }
1790
1791 /** Refuses a second declaration of `name` of one kind in this run (TypeScript cannot see string names). */
1792 #unique(map: ReadonlyMap<string, unknown>, kind: string, name: string): void {
1793 if (typeof name !== "string" || name === "") throw new TypeError(`${kind} needs a name`);
1794 if (map.has(name)) throw invalid("duplicate", `${this.#object.typeName}: duplicate ${kind} name ${name}`);
1795 }
1796
1797 state<S extends TSchema>(
1798 name: string,
1799 schema: S,
1800 initial: Static<S> | StateInit<Static<S>>,
1801 options: StateOptions<Static<S>> = {},
1802 ): Cell<Static<S>> {
1803 this.#unique(this.#decls.cells, "state", name);
1804 const version = options.version ?? 1;
1805 if (!Number.isInteger(version) || version < 1)
1806 throw new TypeError(`state ${name}: version must be a positive integer`);
1807 const host = this.#object.host;
1808 // A JSON value never holds a function: an object with a function `init` is the initializer, not a value.
1809 const init = isStateInit(initial) ? initial.init : undefined;
1810 let cell = this.#previous?.cells.get(name);
1811 if (cell === undefined) {
1812 cell = new Cell<unknown>(
1813 name,
1814 schema,
1815 init === undefined ? { value: initial } : undefined,
1816 this.#object.guard,
1817 {
1818 dev: host.dev,
1819 report: (error) => host.report(error),
1820 },
1821 );
1822 if (init !== undefined) this.#created.inits.push([cell, init]);
1823 }
1824 this.#decls.cells.set(name, cell);
1825 this.#decls.cellSchemas.set(name, schema);
1826 this.#decls.cellVersions.set(name, version);
1827 if (options.migrate !== undefined) this.#decls.cellMigrations.set(name, options.migrate);
1828 return cell as Cell<Static<S>>;
1829 }
1830
1831 get<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions): Ref<C> {
1832 const host = this.#object.host;
1833 // A prepare rerun (recording mode) binds new references against the reload's pending contracts: a breaking provider
1834 // change and its updated consumer reload together.
1835 const candidate = this.#previous !== undefined;
1836 const address = host.addressOf(type, input, options?.principal ?? host.principal, candidate);
1837 const declared = this.#decls.refs.get(address);
1838 if (declared !== undefined) {
1839 if (declared.contract.fingerprint !== type.fingerprint) {
1840 throw invalid("duplicate", `${this.#object.typeName}: ${type.name} held twice with different contracts`);
1841 }
1842 return declared.proxy as Ref<C>;
1843 }
1844 const existing = this.#previous?.refs.get(address);
1845 if (
1846 existing !== undefined &&
1847 existing.contract.fingerprint === type.fingerprint &&
1848 existing.status !== "gone" &&
1849 existing.status !== "released"
1850 ) {
1851 this.#decls.refs.set(address, existing);
1852 return existing.proxy as Ref<C>;
1853 }
1854 const ref = host.acquire(type, input, options, "object", this.#object, candidate);
1855 this.#decls.refs.set(address, ref);
1856 this.#created.refs.push(ref);
1857 return ref.proxy as Ref<C>;
1858 }
1859
1860 resource<T>(name: string, declaration: ResourceDeclaration<T>): Resource<T> {
1861 this.#unique(this.#decls.resources, "resource", name);
1862 if (!Number.isInteger(declaration.version)) throw new TypeError(`resource ${name}: version must be an integer`);
1863 const deps = (declaration.deps ?? []).map((dep) => {
1864 const resolved = refOf(dep) ?? resourceOf(dep);
1865 if (resolved === undefined) {
1866 throw new TypeError(`resource ${name}: deps must be references or resources of this object`);
1867 }
1868 return resolved;
1869 });
1870 const existing = this.#previous?.resources.get(name);
1871 const kept =
1872 existing !== undefined &&
1873 existing.spec.version === declaration.version &&
1874 existing.exclusive === (declaration.exclusive === true) &&
1875 existing.deps.length === deps.length &&
1876 existing.deps.every((dep, index) => dep === deps[index]);
1877 const resource = kept ? existing : new ResourceImpl(name, declaration as ResourceDeclaration<unknown>, deps);
1878 if (kept) this.#decls.adopted.set(existing, declaration as ResourceDeclaration<unknown>);
1879 else this.#created.resources.push(resource);
1880 this.#decls.resources.set(name, resource);
1881 return new ResourceFacade(resource, this.#object.host) as unknown as Resource<T>;
1882 }
1883
1884 on(name: string, source: unknown, ...rest: readonly unknown[]): void {
1885 this.#unique(this.#decls.listeners, "listener", name);
1886 const [select, fn] = rest.length === 1 ? [undefined, rest[0]] : [rest[0], rest[1]];
1887 if (typeof fn !== "function") throw new TypeError(`listener ${name}: the handler must be a function`);
1888 if (select !== undefined && typeof select !== "function")
1889 throw new TypeError(`listener ${name}: select must be a function`);
1890 this.#decls.listeners.set(name, {
1891 source,
1892 select: select as ListenerDecl["select"],
1893 fn: fn as ListenerDecl["fn"],
1894 });
1895 }
1896
1897 task(fn: (ctx: Ctx) => Promise<void>): void {
1898 if (typeof fn !== "function") throw new TypeError("a task must be a function");
1899 this.#decls.tasks.set(`#${this.#decls.tasks.size}`, fn);
1900 }
1901
1902 derive<const S extends Sources, T>(sources: S, fn: (...values: SourceValues<S>) => T): Readable<T> {
1903 if (typeof fn !== "function") throw new TypeError("a derivation needs a function");
1904 const host = this.#object.host;
1905 const key = `#${this.#decls.derives.size}`;
1906 const derived = new Derived(key, sources, fn as unknown as (...values: never[]) => unknown, {
1907 dev: host.dev,
1908 report: (error) => host.report(error),
1909 });
1910 this.#created.derives.push(derived);
1911 this.#decls.derives.set(key, derived);
1912 return derived as unknown as Readable<T>;
1913 }
1914
1915 expose<T>(resource: Resource<T>): Exposed<T> {
1916 const resolved = resourceOf(resource);
1917 if (resolved === undefined || ![...this.#decls.resources.values()].includes(resolved)) {
1918 throw new TypeError("expose takes a resource declared by this object");
1919 }
1920 return new ExposedImpl(resolved) as unknown as Exposed<T>;
1921 }
1922
1923 register<V>(registry: Registry<V>, entries: Readonly<Record<string, V>>): void {
1924 if (!this.#object.hostLifetime)
1925 throw invalid("not_host_lifetime", `${this.#object.typeName}: only objects of lifetime "host" may register`);
1926 for (const [key, value] of Object.entries(entries)) {
1927 const id = `${registry.name}\u0000${key}`;
1928 this.#unique(this.#decls.registrations, "register", id);
1929 this.#decls.registrations.set(id, { registry: registry as Registry<unknown>, key, value });
1930 }
1931 }
1932}