1
import type { TSchema } from "typebox";2
import { type Draft, diffRevisions, type JsonValue, type Op, type Tracker, track } from "./delta/index.ts";3
import { ChordError } from "./errors.ts";4
import { enqueue, holdPublications } from "./publish.ts";5
import { assertValid } from "./schema.ts";6
import type { Ctx, Readable, StateEvent } from "./types.ts";8
export interface SourceOptions {9
readonly dev: boolean;10
readonly report: (error: unknown) => void;11
}13
/** Checks that `ctx` may write an object's cells now; throws otherwise. */14
export type WriteGuard = (ctx: Ctx) => void;16
let sequence = 0;18
/** Fans out values and delta events; listener errors are reported, not thrown to the writer. */19
class Fanout<T> {20
readonly #values = new Set<(value: T) => void>();21
readonly #events = new Set<(event: StateEvent<T>) => void>();22
readonly #report: (error: unknown) => void;24
constructor(report: (error: unknown) => void) {25
this.#report = report;26
}28
subscribe(listener: (value: T) => void, current: T): () => void {29
this.#values.add(listener);30
this.#call(listener, current);31
return () => this.#values.delete(listener);32
}34
events(listener: (event: StateEvent<T>) => void, current: T): () => void {35
this.#events.add(listener);36
this.#call(listener, { type: "snap", value: current });37
return () => this.#events.delete(listener);38
}40
/**41
* Queues delivery to the listeners subscribed now. A listener that subscribes later already got this revision in42
* its snapshot; one that unsubscribes before delivery is skipped.43
*/44
emit(event: StateEvent<T>): void {45
const events = [...this.#events];46
const values = [...this.#values];47
enqueue(() => {48
for (const listener of events) if (this.#events.has(listener)) this.#call(listener, event);49
for (const listener of values) if (this.#values.has(listener)) this.#call(listener, event.value);50
});51
}53
#call<V>(listener: (value: V) => void, value: V): void {54
try {55
listener(value);56
} catch (error) {57
this.#report(error);58
}59
}60
}62
/**63
* Whether a state source has its value (entry 8): a remote reference's member before its first snapshot has none, and64
* neither has anything derived from or forwarding it. Sources without this symbol always have their value.65
*/66
export const HYDRATION: unique symbol = Symbol("chord.hydration");68
export interface Hydration {69
readonly hydrated: boolean;70
/** Resolves once hydrated; rejects if the source ends first. */71
whenHydrated(): Promise<void>;72
}74
/** The hydration of a readable, or undefined for a source that always has its value. */75
export function hydrationOf(value: unknown): Hydration | undefined {76
if (value === null || typeof value !== "object") return undefined;77
return (value as { readonly [HYDRATION]?: Hydration })[HYDRATION];78
}80
/** The hydrations of `sources` that are not hydrated yet. */81
export const unhydrated = (sources: Iterable<unknown>): Hydration[] =>82
[...sources].map(hydrationOf).filter((hydration): hydration is Hydration => hydration?.hydrated === false);84
/** An object-owned state source (cell or derivation). Writes recompute dependents atomically. */85
export abstract class Source<T> implements Readable<T> {86
readonly key: string;87
readonly seq = ++sequence;88
readonly dependents = new Set<Derived<unknown>>();89
/** Schemas of remote state members currently exposing this source (checked per write in dev mode). */90
schemas: readonly TSchema[] = [];91
protected readonly options: SourceOptions;92
protected readonly fanout: Fanout<T>;94
constructor(key: string, options: SourceOptions) {95
this.key = key;96
this.options = options;97
this.fanout = new Fanout(options.report);98
}100
abstract get value(): T;102
subscribe(listener: (value: T) => void): () => void {103
return this.fanout.subscribe(listener, this.value);104
}106
events(listener: (event: StateEvent<T>) => void): () => void {107
return this.fanout.events(listener, this.value);108
}110
/** Per-write validation, dev mode only. */111
validate(value: unknown): void {112
if (!this.options.dev) return;113
for (const schema of this.ownSchemas()) assertValid("state", `state ${this.key}`, schema, value);114
for (const schema of this.schemas) assertValid("state", `state ${this.key}`, schema, value);115
}117
protected ownSchemas(): readonly TSchema[] {118
return [];119
}120
}122
/** The tracker tracks containers, so a cell tracks `{ v: value }` and strips the box from published ops. */123
interface Box<T> {124
v: T;125
}127
function unbox(ops: readonly Op[], value: unknown): Op[] {128
const result: Op[] = [];129
for (const op of ops) {130
if (op[0] === "r" || op[1].length === 0) return [["r", value as JsonValue]];131
const path = op[1].slice(1);132
switch (op[0]) {133
case "p":134
result.push(["p", path, op[2], op[3], op[4]]);135
break;136
case "m":137
result.push(["m", path, op[2]]);138
break;139
default:140
// s/d/a/t on the value itself replace it.141
if (path.length === 0) return [["r", value as JsonValue]];142
if (op[0] === "d") result.push(["d", path as [string | number, ...(string | number)[]]]);143
else result.push([op[0], path as [string | number, ...(string | number)[]], op[2]] as Op);144
}145
}146
return result;147
}149
/** A state cell holding any JSON value, validated against its schema at creation and (dev mode) on writes. */150
export class Cell<T> extends Source<T> {151
/** Replaced at a reload commit that changes the schema (state-version bump). */152
schema: TSchema;153
#tracker: Tracker<Box<T>>;154
readonly #guard: WriteGuard;155
/** False until `initialize` for a cell declared with `init`: reads and writes throw `not_ready`. */156
#initialized: boolean;158
/**159
* `initial` is always validated against `schema`; ownership moves to the cell. Without `initial`, the cell has no160
* value until `initialize` (a cell declared with `init`, filled before its object goes live).161
*/162
constructor(163
key: string,164
schema: TSchema,165
initial: { readonly value: T } | undefined,166
guard: WriteGuard,167
options: SourceOptions,168
) {169
super(key, options);170
if (initial !== undefined) assertValid("state", `initial value of state ${key}`, schema, initial.value);171
this.schema = schema;172
this.#tracker = track<Box<T>>({ v: (initial?.value ?? null) as T });173
this.#guard = guard;174
this.#initialized = initial !== undefined;175
}177
/** Sets the first value of a cell declared with `init` (validated; ownership moves to the cell). Publishes nothing. */178
initialize(value: T): void {179
if (this.#initialized) throw new Error(`state ${this.key} is already initialized`);180
assertValid("state", `initial value of state ${this.key}`, this.schema, value);181
this.#tracker = track<Box<T>>({ v: value });182
this.#initialized = true;183
}185
protected override ownSchemas(): readonly TSchema[] {186
return [this.schema];187
}189
get value(): T {190
if (!this.#initialized) throw notReady(`state ${this.key} (its init has not run)`);191
return this.#tracker.value.v;192
}194
/**195
* Mutates a draft (only mutated paths are published), or returns a new value (`n => n + 1`). A returned value is196
* always validated against the schema. The draft is unusable after `fn` returns.197
*/198
change(ctx: Ctx, fn: (draft: Draft<T>) => T): void;199
change(ctx: Ctx, fn: (draft: Draft<T>) => void): void;200
change(ctx: Ctx, fn: (draft: Draft<T>) => unknown): void {201
this.#guard(ctx);202
if (!this.#initialized) throw notReady(`state ${this.key} (its init has not run)`);203
const change = this.#tracker.beginChange();204
let prepared: ReturnType<typeof change.prepare>;205
try {206
const draft = change.state as Draft<Box<T>>;207
const result: unknown = fn(draft.v as Draft<T>);208
if (result instanceof Promise) throw new TypeError("cell.change callbacks must be synchronous");209
if (result !== undefined) {210
if (result !== draft.v) assertValid("state", `state ${this.key}`, this.schema, result);211
draft.v = result as Draft<T>;212
}213
prepared = change.prepare();214
} catch (error) {215
change.abort();216
throw error;217
}218
this.#publish(prepared, "ops");219
}221
/**222
* Replaces the whole value. Ownership of `value` moves to the cell: never mutate it afterwards.223
*224
* Subscribers get a structural diff (`diffRevisions`) when `diff` is true, or by default when the new value shares225
* containers with the old one (a new immutable revision of the same state, e.g. mirrored from another store);226
* otherwise a single `r` op. The resulting value is the same either way; only the ops differ.227
*/228
replace(ctx: Ctx, value: T, options: { readonly diff?: boolean } = {}): void {229
this.#guard(ctx);230
if (!this.#initialized) throw notReady(`state ${this.key} (its init has not run)`);231
const before = this.value;232
const diff = options.diff ?? sharesStructure(before, value);233
const ops = diff ? diffRevisions(before as JsonValue, value as JsonValue) : undefined;234
this.#publish(this.#tracker.prepareReplace({ v: value }), "ops", true, ops);235
}237
/**238
* Installs a migrated value and its schema (reload commit). The caller validated the value and the derivations239
* over it against every schema that will apply, so nothing is checked here. Subscribers receive a reset.240
*/241
reset(value: T, schema: TSchema): void {242
this.schema = schema;243
this.#publish(this.#tracker.prepareReplace({ v: value }), "reset", false);244
}246
/** Adopts this revision and every derived one, then queues all notifications (cell first, then derivations). */247
#publish(248
prepared: ReturnType<Tracker<Box<T>>["prepareReplace"]>,249
type: "ops" | "reset",250
validate = true,251
ops?: readonly Op[],252
): void {253
if (prepared.ops.length === 0 && type === "ops") {254
this.#tracker.adopt(prepared);255
return;256
}257
const value = prepared.value.v;258
let candidates: Map<Derived<unknown>, unknown>;259
try {260
if (validate) this.validate(value);261
candidates = computeDependents(this as Source<unknown>, value, validate);262
} catch (error) {263
prepared.abort();264
throw error;265
}266
holdPublications(() => {267
this.#tracker.adopt(prepared);268
const published = ops !== undefined && ops.length > 0 ? ops : unbox(prepared.ops, value);269
this.fanout.emit(type === "reset" ? { type, value } : { type, ops: published, value });270
for (const [derived, next] of candidates) derived.install(next);271
});272
}273
}275
/** True if `b` reuses at least one container of `a` at the same key: a new revision of the same state. */276
function sharesStructure(a: unknown, b: unknown): boolean {277
if (a === null || b === null || typeof a !== "object" || typeof b !== "object" || a === b) return false;278
if (Array.isArray(a) !== Array.isArray(b)) return false;279
for (const [key, child] of Object.entries(b)) {280
if (child !== null && typeof child === "object" && (a as Record<string, unknown>)[key] === child) return true;281
}282
return false;283
}285
/** Recomputes every transitive dependent of `changed` against candidate values and validates them. */286
function computeDependents(changed: Source<unknown>, value: unknown, validate = true): Map<Derived<unknown>, unknown> {287
const pending = new Set<Derived<unknown>>();288
const visit = (source: Source<unknown>): void => {289
for (const derived of source.dependents) {290
if (pending.has(derived)) continue;291
pending.add(derived);292
visit(derived);293
}294
};295
visit(changed);296
const values = new Map<Readable<unknown>, unknown>([[changed, value]]);297
const result = new Map<Derived<unknown>, unknown>();298
for (const derived of [...pending].sort((a, b) => a.seq - b.seq)) {299
const next = derived.compute((source) => (values.has(source) ? values.get(source) : source.value));300
if (validate) derived.validate(next);301
values.set(derived, next);302
result.set(derived, next);303
}304
return result;305
}307
export type Sources = readonly Readable<unknown>[];308
export type SourceValues<S extends Sources> = { [K in keyof S]: S[K] extends Readable<infer T> ? T : never };310
const isReadable = (value: unknown): value is Readable<unknown> =>311
value !== null &&312
typeof value === "object" &&313
typeof (value as Readable<unknown>).subscribe === "function" &&314
"value" in value;316
/**317
* A synchronous derivation. Sources are object cells/derivations (recomputed atomically with the write) or other318
* readables such as reference state members (recomputed when they publish). Subscribers receive diffs.319
*/320
export class Derived<T> extends Source<T> {321
readonly sources: readonly Readable<unknown>[];322
readonly #fn: (...values: never[]) => unknown;323
#value: T;324
#external: (() => void)[] = [];326
constructor(key: string, sources: Sources, fn: (...values: never[]) => unknown, options: SourceOptions) {327
super(key, options);328
this.sources = sources.map((source) => {329
if (!isReadable(source)) throw new TypeError(`derive ${key}: sources must be readables`);330
return source;331
});332
this.#fn = fn;333
this.#value = undefined as T;334
}336
get value(): T {337
return this.#value;338
}340
/** Hydrated once every source is (a derivation over a remote member waits for its snapshot). */341
get [HYDRATION](): Hydration | undefined {342
const pending = unhydrated(this.sources);343
if (pending.length === 0) return undefined;344
return {345
hydrated: false,346
whenHydrated: () => Promise.all(pending.map((hydration) => hydration.whenHydrated())).then(() => {}),347
};348
}350
/**351
* Computes the first value (or takes it from `precomputed`, a reload's validated dry run) and starts following352
* the sources (at install, never inside a factory).353
*/354
attach(precomputed?: ReadonlyMap<unknown, unknown>): void {355
this.#value = precomputed?.has(this) ? (precomputed.get(this) as T) : this.compute((source) => source.value);356
for (const source of this.sources) {357
if (source instanceof Source) source.dependents.add(this as Derived<unknown>);358
else this.#external.push(source.subscribe(() => this.refresh()));359
}360
}362
detach(): void {363
for (const source of this.sources)364
if (source instanceof Source) source.dependents.delete(this as Derived<unknown>);365
for (const unsubscribe of this.#external.splice(0)) unsubscribe();366
}368
compute(read: (source: Readable<unknown>) => unknown): T {369
const result: unknown = this.#fn(...(this.sources.map(read) as never[]));370
if (result instanceof Promise) throw new TypeError(`derive ${this.key}: fn must be synchronous`);371
return result as T;372
}374
/** Recomputes and republishes, including dependents. Errors are reported (the source write already happened). */375
refresh(): void {376
try {377
const next = this.compute((source) => source.value);378
const dependents = computeDependents(this as Derived<unknown>, next);379
holdPublications(() => {380
this.install(next);381
for (const [derived, value] of dependents) derived.install(value);382
});383
} catch (error) {384
this.options.report(error);385
}386
}388
install(next: T): void {389
const before = this.#value;390
this.#value = next;391
const ops: Op[] =392
before === undefined || next === undefined393
? [["r", (next ?? null) as JsonValue]]394
: diffRevisions(before as JsonValue, next as JsonValue);395
if (ops.length > 0) this.fanout.emit({ type: "ops", ops, value: next });396
}397
}399
export const isSource = (value: unknown): value is Cell<unknown> | Derived<unknown> => value instanceof Source;401
/** Thrown by placeholders used before activation finished. */402
export const notReady = (what: string): ChordError => new ChordError("not_ready", `${what} is not ready`);