@mmstack/mesh 21.15.1 → 21.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/generation.ts","../../../../../packages/mesh/client/src/lib/session.ts","../../../../../packages/mesh/client/src/lib/agent-seat.ts","../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/peer-lifecycle.ts","../../../../../packages/mesh/client/src/lib/peer-links.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/lib/rtc-presence.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n admits,\n createRanges,\n recordAdmission,\n type CoverContext,\n type Dot,\n type GenerationReason,\n type Hlc,\n type Key,\n type OpEnvelope,\n type Ranges,\n type Receipts,\n type RegisterStore,\n type StoreOp,\n type TailPolicy,\n type VersionRange,\n} from '@mmstack/mesh-protocol';\n\n/**\n * The client half of a room generation: the record fields a snapshot welcome carries, the admission\n * evidence the client keeps for its pre-check, and the pure decisions the session takes on them\n * (which welcome to install, what a new generation does with the pending tail, whether a replayed\n * envelope may be sent, when a member is ready for a consensus cut). Nothing here touches a socket,\n * a store or a timer, so a harness can drive the same decisions the session does.\n */\n\n/** The immutable fields of the installed generation, as the client keeps them in its record. */\nexport type InstalledGeneration = {\n readonly instance: string;\n readonly index: number;\n readonly reason: GenerationReason;\n readonly policy: TailPolicy;\n readonly extent: Readonly<Record<string, Readonly<Record<string, Hlc>>>>;\n readonly preCutMax: Readonly<Record<string, Hlc>>;\n /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */\n readonly seq: number;\n};\n\n/**\n * The admission evidence of the installed generation as this client knows it: the welcome's ranges,\n * settled vector and first stamps, then every envelope the client ingests (its own included).\n * A lead or lag against the relay's view only ever yields a refusal the client lands as a conflict.\n */\nexport type ClientAdmission = {\n readonly ranges: Map<string, Ranges>;\n readonly settled: Map<string, Hlc>;\n readonly firstStamps: Map<string, Hlc>;\n};\n\n/** The serializable form of {@link ClientAdmission}. */\nexport type ClientAdmissionRecord = {\n readonly ranges: Readonly<Record<string, readonly VersionRange[]>>;\n readonly settled: Readonly<Record<string, Hlc>>;\n readonly firstStamps: Readonly<Record<string, Hlc>>;\n};\n\nexport const emptyAdmission = (): ClientAdmission => ({\n ranges: new Map(),\n settled: new Map(),\n firstStamps: new Map(),\n});\n\n/** The admission evidence a snapshot welcome carries, as of its seq. */\nexport const admissionOf = (src: ClientAdmissionRecord): ClientAdmission => ({\n ranges: new Map(Object.entries(src.ranges).map(([o, r]) => [o, createRanges(r)])),\n settled: new Map(Object.entries(src.settled)),\n firstStamps: new Map(Object.entries(src.firstStamps)),\n});\n\nexport const admissionRecord = (a: ClientAdmission): ClientAdmissionRecord => ({\n ranges: Object.fromEntries([...a.ranges].map(([o, r]) => [o, r.toJSON()])),\n settled: Object.fromEntries(a.settled),\n firstStamps: Object.fromEntries(a.firstStamps),\n});\n\n/**\n * One envelope reaches this client's view (its own emission, a relay delivery, a replayed or\n * re-applied own write). A version it already holds is a duplicate, and one below its origin's\n * maximum was skipped by the relay: both are refused (`false`), nothing is recorded. Otherwise the\n * version joins the evidence exactly as the relay records it.\n */\nexport function admitLocal(\n a: ClientAdmission,\n env: { readonly origin: string; readonly version: number; readonly hlc: Hlc },\n): boolean {\n const held = a.ranges.get(env.origin);\n if (held && (held.has(env.version) || env.version < held.max())) return false;\n recordAdmission(a, env);\n return true;\n}\n\n/** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */\nexport const coverContext = (\n gen: Pick<InstalledGeneration, 'extent' | 'preCutMax'>,\n a: ClientAdmission,\n): CoverContext => ({\n extent: gen.extent,\n preCutMax: gen.preCutMax,\n firstStamp: (origin) => a.firstStamps.get(origin),\n settled: (origin) => a.settled.get(origin),\n});\n\n/**\n * The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not\n * cover, by the same `admits` the relay runs, over the client's register store. An envelope with\n * an uncovered cite is never sent; it is a conflict.\n */\nexport function uncoveredCites(\n store: RegisterStore,\n ctx: CoverContext,\n env: OpEnvelope,\n): { readonly path: readonly Key[]; readonly dot: Dot }[] {\n const out: { path: readonly Key[]; dot: Dot }[] = [];\n for (const op of env.ops) {\n for (const dot of op.cites ?? []) {\n if (dot.origin === env.origin && dot.hlc.p === env.hlc.p && dot.hlc.l === env.hlc.l) continue;\n if (!admits(store, ctx, op.path, dot)) out.push({ path: op.path, dot });\n }\n }\n return out;\n}\n\n/** What the client knows of its installed generation when a snapshot welcome arrives. */\nexport type WelcomeFence = {\n readonly index: number;\n readonly instance: string | undefined;\n /** The seq of the installed snapshot. */\n readonly seq: number;\n /** The highest seq of a relay-delivered envelope of this generation, deduplicated or not. */\n readonly maxSeq: number;\n};\n\n/**\n * Which snapshot welcome installs. A newer generation (higher index) always does. One of the\n * installed generation does when it is not older than the installed snapshot (`stale` otherwise)\n * and not older than relay traffic already delivered (`older-than-traffic`): installing it would\n * replace that traffic with an earlier state. Anything else is stale.\n */\nexport function welcomeVerdict(\n installed: WelcomeFence,\n msg: { readonly index: number; readonly instance: string; readonly seq: number },\n): 'newer' | 'same' | 'stale' | 'older-than-traffic' {\n if (msg.index > installed.index) return 'newer';\n if (msg.instance !== installed.instance || msg.seq < installed.seq) return 'stale';\n if (msg.seq < installed.maxSeq) return 'older-than-traffic';\n return 'same';\n}\n\n/** A pending envelope of an earlier generation, as the tail policy reads it. */\ntype Pending = { readonly env: Pick<OpEnvelope, 'origin' | 'instance' | 'version'> };\n\n/**\n * A new generation's first step with the pending tail: in version order, an envelope whose version\n * the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest\n * is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the\n * current instance, so the relay receipts it there while the tail entry still names the generation\n * it was authored in, and a crash between the wire and the record would otherwise replay it again\n * after the next cut. An origin's versions never repeat (the counter runs through replay; a restart\n * that loses it mints a new origin), so the version alone identifies the write.\n */\nexport function trimByReceipts<T extends Pending>(\n pending: readonly T[],\n receipts: Receipts,\n): { readonly trimmed: T[]; readonly keep: T[] } {\n const sorted = [...pending].sort(\n (a, b) => a.env.version - b.env.version || (a.env.origin < b.env.origin ? -1 : 1),\n );\n // the union over every generation's ranges of the origin\n const held = (origin: string, version: number): boolean =>\n Object.values(receipts[origin] ?? {}).some((ranges) =>\n ranges.some(([from, to]) => from <= version && version <= to),\n );\n const trimmed: T[] = [];\n const keep: T[] = [];\n for (const t of sorted) {\n if (held(t.env.origin, t.env.version)) trimmed.push(t);\n else keep.push(t);\n }\n return { trimmed, keep };\n}\n\n/** A refusal was classified: a snapshot at or past its seq is owed. */\nexport const owedAfterRefusal = (owed: number | undefined, seq: number): number =>\n Math.max(owed ?? 0, seq);\n\n/** A snapshot installed at `seq`: the owed rehydration completes when it reaches the refusal. */\nexport const owedAfterInstall = (owed: number | undefined, seq: number): number | undefined =>\n owed !== undefined && seq >= owed ? undefined : owed;\n\n/**\n * A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it\n * wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it\n * is out of the outbox the moment it is classified.\n */\nexport const readyValue = (s: {\n readonly pressed: boolean;\n readonly connected: boolean;\n readonly replaying: boolean;\n readonly outstanding: number;\n}): boolean => s.pressed && s.connected && !s.replaying && s.outstanding === 0;\n\n/**\n * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds\n * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a\n * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when\n * an op's epoch rises above the register baseline at its path as the client held it before the\n * envelope (the relay's own test for a bump).\n */\nexport type Intent = { readonly raws: readonly StoreOp[]; readonly bump: boolean };\n\nexport function intentOf(env: OpEnvelope, baseline: (path: readonly Key[]) => number): Intent {\n const raws: StoreOp[] = [];\n let bump = false;\n for (const op of env.ops) {\n if ((op.epoch ?? 0) > baseline(op.path)) bump = true;\n if (op.kind === 'clear') continue;\n const raw: Record<string, unknown> = { ...op };\n delete raw['cites'];\n delete raw['epoch'];\n raws.push(raw as StoreOp);\n }\n return { raws, bump };\n}\n","import { isDevMode } from '@angular/core';\nimport {\n checkEnvelope,\n createRegisterStore,\n MESH_DIRECT_VERSION,\n MESH_PROTO_VERSION,\n type ClientSignalMsg,\n type OpPolicy,\n type PolicyViolation,\n type PresenceState,\n type PrincipalCtx,\n type RegisterCheckpoint,\n type RegisterStore,\n type SeqEnvelope,\n type ServerDirectMsg,\n type ServerMsg,\n type WelcomeMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n} from '@mmstack/primitives/core';\nimport {\n admissionOf,\n admissionRecord,\n admitLocal,\n coverContext,\n emptyAdmission,\n intentOf,\n owedAfterInstall,\n owedAfterRefusal,\n readyValue,\n trimByReceipts,\n uncoveredCites,\n welcomeVerdict,\n type ClientAdmission,\n type ClientAdmissionRecord,\n type InstalledGeneration,\n type Intent,\n} from './generation';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type { Intent } from './generation';\n\n/**\n * Why a write is a conflict: its replay into a new generation cites something the generation does\n * not hold (`'uncovered'`, never sent), or the relay refused it — a cite it does not cover\n * (`'citation'`) or an epoch raised without the authority to (`'epoch-bump'`).\n */\nexport type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';\n\n/**\n * A write that will never be admitted as it stands. Its local effect is retracted (a replay that\n * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).\n * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again\n * as a new write citing the current state. Neither can submit the original envelope.\n */\nexport type MeshConflict = {\n /** The envelope as it was authored (its values, cites and epoch). */\n readonly env: OpEnvelope;\n readonly intent: Intent;\n readonly cause: ConflictCause;\n discard(): void;\n /** Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`). */\n reauthor(): boolean;\n};\n\n/** The room's compaction state, as the relay last announced it. */\nexport type CompactionState = {\n /** Droppable tombstones counted against the budget. */\n readonly count: number;\n /** The hard budget, 0 when the room arms none. */\n readonly budget: number;\n /** Origins of the members currently declared ready for a consensus cut. */\n readonly ready: readonly string[];\n};\n\n/** The room generation the client installed, as its snapshot welcome named it. */\nexport type GenerationState = Pick<InstalledGeneration, 'instance' | 'index' | 'reason' | 'policy'>;\n\n/**\n * The session's durable half, persisted as one unit with the outbox: the fields of the generation\n * the tail was written in and its admission evidence, the intents of the pending writes, unresolved\n * conflicts and an owed snapshot. It holds NO registers and no sequence knowledge: a restart never\n * trusts stale registers — it installs nothing from disk, asks for a snapshot (hello without seq)\n * and resends its outbox first.\n */\nexport type SessionRecord = {\n readonly generation?: Omit<InstalledGeneration, 'seq'>;\n readonly admission?: ClientAdmissionRecord;\n readonly intents?: readonly {\n readonly origin: string;\n readonly version: number;\n readonly intent: Intent;\n }[];\n readonly conflicts?: readonly {\n readonly env: OpEnvelope;\n readonly intent: Intent;\n readonly cause: ConflictCause;\n }[];\n /** A refusal's seq: a snapshot at or past it must install before the client trusts its view. */\n readonly rehydrateOwed?: number;\n};\n\nexport type MeshStatus =\n | 'connecting'\n /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */\n | 'waiting'\n | 'live'\n | 'reconnecting'\n | 'ejected'\n | 'closed';\n\n/** A `direct` frame as a seat or a synced store hands it over: `from` is the sender's origin. */\nexport type MeshDirect = {\n readonly from: string;\n readonly v: number;\n readonly data: unknown;\n};\n\n/**\n * Hands `msg` to every listener; a throwing listener never interrupts the session or the others.\n * @internal\n */\nexport const deliverDirect = (\n listeners: ReadonlySet<(msg: MeshDirect) => void>,\n msg: ServerDirectMsg,\n): void => {\n const out: MeshDirect = { from: msg.from, v: msg.v, data: msg.data };\n for (const cb of [...listeners]) {\n try {\n cb(out);\n } catch {\n // a consumer's failure stays its own\n }\n }\n};\n\n/** One sequenced remote envelope's ops, attributed to the writer that made them. */\nexport type RemoteBatch = {\n /** The relay's total-order stamp for this batch. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Environment callbacks a session shell provides. All are optional except `onStatus`; the\n * session never touches signals, timers beyond `schedule`, storage, or the DOM itself.\n */\nexport type MeshSessionHooks = {\n onStatus(status: MeshStatus, reason?: string): void;\n /** The current op engine's origin, published immediately before each hello. */\n onOrigin?(origin: string): void;\n /** Relay membership, independent of presence; undefined while disconnected or before welcome. */\n onMembers?(members: readonly string[] | undefined): void;\n /**\n * A room message after the session has processed it, for consumers sharing its connection.\n * `direct` frames never pass here; they go to {@link MeshSessionHooks.onDirect} only.\n */\n onMessage?(msg: ServerMsg): void;\n /**\n * A `direct` frame addressed to this session, in the frame version this side speaks; any other\n * version is refused unread. One that arrives before the current connection's welcome is held\n * (up to 256) and handed over right after it, unless its sender leaves first.\n */\n onDirect?(msg: ServerDirectMsg): void;\n /** A welcome or envelope arrived — the shell's \"last synced\" moment. */\n onSynced?(): void;\n /** The presence roster changed (welcome replace, join/leave, teardown clear). */\n onPeers?(peers: ReadonlyMap<string, PresenceState>): void;\n /** A remote (non-own) envelope was ingested, in seq order. */\n onRemote?(batch: RemoteBatch): void;\n /**\n * Seq continuity broke: a snapshot welcome (or a relay instance change) established state\n * without delivering the individual envelopes in between. Any consumer deriving from the\n * `onRemote` stream must rebuild from current state at this seq; appending across a resync\n * would silently skip history.\n */\n onResync?(seq: number): void;\n /** The unacknowledged local tail changed (emit or ack) — the durable-outbox trigger. */\n onOutboxChange?(): void;\n /**\n * A local write violated the room policy. The session ejects itself immediately after —\n * the outcome the relay's own independent check would have produced one hop later. The\n * emit-side check spares the room the round trip; it is never the enforcement.\n */\n onLocalReject?(violation: PolicyViolation): void;\n /** The transport closed and a reconnect is scheduled; `code` is the close code (1009 = message too big). */\n onDisconnect?(code: number, reason: string): void;\n /**\n * Teardown is starting; fired before the unacked tail is dropped, so a shell can persist\n * it (and release any single-writer locks) while it is still intact.\n */\n onTerminal?(state: 'ejected' | 'closed', reason?: string): void;\n /**\n * The relay refused one of this session's writes: it is not in the room and never will be.\n * `'generation'` — written in a room generation that a cut with the `discard` policy closed (a\n * migration or a rollback: the reset is the intent), or in a room recreated without its\n * generation record; `'schema'` — a data shape older than the room's; `'order'` — a version\n * below this origin's admitted maximum that was never admitted (a second tab on one origin);\n * `'compacting'` — a host refused a write from a connection declared ready for the current\n * generation (the relay itself never sends it). The session drops the write locally and hydrates from a fresh snapshot; the envelope carries the\n * values, so the application can offer to write them again. Any `whenAcked` waiter rejects.\n * A write a compaction cut replays is never refused here: it is resent, or it is a conflict.\n */\n onRefused?(env: OpEnvelope, reason: 'generation' | 'schema' | 'order' | 'compacting'): void;\n /** The unresolved conflicts changed (a write classified, discarded or re-authored). */\n onConflicts?(conflicts: readonly MeshConflict[]): void;\n /** The relay announced the room's compaction state (count, budget, ready members). */\n onCompaction?(state: CompactionState): void;\n /**\n * A snapshot welcome of a NEW generation installed (a cut's welcome, or the first snapshot of\n * the session); `undefined` when the room was recreated without its record. A welcome of the\n * installed generation never fires it.\n */\n onGeneration?(generation: GenerationState | undefined): void;\n};\n\nexport type MeshSessionOptions<T extends object> = {\n readonly room: string;\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** The op engine this session feeds. The shell creates (and destroys) it. */\n readonly sync: OpSync<T>;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policy?: OpPolicy;\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion: number;\n readonly schemaVersion?: number;\n /** The room generation a restored outbox was written in; the first welcome decides whether it still holds. */\n readonly instance?: string;\n /**\n * The restored durable record (see {@link SessionRecord}), applied at `connect()` on top of the\n * restored outbox: the registers are hydrated with the pending writes re-applied over them.\n */\n readonly record?: SessionRecord;\n /**\n * Write a conflict's raw ops again (a new write citing the current state), on the shell's store;\n * with `bump`, as an authority override. Without it a conflict can only be discarded.\n */\n readonly reauthor?: (intent: Intent) => void;\n readonly reconnect?: { readonly maxDelayMs?: number };\n /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */\n readonly schedule?: {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n };\n readonly hooks: MeshSessionHooks;\n};\n\n/**\n * The relay-room session protocol, shell-agnostic: hello/welcome handshakes (snapshot\n * hydrate, delta replay, fresh-room seed), own-echo acknowledgement, unacked resend,\n * the relay's per-envelope answers (`drop`), reconnect backoff, presence, eject/reject, the\n * generation fence and settled-vector garbage collection. `meshSync` wraps it for\n * Angular; `agentSeat` wraps it for injector-free environments. One implementation of the\n * wire contract — shells differ only in environment concerns.\n */\nexport type MeshSession = {\n /** Open the first connection. Call once, after any outbox restore has replayed. */\n connect(): void;\n status(): MeshStatus;\n /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */\n lastSeq(): number;\n hasUnacked(): boolean;\n /**\n * Resolves once the unacknowledged local tail is empty — the acknowledgement barrier a\n * caller awaits before treating its writes as the room's. Resolves immediately when\n * nothing is outstanding. Rejects with the terminal reason if the session ends (eject or\n * close) while entries remain: those writes never reached the room, and every later call\n * rejects the same way.\n *\n * With a relay whose adapter confirms durability before echoing, acknowledged means\n * stored; against a relay that echoes eagerly it means only \"the relay has it\".\n */\n whenAcked(): Promise<void>;\n /** The unacknowledged local tail (the durable-outbox payload). */\n unackedEnvs(): readonly OpEnvelope[];\n /** The room generation this session is in, once a welcome (or a restored outbox) named one. */\n instance(): string | undefined;\n peers(): ReadonlyMap<string, PresenceState>;\n setPresence(data: unknown): void;\n /** Send peer signaling over the current connection without a second hello. */\n sendSignal(msg: ClientSignalMsg): void;\n /** Send a `direct` frame to one member over the current connection; lost when there is none. */\n sendDirect(to: string, data: unknown): void;\n /** Writes that will never be admitted as they stand, each with its two verbs. */\n conflicts(): readonly MeshConflict[];\n /**\n * The member pressed (or released) Compact. While pressed, the session declares itself ready for\n * a consensus cut whenever nothing it wrote is outstanding, and re-declares on every change; a\n * reconnect and a new generation release the press. Safety never depends on it.\n */\n declareReady(pressed: boolean): void;\n /** The durable record to persist with the outbox (see {@link SessionRecord}). */\n record(): SessionRecord;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\n/** `direct` frames held before a welcome, per connection: the bound peer links keep for signals. */\nconst HELD_DIRECTS = 256;\n\nexport function meshSession<T extends object>(\n opt: MeshSessionOptions<T>,\n): MeshSession {\n const { sync, hooks } = opt;\n const schedule = opt.schedule ?? {\n set: (fn: () => void, ms: number) => setTimeout(fn, ms),\n clear: (handle: unknown) =>\n clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n\n let status: MeshStatus = 'connecting';\n const ownOrigins = new Set<string>([sync.origin]);\n const unacked = new Map<string, OpEnvelope>();\n const unackedKey = (env: { origin: string; version: number }): string =>\n `${env.origin} ${env.version}`;\n let lastSeq = 0;\n let instance: string | undefined = opt.instance;\n if (instance) sync.adopt(instance);\n // a snapshot was asked for (hello without seq); one hello per burst, cleared by the welcome it earns\n let rehydrating = false;\n\n // ─── the durable record: installed generation, its registers and evidence, intents, conflicts ───\n let gen: InstalledGeneration | undefined;\n let admission: ClientAdmission = emptyAdmission();\n // the client's register store: what `admits` reads for a replay's pre-check, fed every envelope\n // the session ingests (welcome, relay delta, own write) and collected with the relay's vector\n let cover: RegisterStore = createRegisterStore();\n // relay-sequenced ingress of the installed generation, deduplicated or not: the welcome fence\n let maxSeq = 0;\n let owed: number | undefined;\n const intents = new Map<string, Intent>();\n type Held = { env: OpEnvelope; intent: Intent; cause: ConflictCause };\n let held: Held[] = [];\n // census: the press is per connection, never persisted; `declared` mirrors what the relay holds\n let pressed = false;\n let declared: { ready: boolean; instance: string } | undefined;\n\n let peers: ReadonlyMap<string, PresenceState> = new Map();\n let members: readonly string[] | undefined;\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: unknown;\n let unsubs: (() => void)[] = [];\n let closed = false;\n let connected = false;\n // a `direct` frame waits for the welcome of its connection, as peer links hold signals\n let welcomedHere = false;\n let heldDirects: ServerDirectMsg[] = [];\n let versionWarned = false;\n let heldWarned = false;\n let ackFailure: Error | undefined;\n const ackWaiters: {\n resolve: () => void;\n reject: (cause: Error) => void;\n }[] = [];\n\n const releaseAckWaiters = (failure?: Error): void => {\n for (const waiter of ackWaiters.splice(0)) {\n if (failure) waiter.reject(failure);\n else waiter.resolve();\n }\n };\n\n const setStatus = (next: MeshStatus, reason?: string): void => {\n status = next;\n hooks.onStatus(next, reason);\n };\n\n const terminal = (state: 'ejected' | 'closed', reason?: string): void => {\n if (closed) return;\n closed = true;\n if (reconnectTimer !== undefined) {\n schedule.clear(reconnectTimer);\n reconnectTimer = undefined;\n }\n for (const unsub of unsubs.splice(0)) unsub();\n unsubLocal();\n hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window\n if (unacked.size > 0) {\n // these writes are not in the room and never will be on this session\n ackFailure = new Error(reason ?? state);\n releaseAckWaiters(ackFailure);\n } else {\n releaseAckWaiters();\n }\n unacked.clear();\n heldDirects = [];\n transport?.close();\n transport = null;\n peers = new Map();\n hooks.onPeers?.(peers);\n members = undefined;\n hooks.onMembers?.(members);\n setStatus(state, reason);\n };\n\n /** An envelope of the installed generation (or minted before any generation was known). */\n const current = (env: OpEnvelope): boolean =>\n env.instance === '' || env.instance === instance;\n\n const sendEnv = (env: OpEnvelope): void => {\n // an envelope minted before any generation was known adopts the one this session is in\n let out = env;\n if (env.instance === '' && instance) {\n out = { ...env, instance };\n unacked.set(unackedKey(env), out);\n }\n transport?.send({ t: 'env', room: opt.room, env: out });\n };\n const sendHello = (): void => {\n if (!transport) return;\n hooks.onOrigin?.(sync.origin);\n // an owed or requested snapshot is asked for by a hello without seq\n const want = rehydrating || owed !== undefined;\n transport?.send({\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion,\n seq: !want && lastSeq > 0 ? lastSeq : undefined,\n schemaVersion: opt.schemaVersion,\n });\n };\n const requestSnapshot = (): void => {\n if (rehydrating || closed) return;\n rehydrating = true;\n sendHello();\n };\n\n /** Send the census flag when the member's readiness (or its generation) changed. */\n const declare = (): void => {\n if (!instance || !transport || !welcomedHere || closed) return;\n const ready = readyValue({\n pressed,\n connected,\n replaying: false, // a replay runs whole inside one welcome\n outstanding: unacked.size,\n });\n if (declared && declared.ready === ready && declared.instance === instance) return;\n declared = { ready, instance };\n transport.send({ t: 'compact', room: opt.room, instance, ready });\n };\n\n const conflicts = (): readonly MeshConflict[] =>\n held.map((h) => ({\n env: h.env,\n intent: h.intent,\n cause: h.cause,\n discard: () => settleConflict(h),\n reauthor: () => {\n if (!opt.reauthor || !held.includes(h)) return false;\n settleConflict(h);\n opt.reauthor(h.intent);\n return true;\n },\n }));\n const conflictsChanged = (): void => {\n hooks.onConflicts?.(conflicts());\n hooks.onOutboxChange?.();\n };\n const settleConflict = (h: Held): void => {\n if (!held.includes(h)) return;\n held = held.filter((x) => x !== h);\n conflictsChanged();\n };\n /** A pending write will never be admitted as it stands: out of the outbox, into the conflicts. */\n const classify = (env: OpEnvelope, cause: ConflictCause): void => {\n const key = unackedKey(env);\n const intent = intents.get(key) ?? intentOf(env, () => Number.POSITIVE_INFINITY);\n unacked.delete(key);\n intents.delete(key);\n held = [...held, { env, intent, cause }];\n releaseAckWaiters(new Error(`conflict: ${cause}`));\n };\n\n const ackOwn = (origin: string, version: number): void => {\n const key = unackedKey({ origin, version });\n if (!unacked.delete(key)) return;\n intents.delete(key);\n hooks.onOutboxChange?.();\n if (unacked.size === 0) releaseAckWaiters();\n declare();\n };\n const refuse = (\n env: OpEnvelope,\n reason: 'generation' | 'schema' | 'order' | 'compacting',\n ): void => {\n unacked.delete(unackedKey(env));\n intents.delete(unackedKey(env));\n hooks.onRefused?.(env, reason);\n hooks.onOutboxChange?.();\n // \"every write was classified\" is not \"every write was stored\": a waiter rejects\n releaseAckWaiters(new Error(`refused: ${reason}`));\n };\n\n const flushUnacked = (): void => {\n // a write of an earlier generation waits for the welcome that names the new one\n for (const env of unacked.values()) if (current(env)) sendEnv(env);\n };\n\n const applyRemote = (env: SeqEnvelope): void => {\n if (closed) return; // a delta welcome keeps iterating after an eject — nothing lands past it\n // a newer data shape is the room's, whatever generation carried it (a migration row belongs to\n // the generation it closes)\n if (\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion\n ) {\n terminal('ejected', 'schema');\n return;\n }\n // the generation fence: an envelope of another generation is never ingested, and teaches nothing\n if (instance !== undefined && env.instance !== instance) return;\n // sequence knowledge advances on every relay-delivered envelope, before any deduplication\n lastSeq = Math.max(lastSeq, env.seq);\n maxSeq = Math.max(maxSeq, env.seq);\n hooks.onSynced?.();\n if (ownOrigins.has(env.origin)) {\n ackOwn(env.origin, env.version);\n return;\n }\n if (!admitLocal(admission, env)) return; // a duplicate delivery applies nothing\n cover.ingest(env);\n sync.receive(env);\n hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });\n };\n\n /** Hydrate the op engine from `registers` with `pending` own writes re-applied over them. */\n const hydrateWith = (\n registers: readonly RegisterCheckpoint[],\n wm: Readonly<Record<string, number>>,\n pending: readonly OpEnvelope[],\n ): void => {\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(registers);\n // own origins are left out of the watermark: exactly `pending` is re-applied, nothing else\n const theirs: Record<string, number> = {};\n for (const [o, v] of Object.entries(wm)) if (!ownOrigins.has(o)) theirs[o] = v;\n sync.hydrate(\n { root: conv.materialize() as T, registers: [...registers], wm: theirs },\n pending,\n );\n };\n\n /** A room recreated without its generation record (a relay restart): today's discard. */\n const forgetGeneration = (): void => {\n lastSeq = 0;\n for (const env of [...unacked.values()]) refuse(env, 'generation');\n gen = undefined;\n admission = emptyAdmission();\n cover = createRegisterStore();\n maxSeq = 0;\n owed = undefined; // its threshold belongs to the dead room's sequence\n hooks.onGeneration?.(undefined);\n };\n\n /**\n * Install a snapshot welcome ATOMICALLY: the registers (a cut's seed or the current registers),\n * the generation record, its admission evidence and sequence knowledge, and the pending tail.\n * A newer generation trims the tail by its receipts, then applies its policy: `discard` drops the\n * rest, `replay` resends each envelope verbatim (same dots, stamps, versions; instance swapped) in\n * version order when every cite passes the pre-check, and classifies it a conflict otherwise. Own\n * writes of the installed generation the welcome has not admitted stay applied over it.\n */\n const install = (\n msg: Extract<WelcomeMsg, { mode: 'snapshot' }>,\n newer: boolean,\n ): void => {\n const registers = msg.seed ?? msg.registers;\n const admitted = admissionOf(msg);\n const notAdmitted = (env: OpEnvelope): boolean =>\n !admitted.ranges.get(env.origin)?.has(env.version);\n const own = [...unacked.values()]\n .filter((env) => (env.instance === '' || env.instance === msg.instance) && notAdmitted(env))\n .map((env) => (env.instance === msg.instance ? env : { ...env, instance: msg.instance }));\n let keep: OpEnvelope[] = [];\n if (newer) {\n const pending = [...unacked.values()]\n .filter((env) => env.instance !== '' && env.instance !== msg.instance)\n .map((env) => ({ env }));\n const tail = trimByReceipts(pending, msg.receipts);\n for (const { env } of tail.trimmed) {\n // the receipts say it was admitted: acknowledged, never resent\n unacked.delete(unackedKey(env));\n intents.delete(unackedKey(env));\n }\n if (unacked.size === 0) releaseAckWaiters();\n if (msg.policy === 'discard') for (const { env } of tail.keep) refuse(env, 'generation');\n else keep = tail.keep.map((t) => t.env);\n pressed = false; // a new generation starts with nobody pressed\n }\n instance = msg.instance;\n sync.adopt(msg.instance); // a new generation drops the emission floors before the load\n gen = {\n instance: msg.instance,\n index: msg.index,\n reason: msg.reason,\n policy: msg.policy,\n extent: msg.extent,\n preCutMax: msg.preCutMax,\n seq: msg.seq,\n };\n admission = admitted;\n cover = createRegisterStore();\n cover.load(registers);\n for (const env of own) {\n admitLocal(admission, env);\n cover.ingest(env);\n if (env !== unacked.get(unackedKey(env))) unacked.set(unackedKey(env), env);\n }\n const replayed: OpEnvelope[] = [];\n const ctx = coverContext(gen, admission);\n for (const old of keep) {\n const env: OpEnvelope = { ...old, instance: msg.instance };\n if (uncoveredCites(cover, ctx, env).length) {\n classify(old, 'uncovered'); // never sent, never applied\n continue;\n }\n unacked.set(unackedKey(env), env);\n admitLocal(admission, env);\n cover.ingest(env);\n replayed.push(env);\n }\n hydrateWith(registers, msg.wm, [...own, ...replayed]);\n if (newer) maxSeq = 0;\n lastSeq = Math.max(msg.seq, maxSeq);\n owed = owedAfterInstall(owed, msg.seq);\n if (keep.length > replayed.length) hooks.onConflicts?.(conflicts());\n hooks.onOutboxChange?.();\n if (newer)\n hooks.onGeneration?.({\n instance: gen.instance,\n index: gen.index,\n reason: gen.reason,\n policy: gen.policy,\n });\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n switch (msg.t) {\n case 'welcome': {\n const prevSeq = lastSeq;\n rehydrating = false;\n let resync = false;\n peers = new Map(msg.peers.map((p) => [p.origin, p]));\n hooks.onPeers?.(peers);\n members = [\n ...new Set(msg.members.filter((origin) => origin !== sync.origin)),\n ];\n hooks.onMembers?.(members);\n if (msg.mode === 'snapshot') {\n const fence = {\n index: gen?.index ?? -1,\n instance,\n seq: gen?.seq ?? 0,\n maxSeq,\n };\n let verdict = welcomeVerdict(fence, msg);\n // the answer to this connection's hello is the relay's current state: another instance at\n // an index not above the installed one is a room recreated without its record\n if (verdict === 'stale' && !welcomedHere && msg.instance !== instance) {\n forgetGeneration();\n verdict = 'newer';\n }\n if (verdict === 'newer' || verdict === 'same') {\n install(msg, verdict === 'newer');\n resync = true;\n } else if (owed !== undefined) {\n // a rejected snapshot while one is owed is asked for again\n requestSnapshot();\n }\n } else {\n if (instance !== undefined && msg.instance !== instance) {\n // a room recreated without its generation record: the tail written in the old one is\n // refused loudly and the new room's state replaces it\n forgetGeneration();\n resync = true;\n }\n instance = msg.instance;\n sync.adopt(msg.instance);\n if (msg.mode === 'delta') {\n for (const env of msg.envs) applyRemote(env);\n } else if (msg.seq === 0 && lastSeq === 0) {\n sync.seed();\n }\n }\n // every branch can end terminal (schema eject in a delta env, a seed or rebase\n // emission tripping the emit-side policy) — never revive to live\n if (closed) {\n if (resync && lastSeq === 0) lastSeq = prevSeq;\n return;\n }\n if (msg.mode !== 'snapshot') lastSeq = Math.max(lastSeq, msg.seq);\n attempts = 0;\n hooks.onSynced?.();\n if (resync) hooks.onResync?.(lastSeq);\n setStatus('live');\n flushUnacked();\n if (hasPresence)\n transport?.send({\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n welcomedHere = true;\n // the relay resets every declaration at a join and at a cut\n declared = instance ? { ready: false, instance } : undefined;\n declare();\n if (owed !== undefined) requestSnapshot(); // keep asking until one at or past it installs\n const replay = heldDirects;\n heldDirects = [];\n for (const held of replay) {\n if (closed) return;\n hooks.onDirect?.(held);\n }\n return;\n }\n case 'env':\n applyRemote(msg.env);\n return;\n case 'presence': {\n const next = new Map(peers);\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peers = next;\n hooks.onPeers?.(peers);\n return;\n }\n case 'member': {\n // a leave discards what that origin sent before the welcome\n if (msg.gone)\n heldDirects = heldDirects.filter((h) => h.from !== msg.origin);\n if (members === undefined || msg.origin === sync.origin) return;\n members = msg.gone\n ? members.filter((origin) => origin !== msg.origin)\n : members.includes(msg.origin)\n ? members\n : [...members, msg.origin];\n hooks.onMembers?.(members);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n terminal('ejected', msg.reason);\n return;\n case 'settled':\n sync.settle(msg.settled);\n cover.settle(msg.settled);\n return;\n case 'compaction':\n hooks.onCompaction?.({ count: msg.count, budget: msg.budget, ready: msg.ready });\n return;\n case 'drop': {\n const env = unacked.get(unackedKey(msg));\n if (!env) return; // already classified (a duplicate reply after the echo, or an old generation's)\n if (msg.reason === 'duplicate') {\n ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement\n return;\n }\n if (msg.reason === 'generation') {\n // the room moved to a newer generation: the write waits for its welcome and its policy\n requestSnapshot();\n return;\n }\n if (msg.reason === 'citation' || msg.reason === 'epoch-bump') {\n // a refusal is a conflict; the snapshot that drops its local effect is owed until one\n // at or past the refusal's seq installs (repeated replies find nothing left to classify)\n classify(env, msg.reason);\n owed = owedAfterRefusal(owed, msg.seq);\n conflictsChanged();\n declare();\n requestSnapshot();\n return;\n }\n refuse(env, msg.reason);\n // the refused write is still applied locally: drop and rehydrate from a fresh snapshot\n requestSnapshot();\n return;\n }\n }\n };\n\n const receiveDirect = (msg: ServerDirectMsg): void => {\n // a frame version this side does not speak is refused whole: nothing else of it is read\n if (msg.v !== MESH_DIRECT_VERSION) {\n if (isDevMode() && !versionWarned) {\n versionWarned = true;\n console.warn(\n `[@mmstack/mesh] dropped a direct frame of version ${String(msg.v)}; this side speaks ${MESH_DIRECT_VERSION}`,\n );\n }\n return;\n }\n if (welcomedHere) hooks.onDirect?.(msg);\n else if (heldDirects.length < HELD_DIRECTS) heldDirects.push(msg);\n else if (isDevMode() && !heldWarned) {\n heldWarned = true;\n console.warn(\n `[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`,\n );\n }\n };\n\n /** The restored record, applied once on top of the restored outbox: nothing of it is installed. */\n let restoreRecord = (): void => {\n restoreRecord = () => undefined;\n const rec = opt.record;\n if (!rec) return;\n owed = rec.rehydrateOwed;\n held = (rec.conflicts ?? []).map((c) => ({ ...c }));\n for (const x of rec.intents ?? []) {\n const key = unackedKey(x);\n if (unacked.has(key)) intents.set(key, x.intent);\n }\n if (held.length) hooks.onConflicts?.(conflicts());\n // the generation the tail was written in classifies it at the next welcome; no seq is known, so\n // any snapshot of that generation (or a newer one) installs\n if (!rec.generation || rec.generation.instance !== instance) return;\n gen = { ...rec.generation, seq: 0 };\n admission = admissionOf(rec.admission ?? { ranges: {}, settled: {}, firstStamps: {} });\n };\n\n const connect = (): void => {\n if (closed) return;\n restoreRecord();\n for (const unsub of unsubs.splice(0)) unsub();\n const t = opt.transport();\n transport = t;\n connected = true;\n welcomedHere = false;\n heldDirects = [];\n unsubs = [\n t.onMessage((msg) => {\n if (closed || transport !== t || msg.room !== opt.room) return;\n if (msg.t === 'direct') {\n receiveDirect(msg);\n return;\n }\n handle(msg);\n if (!closed || msg.t === 'reject' || msg.t === 'eject')\n hooks.onMessage?.(msg);\n }),\n t.onClose((code, reason) => {\n if (closed || transport !== t) return;\n transport = null;\n connected = false;\n welcomedHere = false;\n pressed = false; // a reconnect is a leave and a join: the press does not carry over\n declared = undefined;\n rehydrating = false; // the next hello asks again\n heldDirects = [];\n members = undefined;\n hooks.onMembers?.(members);\n setStatus('reconnecting');\n hooks.onDisconnect?.(code, reason);\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = schedule.set(\n () => {\n reconnectTimer = undefined;\n connect();\n },\n delay + Math.random() * 100,\n );\n }),\n ];\n sendHello();\n // a restart resends its outbox before relying on any installed state: a refusal whose conflict\n // did not persist before a crash is answered again at once\n if (instance) flushUnacked();\n };\n\n const unsubLocal = sync.subscribe((env, ctx) => {\n const violation = checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n // the last sequence this client observed; it can only lag the relay's, so a rule that\n // keys off an empty room is at worst more permissive here than it is at the relay\n { seq: lastSeq },\n );\n if (violation) {\n // same outcome the relay's own check would produce one hop later — the emit-side\n // check is an optimization, never the enforcement\n hooks.onLocalReject?.(violation);\n terminal('ejected', violation.reason);\n return;\n }\n ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim\n const key = unackedKey(env);\n // the intent the engine stamped this envelope from (a restored envelope carries none: its\n // record supplies it, or it is read back from the envelope against the registers held now)\n if (!intents.has(key))\n intents.set(\n key,\n ctx?.raws\n ? { raws: ctx.raws, bump: !!ctx.bump }\n : intentOf(env, (path) => cover.maxEpoch(path)),\n );\n admitLocal(admission, env);\n cover.ingest(env);\n unacked.set(key, env);\n hooks.onOutboxChange?.();\n declare(); // the outbox filled: not ready\n if (status === 'live') sendEnv(env);\n });\n\n return {\n connect,\n status: () => status,\n lastSeq: () => lastSeq,\n hasUnacked: () => unacked.size > 0,\n whenAcked: () =>\n ackFailure\n ? Promise.reject(ackFailure)\n : unacked.size === 0\n ? Promise.resolve()\n : new Promise<void>((resolve, reject) => {\n ackWaiters.push({ resolve, reject });\n }),\n unackedEnvs: () => [...unacked.values()],\n instance: () => instance,\n peers: () => peers,\n sendSignal: (msg) => {\n if (!closed && msg.room === opt.room) transport?.send(msg);\n },\n sendDirect: (to, data) => {\n if (closed) return;\n transport?.send({\n t: 'direct',\n room: opt.room,\n to,\n v: MESH_DIRECT_VERSION,\n data,\n });\n },\n setPresence: (data) => {\n presenceData = data;\n hasPresence = true;\n if (status === 'live') {\n transport?.send({ t: 'presence', room: opt.room, data });\n }\n },\n conflicts,\n declareReady: (next) => {\n pressed = next;\n declare();\n },\n record: () => ({\n ...(gen\n ? {\n generation: {\n instance: gen.instance,\n index: gen.index,\n reason: gen.reason,\n policy: gen.policy,\n extent: gen.extent,\n preCutMax: gen.preCutMax,\n },\n admission: admissionRecord(admission),\n }\n : {}),\n intents: [...unacked.values()].map((env) => ({\n origin: env.origin,\n version: env.version,\n intent: intents.get(unackedKey(env)) ?? intentOf(env, () => Number.POSITIVE_INFINITY),\n })),\n conflicts: held.map((h) => ({ env: h.env, intent: h.intent, cause: h.cause })),\n ...(owed !== undefined ? { rehydrateOwed: owed } : {}),\n }),\n close: () => terminal('closed'),\n };\n}\n","import { signal, type Signal } from '@angular/core';\nimport { createWatch } from '@angular/core/primitives/signals';\nimport type {\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n createStoreContext,\n forkStore,\n isStoreReservedKey,\n opSync,\n store,\n type DotFrontier,\n type ForkStoreOptions,\n type DiffOpsOptions,\n type MergePolicyEntry,\n type OpLogDriver,\n type OpSync,\n type StoreOp,\n type SyncedFork,\n type toStoreOptions,\n type WritableSignalStore,\n type OpEnvelope,\n} from '@mmstack/primitives/core';\nimport type { SeatSync } from './mesh-sync';\nimport {\n deliverDirect,\n meshSession,\n type CompactionState,\n type MeshConflict,\n type MeshDirect,\n type MeshStatus,\n} from './session';\nimport type { MeshTransportFactory } from './transport';\n\nconst microtaskDriver = (): OpLogDriver => (run) => {\n let scheduled = false;\n const watch = createWatch(\n () => run(),\n (w) => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n w.run();\n });\n },\n false,\n );\n watch.notify();\n return { destroy: () => watch.destroy() };\n};\n\n/** A sequenced batch of another writer's ops, delivered in relay order. */\nexport type SeatChange = {\n readonly kind: 'change';\n /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past\n * the relay's retention, or a relay restart) without seeing the individual changes in\n * between. Anything accumulated from prior `change` events — narration buffers, cached\n * prompt prefixes — no longer extends the stream and must be rebuilt from current state.\n */\nexport type SeatResync = {\n readonly kind: 'resync';\n /** The seq the re-established state corresponds to. */\n readonly seq: number;\n};\n\nexport type SeatEvent = SeatChange | SeatResync;\n\n/** A base state provably derivable from the room's history alone — safe to cache. */\nexport type StableSnapshot<T> = {\n /** The relay seq this state is the fold of. */\n readonly seq: number;\n readonly doc: T;\n};\n\nexport type AgentSeatOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. One identity per seat. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * How the seat's writes are diffed into ops (forwarded to its `opSync`; see `DiffOpsOptions`).\n * Absent: whole-value adds, as before. A per-path `added` predicate keeps chosen collections\n * leafy while each entry stays one atomic `set` (the whole-entry law the relay holds agents to).\n */\n readonly emit?: DiffOpsOptions;\n /**\n * Emit-side validation, symmetric with the relay's — an optimization, not the\n * enforcement (the relay validates every envelope regardless). A violating write is\n * never sent and ejects the seat exactly as the relay would have; the refused value\n * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.\n */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion?: number;\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;\n * pass your own to share proxy caches across several seats in one process.\n */\n readonly context?: toStoreOptions;\n readonly onEject?: (reason: string) => void;\n /** A write the relay refused; it is not in the room, and the doc was rehydrated. The envelope carries its values. */\n readonly onRefused?: (\n env: OpEnvelope,\n reason: 'generation' | 'schema' | 'order' | 'compacting',\n ) => void;\n};\n\nexport type AgentSeat<T extends object> = {\n /** The live converging replica. Reads exactly like a local signal store. */\n readonly doc: WritableSignalStore<T & Record<string, any>>;\n status(): MeshStatus;\n peers(): readonly PresenceState[];\n /** The current document value — plain JSON-serializable data, for context assembly. */\n snapshot(): T;\n /**\n * The current document, stamped with the relay seq it is provably the pure fold of\n * or null when stability cannot be guaranteed\n */\n stableSnapshot(): StableSnapshot<T> | null;\n /** Run local writes and emit them to the room as one envelope, like any peer's edit. */\n write(fn: () => void): void;\n /**\n * The seat's writes that will never be admitted as they stand (a replay a compaction cut could not\n * carry, or a relay refusal), each with `discard()` and `reauthor()`.\n */\n conflicts(): readonly MeshConflict[];\n /** The room's compaction state as the relay last announced it; undefined before any notice. */\n readonly compaction: Signal<CompactionState | undefined>;\n /**\n * The seat pressed (`true`) or released Compact: it declares itself ready for a consensus cut\n * whenever it is connected and nothing it wrote is outstanding, re-declaring on every change. A\n * reconnect or a new generation releases it.\n */\n declareReady(pressed: boolean): void;\n /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */\n setAtPath(path: string | readonly (string | number)[], value: unknown): void;\n /**\n * The room's sequenced history as it arrives: `change` events carry another writer's ops\n * in strictly increasing seq order, so a listener may append them (narration, prompt\n * suffixes) without any diffing. A `resync` event voids that guarantee — everything\n * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).\n * Own writes never echo here.\n */\n changes(cb: (event: SeatEvent) => void): () => void;\n /**\n * An isolated branch for a reviewable proposal. The fork observes the room as it is now;\n * `commit()` emits its diff citing only those observed writes, so a room edit that lands\n * while the fork is open survives as a concurrent value for the merge policy to resolve\n * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the\n * staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /**\n * Every local write is acknowledged by the room. `false` while a write is still in the\n * unacknowledged tail, and it stays `false` once the seat ends with writes outstanding.\n */\n acked(): boolean;\n /**\n * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects\n * with the terminal reason if the seat ends while writes are outstanding. The barrier to\n * await before handing a result to something that must contain every edit.\n */\n whenAcked(): Promise<void>;\n /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */\n setPresence(data: unknown): void;\n /**\n * Send an ephemeral payload to one member, by origin. The relay routes it to that member only\n * and never persists it; with no connection, or `to` not in the room, it is lost.\n */\n send(to: string, data: unknown): void;\n /**\n * Listen for `direct` frames addressed to this seat; returns the unsubscribe. A frame that\n * arrives with no listener is lost.\n */\n direct(cb: (msg: MeshDirect) => void): () => void;\n /** Authority surface over this seat's op-sync; see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n close(): void;\n};\n\n/**\n * A headless mesh peer: the same replica and wire contract `meshSync` implements in the\n * browser, without Angular's injector or any browser API — for agents, server-side bridges,\n * and device writers joining a room as first-class, attributed participants. Each call is\n * one identity with its own replica; run several seats in one process for several\n * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as\n * to any human peer.\n */\nexport function agentSeat<T extends object>(\n initial: T,\n opt: AgentSeatOptions,\n): AgentSeat<T> {\n const context = opt.context ?? createStoreContext();\n const root = store(initial as T & Record<string, any>, context);\n const doc = root as unknown as WritableSignalStore<T & Record<string, any>>;\n const read = root as unknown as () => T;\n const policyVersion = opt.policyVersion ?? 0;\n\n // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's\n // ops (which did NOT apply) out of the change stream.\n let rejected = false;\n const sync = opSync(root as never, {\n writer: opt.writer,\n policies: opt.policies,\n policyVersion,\n driver: microtaskDriver(),\n emit: opt.emit,\n onReject: (_env, reason) => {\n rejected = true;\n console.warn(\n `[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`,\n );\n },\n }) as OpSync<T>;\n\n const listeners = new Set<(event: SeatEvent) => void>();\n const directListeners = new Set<(msg: MeshDirect) => void>();\n const emit = (event: SeatEvent): void => {\n for (const cb of [...listeners]) cb(event);\n };\n const compaction = signal<CompactionState | undefined>(undefined);\n let welcomed = false;\n let diverged = false;\n let terminated = false;\n let lostWrites = false;\n\n const session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n // the recorded raw ops re-stamped against the current registers, as one new envelope\n reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),\n hooks: {\n onStatus: (s, reason) => {\n if (s === 'live') welcomed = true;\n if (s === 'ejected' && reason !== undefined) opt.onEject?.(reason);\n },\n onRemote: (batch) => {\n if (rejected) {\n rejected = false;\n return;\n }\n emit({ kind: 'change', ...batch });\n },\n onResync: (seq) => emit({ kind: 'resync', seq }),\n onDirect: (msg) => deliverDirect(directListeners, msg),\n onCompaction: (state) => compaction.set(state),\n onConflicts: (list) => {\n // a refused write stays applied until the rehydrate that follows lands\n if (list.some((c) => c.cause !== 'uncovered')) diverged = true;\n },\n onRefused: (env, reason) => {\n diverged = true; // the write stays applied until the rehydrate that follows lands\n opt.onRefused?.(env, reason);\n },\n onLocalReject: (violation) => {\n diverged = true; // the write stays in the replica but will never reach the room\n console.warn(\n '[@mmstack/mesh] agent seat write violates the room policy — not sent',\n violation,\n );\n },\n onTerminal: () => {\n if (session.hasUnacked()) {\n diverged = true;\n lostWrites = true; // latched: no echo can arrive for them now\n }\n terminated = true;\n },\n },\n });\n // a write after the terminal state is one the room will never sequence: the doc keeps it\n // (post-mortem), but the seat stops claiming provable folds — same latch as a refused write\n sync.subscribe(() => {\n if (terminated) diverged = true;\n });\n session.connect();\n\n return {\n doc,\n status: () => session.status(),\n peers: () => [...session.peers().values()],\n snapshot: () => read(),\n stableSnapshot: () => {\n sync.flush(); // a write made this tick must count as pending, not linger unstamped\n if (!welcomed || diverged || session.hasUnacked()) return null;\n return { seq: session.lastSeq(), doc: read() };\n },\n write: (fn) => {\n fn();\n sync.flush();\n },\n conflicts: () => session.conflicts(),\n compaction: compaction.asReadonly(),\n declareReady: (pressed) => session.declareReady(pressed),\n setAtPath: (path, value) => {\n setAtPath(doc, path, value);\n sync.flush();\n },\n changes: (cb) => {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(doc, forkOpt);\n let frontier: DotFrontier = sync.captureFrontier();\n const recapture = (): void => {\n frontier = sync.captureFrontier();\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () => {\n sync.commitScope(frontier, () => f.commit());\n sync.flush();\n },\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n acked: () => {\n sync.flush(); // a write made this tick counts as pending, not as unstamped\n return !lostWrites && !session.hasUnacked();\n },\n whenAcked: () => {\n sync.flush();\n return session.whenAcked();\n },\n setPresence: (data) => session.setPresence(data),\n send: (to, data) => session.sendDirect(to, data),\n direct: (cb) => {\n directListeners.add(cb);\n return () => directListeners.delete(cb);\n },\n sync: {\n override: (fn) => sync.override(fn),\n captureFrontier: () => sync.captureFrontier(),\n commitScope: (frontier, fn) => sync.commitScope(frontier, fn),\n liveUnder: (path) => sync.liveUnder(path),\n liveAt: (path) => sync.liveAt(path),\n appliedFrontier: () => sync.appliedFrontier(),\n },\n close: () => {\n diverged = true; // sync is destroyed below: later writes are unwatched, so no more proofs\n session.close();\n sync.destroy();\n },\n };\n}\n\ntype PathSegment = string | number;\n\nconst parsePath = (\n path: string | readonly PathSegment[],\n): readonly PathSegment[] =>\n typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;\n\n// resolve a string segment against an array ('0' → 0) so dot-paths address list items\nconst resolveKey = (current: unknown, seg: PathSegment): PathSegment =>\n Array.isArray(current) && typeof seg === 'string' && /^\\d+$/.test(seg)\n ? Number(seg)\n : seg;\n\nfunction withPathSet(\n current: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): unknown {\n if (path.length === 0) return value;\n const [head, ...rest] = path;\n if (Array.isArray(current)) {\n const idx = typeof head === 'number' ? head : Number(head);\n const copy = [...current];\n copy[idx] = withPathSet(current[idx], rest, value);\n return copy;\n }\n const base =\n current !== null && typeof current === 'object'\n ? (current as Record<PathSegment, unknown>)\n : {};\n return { ...base, [head]: withPathSet(base[head], rest, value) };\n}\n\n/**\n * Applies `value` at a path on a signal-store node — the write shape a tool-calling model\n * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as\n * the path exists in the current value and finishes with one immutable set on the deepest\n * real node, which also covers paths that do not exist yet (a fresh record key creates it).\n * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer\n * `seat.setAtPath`, which also emits immediately.\n */\nexport function setAtPath(\n node: unknown,\n path: string | readonly PathSegment[],\n value: unknown,\n): void {\n const segs = parsePath(path);\n let cursor = node as Record<PathSegment, unknown> & {\n (): unknown;\n set(v: unknown): void;\n };\n let walked = 0;\n for (const seg of segs) {\n const current = cursor();\n if (current === null || typeof current !== 'object') break;\n const key = resolveKey(current, seg);\n // a key the node answers itself has no child node; the rest of the path is set on this value\n if (!Object.hasOwn(current, key) || isStoreReservedKey(key)) break;\n const child = cursor[key];\n if (typeof child !== 'function') break;\n cursor = child as typeof cursor;\n walked++;\n }\n const rest = segs.slice(walked);\n if (rest.length === 0) {\n cursor.set(value);\n return;\n }\n cursor.set(withPathSet(cursor(), rest, value));\n}\n\nconst MAX_VALUE_CHARS = 120;\n\nconst printable = (value: unknown): string => {\n const json = JSON.stringify(value);\n if (json === undefined) return String(value);\n return json.length > MAX_VALUE_CHARS\n ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`\n : json;\n};\n\n/**\n * One store op as a plain-English line (\"mira set plan.endDate to \\\"2026-10-11\\\"\"), for\n * activity feeds and model context. Values render as truncated JSON. Pair with a seat's\n * `changes` stream: narrating each batch's ops yields an append-only account of the room.\n */\nexport function describeOp(op: StoreOp, writer: string): string {\n const at = op.path.length === 0 ? 'the document root' : op.path.join('.');\n switch (op.kind) {\n case 'set':\n return `${writer} set ${at} to ${printable(op.next)}`;\n case 'delete':\n return `${writer} removed ${at}`;\n case 'clear':\n return `${writer} cleared ${at}`;\n }\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport type {\n IceServer,\n OpPolicy,\n PresenceState,\n PrincipalCtx,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n type AsyncStore,\n type DiffOpsOptions,\n type DotFrontier,\n type ForkStoreOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type SyncOp,\n type WritableSignalStore,\n type Hlc,\n} from '@mmstack/primitives/core';\nimport {\n deliverDirect,\n meshSession,\n type CompactionState,\n type GenerationState,\n type MeshConflict,\n type MeshDirect,\n type MeshSession,\n type MeshStatus,\n type SessionRecord,\n} from './session';\nimport type { MeshTransportFactory } from './transport';\nimport type { SignalingPort } from './peer-links';\n\nexport type {\n CompactionState,\n ConflictCause,\n GenerationState,\n Intent,\n MeshConflict,\n MeshDirect,\n MeshStatus,\n} from './session';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n */\nexport type SyncHealthStatus =\n 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`. */\n readonly reason?:\n 'proto' | 'policy-version' | 'schema' | 'quota' | 'worker' | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * Offline writes persisted by an older build that could not be restored on boot. Envelopes\n * from a previous wire-protocol version lack the citation metadata current merging needs,\n * so they are dropped (loudly) instead of being upgraded with fabricated citations.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * Writes the relay refused on this session: they are not in the room. Each was handed to\n * `onRefused` with its values, and the store was rehydrated from a fresh snapshot after it.\n */\n readonly refusedWrites?: number;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent:\n * whole-value adds, as before. A per-path `added` predicate keeps chosen collections leafy (so\n * concurrent first writers merge) while their entries stay one atomic `set`.\n */\n readonly emit?: DiffOpsOptions;\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n readonly onEject?: (reason: string) => void;\n /** The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message too big, 1006 = dropped). */\n readonly onDisconnect?: (code: number, reason: string) => void;\n /** A write the relay refused (see `MeshSessionHooks.onRefused`); the envelope carries its values. */\n readonly onRefused?: (\n env: OpEnvelope,\n reason: 'generation' | 'schema' | 'order' | 'compacting',\n ) => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes\n * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room\n * on the next welcome, instead of being lost with in-memory state. The payload is written to\n * `store` under `key`, debounced.\n *\n * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so\n * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects\n * the one tab that restores from the slot and writes to it; origins are fresh on every boot either\n * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the\n * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner\n * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and\n * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced\n * write means a hard crash within the debounce window can drop the very last mint — a small,\n * best-effort gap; tune it with `debounceMs`.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: AsyncStore;\n /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */\n readonly debounceMs?: number;\n /**\n * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the\n * Web Lock elects the one tab that restores from it and writes to it.\n * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and\n * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin\n * and never touches the slot — its unacknowledged writes live in memory only and are lost if that\n * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral\n * for life, also after the owner leaves. When the lock is free both behave the same (take it,\n * restore, persist). `'off'` skips the lock (you coordinate ownership).\n */\n readonly crossTab?: 'queue' | 'off' | 'ephemeral';\n };\n};\n\n/**\n * The client's durable record, persisted under `outbox.key` as ONE unit: the writing boot's origin,\n * the emit high-water and the tail, and the session's record beside them (the tail's generation\n * fields and evidence, its intents, unresolved conflicts and an owed snapshot). No registers and no\n * sequence knowledge: a restart never trusts stale registers — it holds none, asks for a snapshot\n * and resends the tail first.\n */\ntype PersistedOutbox = SessionRecord & {\n /** The origin of the boot that wrote the slot; the next boot mints its own and resends the tail verbatim. */\n readonly origin: string;\n readonly version: number;\n readonly envs: readonly OpEnvelope[];\n /** The room generation the tail was written in; the first welcome decides whether it still holds. */\n readonly instance?: string;\n /** Emission epoch floors: a floor whose own sibling was collected has no other source on reload. */\n readonly floors?: readonly {\n readonly path: readonly (string | number)[];\n readonly epoch: number;\n }[];\n /** The last stamp minted: an acked, dropped tail still moved the clock. */\n readonly clock?: Hlc;\n};\n\n/**\n * The authority surface of a peer's op-sync, for callers that compose over a seat rather than\n * inside it: `override` for authority-bumped writes (`rebalanceContainer`, an owner's\n * authoritative commit), `captureFrontier` + `commitScope` for a commit that cites what was\n * observed earlier (a fork whose base is kept elsewhere), `liveUnder` / `liveAt` to read live\n * registers and `appliedFrontier` for the observation vector they are compared against (a\n * conflict projection: \"did the writer see this sibling\", answered by causality, never by order).\n * Deliberately narrow: no `receive`, `flush`, or `destroy` — those stay the seat's own.\n */\nexport type SeatSync<T = unknown> = Pick<\n OpSync<T>,\n | 'override'\n | 'captureFrontier'\n | 'commitScope'\n | 'liveUnder'\n | 'liveAt'\n | 'appliedFrontier'\n>;\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */\n readonly origin: Signal<string | null>;\n /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */\n readonly members: Signal<readonly string[]>;\n /** Peer signaling on this session's connection; buffers up to 256 early signals until the first listener. */\n readonly signaling: SignalingPort;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n /**\n * Every local write is acknowledged by the room. `false` while a write is still in the\n * unacknowledged tail, and it stays `false` once a session ends with writes outstanding —\n * those never landed, and no later echo can arrive to change that.\n */\n readonly acked: Signal<boolean>;\n /**\n * Resolves when the unacknowledged tail is empty (immediately if it already is), rejects\n * with the terminal reason if the session ends while writes are outstanding. The barrier\n * to await before publishing something that must contain every edit; `synced()` is a\n * connection indicator, not a save barrier.\n */\n whenAcked(): Promise<void>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Send an ephemeral payload to one member, by origin. The relay routes it to that member only\n * and never persists it; with no connection, or `to` not in the room, it is lost.\n */\n send(to: string, data: unknown): void;\n /**\n * Listen for `direct` frames addressed to this client; returns the unsubscribe. A frame that\n * arrives with no listener is lost. Peer links on {@link MeshSyncRef.signaling} never see them.\n */\n direct(cb: (msg: MeshDirect) => void): () => void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /** Authority surface over the CURRENT op-sync (it is rebuilt on restore); see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n /**\n * Writes that will never be admitted as they stand: a write a compaction cut could not replay\n * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or\n * `reauthor()` (write its values again, citing the current state). Persisted with the outbox.\n */\n readonly conflicts: Signal<readonly MeshConflict[]>;\n /** The room's compaction state as the relay last announced it; undefined before any notice. */\n readonly compaction: Signal<CompactionState | undefined>;\n /**\n * The room generation this client installed: set by every snapshot welcome of a new generation\n * (a cut's welcome flips it), untouched by one of the installed generation. Undefined until the\n * first snapshot welcome and after a room was recreated without its record.\n */\n readonly generation: Signal<GenerationState | undefined>;\n /**\n * The member pressed (`true`) or released Compact: the client declares itself ready for a\n * consensus cut whenever nothing it wrote is outstanding, re-declaring on every change. A\n * reconnect or a new generation releases it.\n */\n declareReady(pressed: boolean): void;\n close(): void;\n};\n\nconst OUTBOX_DEBOUNCE_MS = 300;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const origin = signal<string | null>(null);\n const members = signal<readonly string[]>([]);\n let membership: readonly string[] | undefined;\n // the last roster the links on the port were given; a socket drop blanks the session's, not this\n let roster: readonly string[] = [];\n const signalingListeners = new Set<(msg: ServerMsg) => void>();\n const directListeners = new Set<(msg: MeshDirect) => void>();\n let earlySignals: ServerMsg[] | null = [];\n // the ICE servers of the last welcome, for peer links that attach after it\n let welcomeIce: readonly IceServer[] | undefined;\n const deliverSignal = (\n cb: (msg: ServerMsg) => void,\n msg: ServerMsg,\n ): void => {\n try {\n cb(msg);\n } catch {\n // A failed peer link must never interrupt the room's sync session or other listeners.\n }\n };\n const signalMessage = (msg: ServerMsg): void => {\n if (msg.t === 'welcome') welcomeIce = msg.ice;\n if (msg.t === 'welcome' && earlySignals !== null) earlySignals = [];\n if (msg.t === 'member' && msg.gone && earlySignals !== null) {\n earlySignals = earlySignals.filter(\n (held) => held.t !== 'signal' || held.from !== msg.origin,\n );\n }\n if (\n msg.t === 'signal' &&\n earlySignals !== null &&\n earlySignals.length < 256\n ) {\n earlySignals.push(msg);\n }\n for (const cb of [...signalingListeners]) deliverSignal(cb, msg);\n };\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const acked = signal(true); // nothing has been written yet\n const refused = signal(0);\n const droppedInvalid = signal(0);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const conflicts = signal<readonly MeshConflict[]>([]);\n const compaction = signal<CompactionState | undefined>(undefined);\n const generation = signal<GenerationState | undefined>(undefined);\n const peers = computed(() => [...peerMap().values()]);\n const policyVersion = opt.policyVersion ?? 0;\n\n const health = computed<SyncHealth>(() => {\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(refused() > 0 ? { refusedWrites: refused() } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'waiting':\n return { status: 'waiting', lastSyncedAt: at, ...extra };\n case 'ejected': {\n const reason = lastReason();\n return reason && OUTDATED_REASONS.has(reason)\n ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }\n : { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n }\n default: // connecting / reconnecting / closed — not reachable\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n // Created lazily: with a persisted outbox the slot lock and the restored tail come first, so the\n // engine never mints before it knows the generation it is in\n let sync!: OpSync<T>;\n let session: MeshSession | undefined;\n let started = false;\n let closed = false;\n let pendingPresence: { data: unknown } | undefined;\n let persistTimer: ReturnType<typeof setTimeout> | undefined;\n let pendingPersist: Promise<void> | undefined;\n let releaseLock: (() => void) | undefined;\n let cancelLock: (() => void) | undefined;\n // this tab owns the persisted slot ('off', no Web Locks, or a granted lock); an ephemeral boot never does\n let durable = false;\n // the slot's clock high-water as restored: persisted back until this boot mints its own stamp\n let restoredClock: Hlc | undefined;\n\n // resolves when the store has the payload (a failed write resolves too: persistence is best-effort)\n const doPersist = (): Promise<void> => {\n if (closed || !opt.outbox || !started || !session || !durable)\n return Promise.resolve(); // ephemeral: never writes\n const instance = session.instance();\n const clock = sync.lastStamp() ?? restoredClock;\n const payload: PersistedOutbox = {\n origin: sync.origin,\n version: sync.watermark()[sync.origin] ?? 0,\n envs: session.unackedEnvs(),\n ...(instance ? { instance } : {}),\n floors: sync.floors(),\n ...(clock ? { clock } : {}),\n ...session.record(),\n };\n const { store, key } = opt.outbox;\n // Capture before queueing: teardown clears the session's tail immediately after this call.\n const write = (): Promise<void> => {\n try {\n return Promise.resolve(store.set(key, payload)).then(\n () => undefined,\n () => undefined,\n );\n } catch {\n return Promise.resolve(); // a failed save must not block later saves or lock release\n }\n };\n // Keep the idle path synchronous, but never let an older save land after a newer one.\n const pending = pendingPersist ? pendingPersist.then(write) : write();\n pendingPersist = pending;\n void pending.then(() => {\n if (pendingPersist === pending) pendingPersist = undefined;\n });\n return pending;\n };\n // coalesce outbox writes; `immediate` bypasses the debounce, but waits for earlier saves\n const persistOutbox = (immediate = false): Promise<void> => {\n if (!opt.outbox) return Promise.resolve();\n if (immediate) {\n if (persistTimer !== undefined) clearTimeout(persistTimer);\n persistTimer = undefined;\n return doPersist();\n }\n if (persistTimer === undefined) {\n persistTimer = setTimeout(() => {\n persistTimer = undefined;\n void doPersist();\n }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);\n }\n return Promise.resolve(); // the debounced path is not awaited\n };\n\n const dropLocks = (): void => {\n cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown\n releaseLock?.(); // free a held lock for the next waiting tab\n cancelLock = releaseLock = undefined;\n };\n\n // Only a tail this boot could actually get admitted is worth resending: recorded under\n // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin\n // per envelope, so restoring one would eject the boot, persist the tail intact, and brick\n // every boot after). Anything else drops loudly instead.\n const restorable = (env: OpEnvelope): boolean =>\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n env.ops.every(\n (op) =>\n Array.isArray((op as SyncOp).cites) &&\n typeof (op as SyncOp).epoch === 'number',\n );\n\n const initCore = (restore?: PersistedOutbox): void => {\n if (closed) return;\n restoredClock = restore?.clock;\n sync = opSync(source, {\n writer: opt.writer,\n instance: restore?.instance,\n policies: opt.policies,\n policyVersion,\n injector,\n emit: opt.emit,\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`,\n );\n }\n },\n });\n started = true;\n // set once this session ends: only then are the links riding on its port retired\n let ended = false;\n session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n instance: restore?.instance,\n record: restore,\n // the recorded raw ops re-stamped against the current registers, as one new envelope\n reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),\n reconnect: opt.reconnect,\n hooks: {\n onOrigin: (value) => origin.set(value),\n onMembers: (value) => {\n membership = value;\n members.set(value ?? []);\n if (value !== undefined) {\n roster = value;\n return;\n }\n if (earlySignals !== null) earlySignals = [];\n // Peer links outlive a socket drop: the next welcome re-lists who is still there. A\n // borrowed port has no close of its own, so the session's end retires them here, from\n // the last roster the links saw (a drop before the close already blanked the session's).\n if (!ended) return;\n const retired = roster;\n roster = [];\n for (const origin of retired) {\n signalMessage({ t: 'member', room: opt.room, origin, gone: true });\n }\n },\n onMessage: signalMessage,\n onDirect: (msg) => deliverDirect(directListeners, msg),\n onRefused: (env, reason) => {\n refused.update((n) => n + 1);\n opt.onRefused?.(env, reason);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`,\n );\n }\n },\n onStatus: (s, reason) => {\n if (s === 'ejected' || s === 'closed') {\n closed = true;\n lastReason.set(reason);\n }\n status.set(s);\n if ((s === 'ejected' || s === 'closed') && reason !== undefined) {\n opt.onEject?.(reason);\n }\n },\n onDisconnect: (code, reason) => opt.onDisconnect?.(code, reason),\n onSynced: () => lastSyncedAt.set(Date.now()),\n onPeers: (map) => peerMap.set(map),\n onConflicts: (list) => conflicts.set(list),\n onCompaction: (state) => compaction.set(state),\n onGeneration: (next) => generation.set(next),\n onOutboxChange: () => {\n void persistOutbox();\n acked.set(!session?.hasUnacked());\n },\n onTerminal: () => {\n ended = true;\n // latched: the tail is about to be dropped from the session, but it was never\n // acknowledged, so the answer to \"is everything I wrote in the room\" stays no\n if (session?.hasUnacked()) acked.set(false);\n // save the still-unacked tail for the next boot, and release the lock only once the store\n // has it: a successor granted earlier could restore the slot before this write lands\n let saved: Promise<void>;\n try {\n saved = persistOutbox(true);\n } catch {\n saved = Promise.resolve(); // a failed capture must still hand the slot on\n }\n void saved.finally(dropLocks);\n },\n onLocalReject: (violation) => {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n },\n },\n });\n if (\n restore &&\n (restore.envs.length > 0 ||\n restore.version > 0 ||\n (restore.floors?.length ?? 0) > 0 ||\n restore.clock !== undefined)\n ) {\n const kept = restore.envs.filter(restorable);\n const dropped = restore.envs.length - kept.length;\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`,\n );\n }\n }\n\n sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend\n }\n void persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe\n if (pendingPresence) {\n session.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n session.connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting' || s === 'waiting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () =>\n status() === 'connecting' ||\n status() === 'waiting' ||\n status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n const teardown = (): void => {\n if (session) {\n session.close(); // no-op if already terminal; onTerminal handled locks + persist\n } else if (!closed) {\n // closed before the (async) boot ever created the session\n closed = true;\n dropLocks();\n status.set('closed');\n }\n if (started) sync.destroy();\n };\n\n injector.get(DestroyRef).onDestroy(teardown);\n\n // Load the persisted outbox, then boot on a fresh origin. A fresh/unreadable slot boots clean.\n const bootFromDisk = async (): Promise<void> => {\n durable = true; // every caller owns the slot\n if (closed || !opt.outbox) return;\n let saved: PersistedOutbox | undefined;\n try {\n const raw = await opt.outbox.store.get(opt.outbox.key);\n saved =\n raw && typeof raw === 'object' && 'origin' in raw\n ? (raw as PersistedOutbox)\n : undefined;\n } catch {\n saved = undefined; // an unreadable slot must not wedge the boot\n }\n initCore(saved);\n };\n\n const beginConnect = (): void => {\n if (closed) return;\n if (!opt.outbox) {\n initCore();\n } else if ((opt.outbox.crossTab ?? 'queue') === 'off') {\n void bootFromDisk(); // no single-writer lock — the app coordinates ownership\n } else {\n const locks = globalThis.navigator?.locks;\n const mode = opt.outbox.crossTab ?? 'queue';\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] outbox crossTab:\"${mode}\" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock ('queue' and 'ephemeral' both own the slot). Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:\"off\" to silence this.`,\n );\n }\n void bootFromDisk();\n return;\n }\n const name = `@mmstack/mesh:outbox:${opt.outbox.key}`;\n // hold a granted lock until teardown resolves this promise\n const hold = (queued = false): Promise<void> => {\n cancelLock = undefined; // granted — no longer abortable, only releasable\n if (closed) return Promise.resolve();\n if (queued) status.set('connecting'); // the wait ends with the grant\n return new Promise<void>((release) => {\n releaseLock = release;\n void bootFromDisk();\n });\n };\n const queueUp = (): void => {\n status.set('waiting');\n const abort = new AbortController();\n cancelLock = () => abort.abort();\n void locks\n .request(name, { mode: 'exclusive', signal: abort.signal }, () =>\n hold(true),\n )\n .catch((e: unknown) => {\n // an aborted request is our own teardown; any other failure → degrade to no-lock\n if (\n !closed &&\n !started &&\n (e as { name?: string })?.name !== 'AbortError'\n ) {\n status.set('connecting'); // no longer waiting on anyone\n void bootFromDisk();\n }\n });\n };\n // Web Locks forbids `signal` together with `ifAvailable`, hence the probe first\n void locks\n .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {\n if (lock === null) {\n // another tab owns the slot\n if (closed) return Promise.resolve();\n if (mode === 'ephemeral') {\n initCore(); // live at once on a fresh origin; never reads or writes the slot\n return Promise.resolve();\n }\n queueUp();\n return Promise.resolve();\n }\n return hold();\n })\n .catch(() => {\n if (!closed && !started) void bootFromDisk(); // a broken lock manager degrades to no-lock\n });\n }\n };\n\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n return {\n status: status.asReadonly(),\n origin: origin.asReadonly(),\n members: members.asReadonly(),\n signaling: {\n members: () => membership,\n iceServers: () => welcomeIce,\n send: (msg) => session?.sendSignal(msg),\n onMessage: (cb) => {\n signalingListeners.add(cb);\n const held = earlySignals ?? [];\n earlySignals = null;\n for (const msg of held) deliverSignal(cb, msg);\n return () => signalingListeners.delete(cb);\n },\n },\n health,\n acked: acked.asReadonly(),\n whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet\n peers,\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n send: (to, data) => session?.sendDirect(to, data),\n direct: (cb) => {\n directListeners.add(cb);\n return () => directListeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n conflicts: conflicts.asReadonly(),\n compaction: compaction.asReadonly(),\n generation: generation.asReadonly(),\n declareReady: (pressed) => session?.declareReady(pressed),\n sync: {\n override: (fn) => (started ? sync.override(fn) : fn()),\n captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),\n commitScope: (frontier, fn) =>\n started ? sync.commitScope(frontier, fn) : fn(),\n liveUnder: (path) => (started ? sync.liveUnder(path) : []),\n liveAt: (path) => (started ? sync.liveAt(path) : []),\n appliedFrontier: () => (started ? sync.appliedFrontier() : {}),\n },\n close: teardown,\n };\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n /** `code` and `reason` are the close frame's (1006 for a dropped connection, 1000 for a normal close). */\n onClose(cb: (code: number, reason: string) => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<(code: number, reason: string) => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = (event) => {\n for (const cb of [...closeCbs]) cb(event.code, event.reason);\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/** A message as it reads after a JSON hop: keys holding `undefined` gone, such array slots `null`. */\nconst asJson = <T>(msg: T): T => JSON.parse(JSON.stringify(msg)) as T;\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n *\n * Messages cross as JSON in both directions, as they would over a socket, so a direct peer holds\n * exactly what a socket peer would. Handed over by reference, an `undefined` an emitter wrote\n * would reach relay memory where a socket peer's would have been dropped.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n): MeshTransportFactory {\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<(code: number, reason: string) => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n const wired = asJson(msg);\n for (const cb of [...messageCbs]) cb(wired);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb(1000, '');\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(asJson(msg));\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb(1000, '');\n },\n };\n };\n}\n","/**\n * The per-origin lifecycle of peer links as a pure reducer. `peerLinks` feeds it every\n * membership and link event and executes the effects it returns, in order; nothing else\n * decides when a link is built, dropped or rebuilt.\n *\n * While the links are open, every listed origin is in exactly one state: `linking` (a peer, an\n * open timeout armed), `open` (a peer, every channel open, no timer) or `waiting` (no peer, a\n * rebuild timer armed). An unlisted origin has no state. After `close` nothing happens again.\n */\nexport type LinkState = 'linking' | 'open' | 'waiting';\n\nexport type LifecycleEvent =\n /** A member joined, or a waiting member's announce arrived: build now. */\n | { readonly t: 'listed'; readonly origin: string }\n | { readonly t: 'welcome'; readonly members: readonly string[] }\n | { readonly t: 'gone'; readonly origin: string }\n | { readonly t: 'opened'; readonly origin: string }\n /** A channel closed, the connector reported the link gone, or the open timeout fired. */\n | { readonly t: 'lost'; readonly origin: string }\n /** The rebuild timer fired. */\n | { readonly t: 'due'; readonly origin: string }\n | { readonly t: 'close' };\n\nexport type LifecycleEffect =\n | { readonly t: 'build'; readonly origin: string }\n | { readonly t: 'drop'; readonly origin: string }\n | { readonly t: 'armOpen'; readonly origin: string }\n | {\n readonly t: 'armRetry';\n readonly origin: string;\n readonly attempt: number;\n }\n | { readonly t: 'disarm'; readonly origin: string };\n\nexport type LinkEntry = {\n readonly state: LinkState;\n /** Losses since the link last opened. */\n readonly attempt: number;\n /** Lost at least once since it last opened. */\n readonly stalled: boolean;\n};\n\nexport type Lifecycle = ReadonlyMap<string, LinkEntry>;\n\nexport type LifecycleStep = {\n readonly next: Lifecycle;\n readonly effects: readonly LifecycleEffect[];\n};\n\n/** The starting value: nothing listed. */\nexport const emptyLifecycle: Lifecycle = new Map();\n\n/** The value after `close`; `step` recognises it by identity and ignores every later event. */\nexport const closedLifecycle: Lifecycle = new Map();\n\nconst hasPeer = (e: LinkEntry | undefined): boolean =>\n e?.state === 'linking' || e?.state === 'open';\n\nconst hasTimer = (e: LinkEntry | undefined): boolean =>\n e?.state === 'linking' || e?.state === 'waiting';\n\n/**\n * Builds now for a listed origin with no peer; keeps an existing one. The open timeout is\n * armed before the build so a link that opens while it is being built cancels it.\n */\nconst listOne = (\n s: Map<string, LinkEntry>,\n origin: string,\n effects: LifecycleEffect[],\n): void => {\n const cur = s.get(origin);\n if (hasPeer(cur)) return;\n if (cur) effects.push({ t: 'disarm', origin });\n effects.push({ t: 'armOpen', origin }, { t: 'build', origin });\n s.set(origin, {\n state: 'linking',\n attempt: cur?.attempt ?? 0,\n stalled: cur?.stalled ?? false,\n });\n};\n\nconst unlistOne = (\n s: Map<string, LinkEntry>,\n origin: string,\n effects: LifecycleEffect[],\n): void => {\n const cur = s.get(origin);\n if (!cur) return;\n if (hasPeer(cur)) effects.push({ t: 'drop', origin });\n effects.push({ t: 'disarm', origin });\n s.delete(origin);\n};\n\nconst none = (s: Lifecycle): LifecycleStep => ({ next: s, effects: [] });\n\n/** One transition. Pure and total: an event that does not apply returns `s` and no effects. */\nexport function step(s: Lifecycle, e: LifecycleEvent): LifecycleStep {\n if (s === closedLifecycle) return none(s);\n const effects: LifecycleEffect[] = [];\n const next = new Map(s);\n switch (e.t) {\n case 'listed':\n if (hasPeer(s.get(e.origin))) return none(s);\n listOne(next, e.origin, effects);\n break;\n case 'welcome': {\n const listed = new Set(e.members);\n for (const origin of s.keys())\n if (!listed.has(origin)) unlistOne(next, origin, effects);\n for (const origin of listed) listOne(next, origin, effects);\n break;\n }\n case 'gone':\n if (!s.has(e.origin)) return none(s);\n unlistOne(next, e.origin, effects);\n break;\n case 'opened': {\n const cur = s.get(e.origin);\n if (cur?.state !== 'linking') return none(s);\n next.set(e.origin, { state: 'open', attempt: 0, stalled: false });\n effects.push({ t: 'disarm', origin: e.origin });\n break;\n }\n case 'lost': {\n const cur = s.get(e.origin);\n if (!cur || !hasPeer(cur)) return none(s);\n next.set(e.origin, {\n state: 'waiting',\n attempt: cur.attempt + 1,\n stalled: true,\n });\n effects.push(\n { t: 'drop', origin: e.origin },\n { t: 'armRetry', origin: e.origin, attempt: cur.attempt },\n );\n break;\n }\n case 'due': {\n const cur = s.get(e.origin);\n if (cur?.state !== 'waiting') return none(s);\n next.set(e.origin, { ...cur, state: 'linking' });\n effects.push(\n { t: 'armOpen', origin: e.origin },\n { t: 'build', origin: e.origin },\n );\n break;\n }\n case 'close':\n for (const [origin, cur] of s) {\n if (hasPeer(cur)) effects.push({ t: 'drop', origin });\n if (hasTimer(cur)) effects.push({ t: 'disarm', origin });\n }\n return { next: closedLifecycle, effects };\n }\n return { next, effects };\n}\n\n/**\n * The wait before rebuild number `attempt` (0-based): equal jitter over a capped exponential,\n * so every delay lies in `[base / 2, base)` with `base = min(minMs * 2^attempt, maxMs)`.\n */\nexport function retryDelay(\n attempt: number,\n bounds: { readonly minMs: number; readonly maxMs: number },\n random: () => number,\n): number {\n const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);\n return base / 2 + random() * (base / 2);\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n signal,\n untracked,\n type Signal,\n} from '@angular/core';\nimport {\n MESH_PROTO_VERSION,\n type ClientSignalMsg,\n type IceServer,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n emptyLifecycle,\n retryDelay,\n step,\n type LifecycleEffect,\n type LifecycleEvent,\n} from './peer-lifecycle';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */\nexport type PeerChannelSpec = {\n readonly label: string;\n readonly ordered?: boolean;\n readonly maxRetransmits?: number;\n};\n\n/** How many signals are held for replay while a connection waits for its welcome. */\nconst HELD_SIGNALS = 256;\n\n/** The single reliable channel every link carries when no channels are asked for. */\nexport const defaultPeerChannels: readonly PeerChannelSpec[] = [\n { label: 'mmstack-mesh' },\n];\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads. Object payloads gain a\n * `link` field on the way out (the sending link's instance id) and, once the remote instance\n * is known, a `to` field; both are stripped before `signal` sees the payload.\n *\n * `channels` lists the labelled channels the link carries; `channel` is the first of them and\n * `channels` (by label) all of them. A connector that returns only `channel` supports a single\n * channel. Signal payloads carry no channel field: one link per remote carries every channel,\n * so nothing needs routing. The field name `ch` is kept free for a future where it does.\n *\n * `onClose`, when the connector has it, reports the link as a whole finished even if no channel\n * said so; the links then rebuild it.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n readonly channels: readonly PeerChannelSpec[];\n /** ICE servers the relay issued in the last welcome, if any. */\n readonly iceServers?: readonly IceServer[];\n}) => {\n readonly channel: DataChannelLike;\n readonly channels?: Readonly<Record<string, DataChannelLike>>;\n signal(data: unknown): void;\n /** Fires once when the link as a whole is gone, whether or not its channels reported it. */\n onClose?(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.\n *\n * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.\n * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form\n * on one network segment. When ICE fails, or stays `disconnected` longer than\n * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before\n * the link connects again, a closed connection, or a negotiation step the browser rejects\n * reports the link gone through `onClose`.\n */\nexport function rtcPeerConnector(\n config?: RTCConfiguration,\n opt?: { readonly disconnectGraceMs?: number },\n): PeerConnector {\n const graceMs = opt?.disconnectGraceMs ?? 5000;\n return ({\n polite,\n sendSignal,\n channels = defaultPeerChannels,\n iceServers,\n }) => {\n const pc = new RTCPeerConnection(\n iceServers\n ? {\n ...config,\n iceServers: iceServers.map((server) => ({\n ...server,\n urls:\n typeof server.urls === 'string'\n ? server.urls\n : [...server.urls],\n })),\n }\n : config,\n );\n let makingOffer = false;\n let ignoreOffer = false;\n const goneCbs = new Set<() => void>();\n let finished = false;\n let restartTried = false;\n let grace: ReturnType<typeof setTimeout> | undefined;\n const clearGrace = (): void => {\n if (grace !== undefined) clearTimeout(grace);\n grace = undefined;\n };\n const reportGone = (): void => {\n if (finished) return;\n finished = true;\n clearGrace();\n for (const cb of [...goneCbs]) cb();\n };\n // one ICE restart per connected period; a second failure is the end of the link\n const failed = (): void => {\n if (finished) return;\n if (restartTried) return reportGone();\n restartTried = true;\n pc.restartIce();\n };\n const rejected = (step: string, err: unknown): void => {\n if (finished || pc.signalingState === 'closed') return;\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`,\n err,\n );\n }\n reportGone();\n };\n pc.oniceconnectionstatechange = () => {\n const state = pc.iceConnectionState;\n if (state === 'connected' || state === 'completed') {\n clearGrace();\n restartTried = false;\n } else if (state === 'failed') {\n clearGrace();\n failed();\n } else if (state === 'disconnected' && grace === undefined) {\n grace = setTimeout(() => {\n grace = undefined;\n const now = pc.iceConnectionState;\n if (now === 'disconnected' || now === 'failed') failed();\n }, graceMs);\n }\n };\n pc.onconnectionstatechange = () => {\n if (pc.connectionState === 'closed') reportGone();\n };\n\n const makeChannel = () => {\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n const like: DataChannelLike = {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n };\n return { attach, like };\n };\n\n const made = new Map(channels.map((c) => [c.label, makeChannel()]));\n\n // the impolite side opens every channel; the polite side adopts them by label\n if (!polite) {\n for (const spec of channels) {\n const init: RTCDataChannelInit = {};\n if (spec.ordered !== undefined) init.ordered = spec.ordered;\n if (spec.maxRetransmits !== undefined)\n init.maxRetransmits = spec.maxRetransmits;\n made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));\n }\n } else {\n pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);\n }\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } catch (err) {\n rejected('make an offer', err);\n } finally {\n makingOffer = false;\n }\n };\n\n const byLabel: Record<string, DataChannelLike> = {};\n for (const [label, ch] of made) byLabel[label] = ch.like;\n\n return {\n channel: byLabel[channels[0].label],\n channels: byLabel,\n signal: async (data) => {\n if (pc.signalingState === 'closed') return;\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n try {\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } catch (err) {\n rejected('apply the remote description', err);\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),\n close: () => {\n finished = true;\n clearGrace();\n for (const ch of made.values()) ch.like.close();\n pc.close();\n },\n };\n };\n}\n\n/**\n * A relay connection someone else owns (a live session, say). Peer links ride on it without\n * saying hello, so the links share that connection's origin and room membership.\n */\nexport type SignalingPort = {\n /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */\n members(): readonly string[] | undefined;\n /** ICE servers from the owner's last welcome, if it keeps them. Read after subscribing. */\n iceServers?(): readonly IceServer[] | undefined;\n send(msg: ClientSignalMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n};\n\nexport type PeerLinksOptions = {\n readonly room: string;\n /** This side's origin; also decides the perfect-negotiation role against each remote. */\n readonly origin: string;\n /**\n * A transport factory means the links own their relay connection (hello, reconnect); a\n * {@link SignalingPort} means they ride on one that is already joined.\n */\n readonly signaling: MeshTransportFactory | SignalingPort;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n /**\n * The channels every link carries, first one the default for `send` and `broadcast`.\n * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.\n */\n readonly channels?: readonly PeerChannelSpec[];\n /** Sent in the hello when the links own their connection. */\n readonly policyVersion?: number;\n /**\n * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe\n * before the first link opens. Defaults to `true`.\n */\n readonly autoConnect?: boolean;\n /** How long a link may take to open every channel before it counts as lost. Default 15000. */\n readonly openTimeoutMs?: number;\n /** Backoff bounds for rebuilding a lost link. Defaults 1000 and 30000. */\n readonly retry?: { readonly minMs?: number; readonly maxMs?: number };\n /** Random source for the backoff jitter; tests pass a seeded one. Default Math.random. */\n readonly random?: () => number;\n readonly injector?: Injector;\n};\n\nexport type PeerLinks = {\n /**\n * `live` once the relay has welcomed this side (or, over a port, once it has seen a\n * welcome); back to `connecting` while an owned relay connection is being re-established.\n * Peer links outlive that: they are retired only by their own close or a relay `gone`. Over\n * a port the same holds across the session's socket drops; when the session itself ends, the\n * port reports `gone` for every member and the links are retired with it.\n */\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins whose link has every channel open. */\n readonly peers: Signal<readonly string[]>;\n /** Members whose link was lost at least once since it last opened: waiting to rebuild, or rebuilding. */\n readonly stalled: Signal<readonly string[]>;\n /**\n * Other origins in the room as the relay reports them (welcome, then join and leave). The\n * relay is the authority on who is present; a link can outlive a dead socket for a while.\n */\n readonly members: Signal<readonly string[]>;\n /** Replays current membership synchronously, then reports every change without coalescing. */\n onMembers(cb: (members: readonly string[]) => void): () => void;\n /** The labels every link carries, in the order they were asked for. */\n readonly channels: readonly string[];\n /** Fires when one channel of a link opens; replays channels that are already open. */\n onOpen(cb: (origin: string, channel: string) => void): () => void;\n onMessage(\n cb: (origin: string, frame: string, channel: string) => void,\n ): () => void;\n /**\n * Fires when a link goes away: a channel closed, the connector reported it gone, it did not\n * open in time, or the relay reported the origin gone. A lost link is rebuilt while the relay\n * lists its origin.\n */\n onClose(cb: (origin: string) => void): () => void;\n /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */\n onEnd(cb: () => void): () => void;\n /** Sends on one open channel; a frame for a channel that is not open is dropped. */\n send(origin: string, frame: string, channel?: string): void;\n /** Sends on the channel of every link where it is open. */\n broadcast(frame: string, channel?: string): void;\n /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */\n connect(): void;\n close(): void;\n};\n\ntype Peer = {\n /** This side's instance id for the link, carried in every signal payload it sends. */\n readonly id: string;\n /** The remote side's instance id, bound by the first signal that carries one. */\n remote?: string;\n link: ReturnType<PeerConnector>;\n channels: Map<string, { channel: DataChannelLike; open: boolean }>;\n unsubs: (() => void)[];\n};\n\n/**\n * A signal payload split into its addressing and the connector's part: `link` is the sending\n * instance, `to` the receiving instance it was bound to when it sent (absent until it is).\n */\nconst unwrapSignal = (\n data: unknown,\n): { link?: string; to?: string; payload?: unknown } => {\n if (typeof data !== 'object' || data === null) return { payload: data };\n const { link, to, ...rest } = data as { link?: unknown; to?: unknown };\n if (typeof link !== 'string') return { payload: data };\n return {\n link,\n to: typeof to === 'string' ? to : undefined,\n payload: Object.keys(rest).length ? rest : undefined,\n };\n};\n\n/**\n * The link layer under peer-to-peer consumers: one peer connection per remote origin in the\n * room, set up from relay membership and negotiated over relay `signal` frames. Each link\n * carries the same labelled channels; frames are opaque strings, what they mean is the\n * consumer's business.\n *\n * An origin is one seat: the relay hands a second connection with the same origin the seat\n * and reports it to the room as a plain join. Links tell seats apart by instance, not by\n * order: every link announces a random instance id in its signals and, once it knows the\n * instance across, addresses its signals to it. A signal addressed to an instance this side\n * no longer has is dropped. An unaddressed signal from an instance other than the one linked\n * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed\n * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt\n * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin\n * still take the seat from each other on every reconnect; give each tab its own origin.\n *\n * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is\n * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for\n * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may\n * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild\n * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.\n *\n * No link is built before the welcome of the connection it signals over: joins before it are\n * superseded by the welcome's roster and signals are held and replayed after it, so every link\n * is built with that welcome's ICE servers and never an earlier connection's.\n */\nexport function peerLinks(opt: PeerLinksOptions): PeerLinks {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;\n const labels = specs.map((c) => c.label);\n const primary = labels[0];\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const members = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n const lifecycle = signal(emptyLifecycle);\n // one timer slot per origin: the open timeout or the rebuild timer, never both\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n const openTimeoutMs = opt.openTimeoutMs ?? 15_000;\n const bounds = {\n minMs: opt.retry?.minMs ?? 1000,\n maxMs: opt.retry?.maxMs ?? 30_000,\n };\n const random = opt.random ?? Math.random;\n // the relay's ICE servers from the last welcome; undefined leaves the connector's own\n let iceServers: readonly IceServer[] | undefined;\n const openCbs = new Set<(origin: string, channel: string) => void>();\n const messageCbs = new Set<\n (origin: string, frame: string, channel: string) => void\n >();\n const closeCbs = new Set<(origin: string) => void>();\n const endCbs = new Set<() => void>();\n const memberCbs = new Set<(members: readonly string[]) => void>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let connected = false;\n let closed = false;\n // no link is built before the welcome of the connection it signals over, so every link\n // carries that welcome's ICE servers: joins are ignored and signals held until then\n let welcomed = false;\n let held: Extract<ServerMsg, { t: 'signal' }>[] = [];\n let heldWarned = false;\n // links are told apart by instance, never by order: a random tag plus a counter\n const tag = Math.random().toString(36).slice(2, 10);\n let linkSeq = 0;\n\n const port: SignalingPort | null =\n typeof opt.signaling === 'function' ? null : opt.signaling;\n const sendSignal = (msg: ClientSignalMsg): void => {\n if (port) port.send(msg);\n else transport?.send(msg);\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n for (const cb of [...closeCbs]) cb(origin);\n };\n\n /**\n * Builds the link to `origin`; `remote` is the instance on the other side when the link is\n * built in answer to one of its signals, so everything this side sends is addressed to it.\n */\n const ensurePeer = (origin: string, remote?: string): Peer => {\n const existing = peers.get(origin);\n if (existing) return existing;\n const id = `${tag}.${++linkSeq}`;\n // signals the connector sends while it is still being built wait until the peer is\n // registered, so the remote's synchronous answer finds it instead of building another\n let building: unknown[] | null = [];\n let retired = false;\n const signal = (data: unknown): void => {\n if (retired) return;\n if (building) {\n building.push(data);\n return;\n }\n const stamped =\n typeof data === 'object' && data !== null\n ? {\n ...data,\n link: id,\n ...(p.remote === undefined ? {} : { to: p.remote }),\n }\n : data;\n sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });\n };\n const link = connector({\n remote: origin,\n polite: opt.origin > origin,\n sendSignal: signal,\n channels: specs,\n ...(iceServers ? { iceServers } : {}),\n });\n const p: Peer = {\n id,\n remote,\n link,\n channels: new Map(),\n unsubs: [() => (retired = true)],\n };\n peers.set(origin, p);\n const lost = (): void => {\n if (peers.get(origin) === p) feed({ t: 'lost', origin });\n };\n if (link.onClose) p.unsubs.push(link.onClose(lost));\n const early = building;\n building = null;\n // announce the instance, so a side that still holds a link to an earlier seat of this\n // origin (a takeover the relay reports as a plain join) replaces it\n signal({});\n for (const data of early) signal(data);\n for (const label of labels) {\n const channel =\n link.channels?.[label] ??\n (label === primary ? link.channel : undefined);\n if (!channel) {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`,\n );\n }\n continue;\n }\n const state = { channel, open: false };\n p.channels.set(label, state);\n p.unsubs.push(\n channel.onOpen(() => {\n state.open = true;\n if (\n peers.get(origin) === p &&\n labels.every((l) => p.channels.get(l)?.open)\n ) {\n openPeers.update((set) => new Set(set).add(origin));\n feed({ t: 'opened', origin });\n // a link rebuilt by a takeover opens while its origin is already open to the\n // lifecycle, which then ignores the report: its open timeout ends here all the same\n if (untracked(lifecycle).get(origin)?.state === 'open')\n disarm(origin);\n }\n for (const cb of [...openCbs]) cb(origin, label);\n }),\n channel.onMessage((frame) => {\n for (const cb of [...messageCbs]) cb(origin, frame, label);\n }),\n channel.onClose(lost),\n );\n }\n return p;\n };\n\n const disarm = (origin: string): void => {\n const timer = timers.get(origin);\n if (timer !== undefined) clearTimeout(timer);\n timers.delete(origin);\n };\n\n const arm = (origin: string, ms: number, fire: LifecycleEvent): void => {\n disarm(origin);\n const timer = setTimeout(() => {\n if (timers.get(origin) !== timer) return;\n timers.delete(origin);\n feed(fire);\n }, ms);\n timers.set(origin, timer);\n };\n\n const execute = (f: LifecycleEffect, remote?: string): void => {\n switch (f.t) {\n case 'drop':\n return dropPeer(f.origin);\n case 'disarm':\n return disarm(f.origin);\n }\n if (closed) return;\n switch (f.t) {\n case 'build':\n ensurePeer(f.origin, remote);\n return;\n case 'armOpen':\n return arm(f.origin, openTimeoutMs, { t: 'lost', origin: f.origin });\n case 'armRetry':\n return arm(f.origin, retryDelay(f.attempt, bounds, random), {\n t: 'due',\n origin: f.origin,\n });\n }\n };\n\n /**\n * Steps the lifecycle and runs its effects in order. The new state is stored first, so an\n * event an effect causes on the spot (a link that opens while it is built) steps from it.\n * `remote` addresses the build of a link made in answer to a signal.\n */\n function feed(e: LifecycleEvent, remote?: string): void {\n const { next, effects } = step(untracked(lifecycle), e);\n if (next !== untracked(lifecycle)) lifecycle.set(next);\n for (const f of effects) execute(f, remote);\n }\n\n const setMembers = (origins: readonly string[]): void => {\n const next = new Set(origins);\n members.set(next);\n for (const cb of [...memberCbs]) cb([...next]);\n };\n\n const welcomeMembers = (\n origins: readonly string[],\n ice: readonly IceServer[] | undefined,\n ): void => {\n setMembers(origins);\n iceServers = ice;\n welcomed = true;\n status.set('live');\n feed({ t: 'welcome', members: origins });\n const replay = held;\n held = [];\n for (const msg of replay) {\n if (closed) return;\n handleSignaling(msg);\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (closed || msg.room !== opt.room) return;\n if (!welcomed && msg.t !== 'welcome' && msg.t !== 'reject') {\n // the welcome's roster supersedes joins before it; a leave discards what the origin sent\n if (msg.t === 'signal') {\n if (held.length < HELD_SIGNALS) held.push(msg);\n else if (isDevMode() && !heldWarned) {\n heldWarned = true;\n console.warn(\n `[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`,\n );\n }\n } else if (msg.t === 'member' && msg.gone) {\n held = held.filter((h) => h.from !== msg.origin);\n }\n return;\n }\n switch (msg.t) {\n case 'welcome':\n welcomeMembers(msg.members, msg.ice);\n return;\n case 'member':\n setMembers(\n msg.gone\n ? [...members()].filter((origin) => origin !== msg.origin)\n : [...new Set([...members(), msg.origin])],\n );\n feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });\n return;\n case 'signal': {\n if (!members().has(msg.from)) {\n // the relay routes signals among members only and reports a join before the\n // joiner's first signal; anything else must not become a link that retries forever\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`,\n );\n }\n return;\n }\n const { link, to, payload } = unwrapSignal(msg.data);\n let peer = peers.get(msg.from);\n if (link === undefined || (!peer && to === undefined)) {\n // no link to this member (lost and waiting to rebuild): its announce is the reason\n // to build now, addressed to its instance if stamped\n if (!peer) feed({ t: 'listed', origin: msg.from }, link);\n peer = peers.get(msg.from);\n if (!peer) return;\n } else if (to !== undefined && to !== peer?.id) {\n // addressed to an instance this side no longer has: a retired link's leftovers\n return;\n } else if (!peer) {\n return;\n } else if (peer.remote === undefined) {\n peer.remote = link;\n } else if (peer.remote !== link) {\n if (to === undefined) {\n // a new instance over there that does not know this side yet: a new seat or a\n // restarted link, so this side rebuilds, addressing it, which is what makes the\n // rebuild final: the other side never rebuilds in answer to an addressed signal.\n // It replaces the instance, not a lost link: the lifecycle state stays and only\n // the open timeout moves to the new instance.\n dropPeer(msg.from);\n arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });\n peer = ensurePeer(msg.from, link);\n } else {\n // built for this very instance, so it is the newer end of this link: adopt it\n peer.remote = link;\n }\n }\n if (payload !== undefined) peer.link.signal(payload);\n return;\n }\n case 'reject':\n close();\n return;\n }\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n if (port) {\n const unsub = port.onMessage(handleSignaling);\n if (closed) {\n unsub();\n return;\n }\n signalingUnsubs = [unsub];\n const current = port.members();\n if (current !== undefined) welcomeMembers(current, port.iceServers?.());\n return;\n }\n const t = (opt.signaling as MeshTransportFactory)();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n welcomed = false;\n held = [];\n status.set('connecting');\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n t.send({\n t: 'hello',\n room: opt.room,\n origin: opt.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n });\n };\n\n const connect = (): void => {\n if (connected || closed) return;\n connected = true;\n connectSignaling();\n };\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n held = [];\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n feed({ t: 'close' });\n // a takeover's open timeout on a link the lifecycle already counts open\n for (const origin of [...timers.keys()]) disarm(origin);\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n setMembers([]);\n memberCbs.clear();\n status.set('connecting');\n for (const cb of [...endCbs]) cb();\n endCbs.clear();\n };\n\n const openChannel = (origin: string, label: string) => {\n const state = peers.get(origin)?.channels.get(label);\n return state?.open ? state.channel : null;\n };\n\n injector.get(DestroyRef).onDestroy(close);\n if (opt.autoConnect !== false) connect();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n stalled: computed(() =>\n [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin),\n ),\n members: computed(() => [...members()]),\n onMembers: (cb) => {\n if (!closed) memberCbs.add(cb);\n cb([...members()]);\n return () => memberCbs.delete(cb);\n },\n channels: labels,\n onOpen: (cb) => {\n openCbs.add(cb);\n for (const [origin, peer] of peers) {\n for (const [label, state] of peer.channels) {\n if (state.open) cb(origin, label);\n }\n }\n return () => openCbs.delete(cb);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),\n send: (origin, frame, channel = primary) => {\n openChannel(origin, channel)?.send(frame);\n },\n broadcast: (frame, channel = primary) => {\n for (const origin of peers.keys())\n openChannel(origin, channel)?.send(frame);\n },\n connect,\n close,\n };\n}\n","import {\n inject,\n Injector,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport {\n opSync,\n type DiffOpsOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives/core';\nimport {\n defaultPeerChannels,\n peerLinks,\n type PeerChannelSpec,\n type PeerConnector,\n type PeerLinks,\n} from './peer-links';\nimport type { MeshTransportFactory } from './transport';\n\nexport {\n rtcPeerConnector,\n type DataChannelLike,\n type PeerConnector,\n} from './peer-links';\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /**\n * This replica's origin, its identity in the room; defaults to a random id per instance.\n * One origin is one seat, so never share one between two live instances.\n */\n readonly origin?: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n /**\n * Further channels every link carries beside the mesh's own reliable one, for consumers\n * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.\n */\n readonly channels?: readonly PeerChannelSpec[];\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n /** How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent: as before. */\n readonly emit?: DiffOpsOptions;\n};\n\nexport type WebRtcMeshRef = {\n /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */\n readonly origin: string;\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */\n readonly links: PeerLinks;\n close(): void;\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is strictly covered hydrates from the other's FULL\n * checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n *\n * There is no relay admission here: no sequence, no generation, no refusals. Beside a\n * relay-backed session over the same document a peer channel may hand on only envelopes the\n * relay has sequenced, never a peer's own unacknowledged writes.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const meshChannel = defaultPeerChannels[0];\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n origin: opt.origin,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n emit: opt.emit,\n });\n\n // subscribe before signaling starts: a link can open, and its first frame arrive, while\n // the hello is still being answered\n const links = peerLinks({\n room: opt.room,\n origin: sync.origin,\n signaling: opt.signaling,\n connector: opt.connector,\n channels: [\n meshChannel,\n ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),\n ],\n policyVersion: opt.policyVersion,\n autoConnect: false,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (origin: string, msg: P2PMsg): void => {\n links.send(origin, JSON.stringify(msg));\n };\n\n const handlePeerMsg = (origin: string, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(origin, { t: 'uptodate' });\n else sendTo(origin, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n links.onOpen((origin, channel) => {\n if (channel === meshChannel.label)\n sendTo(origin, { t: 'hello', wm: sync.watermark() });\n });\n links.onMessage((origin, frame, channel) => {\n if (channel !== meshChannel.label) return;\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(origin, msg);\n });\n\n const unsubLocal = sync.subscribe((env) =>\n links.broadcast(JSON.stringify({ t: 'env', env } satisfies P2PMsg)),\n );\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n unsubLocal();\n links.close();\n sync.destroy();\n };\n\n // a relay reject ends the links; the mesh ends with them\n links.onEnd(close);\n links.connect();\n\n return {\n origin: sync.origin,\n status: links.status,\n peers: links.peers,\n links,\n close,\n };\n}\n","import {\n computed,\n DestroyRef,\n effect,\n inject,\n Injector,\n signal,\n untracked,\n type Signal,\n} from '@angular/core';\nimport { throttled } from '@mmstack/primitives/core';\nimport type { PeerChannelSpec, PeerLinks } from './peer-links';\n\n/**\n * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that\n * waits for a retransmit is already stale, and ordering would hold newer frames behind it.\n * Put it in the `channels` of the {@link PeerLinks} the presence rides on.\n */\nexport const presenceChannel: PeerChannelSpec = {\n label: 'mmstack-presence',\n ordered: false,\n maxRetransmits: 0,\n};\n\n/**\n * What goes over the wire. `seq` counts frames sent on one channel of one links object, in\n * send order, and is shared by every sender created on those links; it never restarts while\n * the links live. It orders frames of one link only, and is never compared across links.\n */\nexport type PresenceFrame<T> = {\n readonly seq: number;\n readonly value: T;\n};\n\nexport type RtcPresenceOptions = {\n /** The channel label on the links; defaults to {@link presenceChannel}'s. */\n readonly channel?: string;\n /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */\n readonly throttleMs?: number;\n /**\n * Who is in the room, from the relay. A value is held only for an origin in it: a peer link\n * can outlive the relay membership on a dead socket, so the link is not proof of presence.\n * Subscribe synchronously with the current roster, then report every transition, including\n * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.\n * A sampled signal or an effect cannot preserve these transitions.\n */\n readonly roster: (cb: (members: readonly string[]) => void) => () => void;\n readonly injector?: Injector;\n};\n\nexport type RtcPresenceRef<T> = {\n /** Publishes this side's value; throttled, and the last value of a burst always goes out. */\n set(value: T): void;\n /** The latest value per origin, only for origins in the roster. */\n readonly peers: Signal<ReadonlyMap<string, T>>;\n /** Stops publishing and forgets every held value. The links stay open. */\n close(): void;\n};\n\nconst none = Symbol('none');\n\n// one send counter per links object and channel, shared by every sender created on them\nconst counters = new WeakMap<PeerLinks, Map<string, { seq: number }>>();\nconst counterOf = (links: PeerLinks, label: string): { seq: number } => {\n let byLabel = counters.get(links);\n if (!byLabel) counters.set(links, (byLabel = new Map()));\n let counter = byLabel.get(label);\n if (!counter) byLabel.set(label, (counter = { seq: 0 }));\n return counter;\n};\n\nconst isNum = (x: unknown): x is number =>\n typeof x === 'number' && Number.isFinite(x);\n\n/**\n * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no\n * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the\n * sender's next `set`.\n *\n * Order comes from causality the receiver observes, never from clocks or from numbers chosen\n * by different senders. A value is held only for an origin in the roster, and it is removed\n * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or\n * below it is dropped: one counter stamps every frame sent on that link in send order, so a\n * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a\n * frame of an old link cannot arrive on a new one. An origin that leaves and comes back\n * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives\n * and nobody reads `peers` between leave and rejoin.\n *\n * The counter belongs to the links and the channel, not to this sender, so a sender closed\n * and recreated on the same links carries on where the last one stopped and is heard at\n * once. A new tab or device is a new link, which every receiver already treats as fresh.\n *\n * Nothing is minted while no link carries the channel: a sender alone costs no frames, no\n * numbers and no timers. The gate is the set of links whose presence channel is open, the very\n * set `broadcast` delivers to, so no frame that anyone could receive is withheld.\n *\n * Values travel as JSON.\n */\nexport function rtcPresence<T>(\n links: PeerLinks,\n opt: RtcPresenceOptions,\n): RtcPresenceRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const label = opt.channel ?? presenceChannel.label;\n if (!links.channels.includes(label)) {\n throw new Error(\n `[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`,\n );\n }\n\n const held = new Map<string, { seq: number; value: T }>();\n const version = signal(0);\n const counter = counterOf(links, label);\n let closed = false;\n let roster: ReadonlySet<string> = new Set();\n // origins whose link has this channel open: who a broadcast would reach\n const open = new Set<string>();\n\n const forget = (origin: string): void => {\n if (held.delete(origin)) version.update((v) => v + 1);\n };\n\n const receive = (origin: string, frame: string): void => {\n if (closed) return;\n let msg: PresenceFrame<T>;\n try {\n msg = JSON.parse(frame) as PresenceFrame<T>;\n } catch {\n return;\n }\n if (\n typeof msg !== 'object' ||\n msg === null ||\n !isNum(msg.seq) ||\n !('value' in msg)\n ) {\n return;\n }\n if (!roster.has(origin)) return;\n const prev = held.get(origin);\n if (prev && msg.seq <= prev.seq) return;\n held.set(origin, { seq: msg.seq, value: msg.value });\n version.update((v) => v + 1);\n };\n\n const unsubs = [\n opt.roster((members) => {\n roster = new Set(members);\n for (const origin of held.keys()) if (!roster.has(origin)) forget(origin);\n }),\n links.onMessage((origin, frame, channel) => {\n if (channel === label) receive(origin, frame);\n }),\n // the link is the epoch: a new or lost link starts the origin fresh\n links.onOpen((origin, channel) => {\n if (channel !== label) return;\n forget(origin);\n open.add(origin);\n }),\n links.onClose((origin) => {\n open.delete(origin);\n forget(origin);\n }),\n links.onEnd(() => close()),\n ];\n\n const peers = computed<ReadonlyMap<string, T>>(() => {\n version();\n if (closed) return new Map();\n const out = new Map<string, T>();\n for (const [origin, entry] of held) {\n if (roster.has(origin)) out.set(origin, entry.value);\n }\n return out;\n });\n\n const destroyRef = injector.get(DestroyRef);\n const outgoing = throttled<T | typeof none>(none, {\n ms: opt.throttleMs ?? 33,\n leading: true,\n trailing: true,\n destroyRef,\n });\n const publisher = effect(\n () => {\n const value = outgoing();\n // a link closed since the set: nothing to reach, so nothing is minted\n if (value === none || closed || open.size === 0) return;\n untracked(() =>\n links.broadcast(\n JSON.stringify({\n seq: counter.seq++,\n value,\n } satisfies PresenceFrame<T>),\n label,\n ),\n );\n },\n { injector },\n );\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n publisher.destroy();\n for (const unsub of unsubs.splice(0)) unsub();\n held.clear();\n open.clear();\n version.update((v) => v + 1);\n };\n\n destroyRef.onDestroy(close);\n\n return {\n set: (value) => {\n if (!closed && open.size > 0) outgoing.set(value);\n },\n peers,\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["none"],"mappings":";;;;;AAwDO,MAAM,cAAc,GAAG,OAAwB;IACpD,MAAM,EAAE,IAAI,GAAG,EAAE;IACjB,OAAO,EAAE,IAAI,GAAG,EAAE;IAClB,WAAW,EAAE,IAAI,GAAG,EAAE;AACvB,CAAA,CAAC;AAEF;AACO,MAAM,WAAW,GAAG,CAAC,GAA0B,MAAuB;AAC3E,IAAA,MAAM,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACjF,IAAA,OAAO,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC7C,IAAA,WAAW,EAAE,IAAI,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AACtD,CAAA,CAAC;AAEK,MAAM,eAAe,GAAG,CAAC,CAAkB,MAA6B;AAC7E,IAAA,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IAC1E,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC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SAAA,GAAA,EAAA,SAAA,EAAA,WAAA,EAAA,8BAAA,EAAA,CAAA,EACC,QAAQ,EAAA,CACX;IAED,MAAM,KAAK,GAAG,MAAW;AACvB,QAAA,IAAI,MAAM;YAAE;QACZ,MAAM,GAAG,IAAI;QACb,SAAS,CAAC,OAAO,EAAE;QACnB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC;AAAE,YAAA,KAAK,EAAE;QAC7C,IAAI,CAAC,KAAK,EAAE;QACZ,IAAI,CAAC,KAAK,EAAE;AACZ,QAAA,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC9B,IAAA,CAAC;AAED,IAAA,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC;IAE3B,OAAO;AACL,QAAA,GAAG,EAAE,CAAC,KAAK,KAAI;AACb,YAAA,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,IAAI,GAAG,CAAC;AAAE,gBAAA,QAAQ,CAAC,GAAG,CAAC,KAAK,CAAC;QACnD,CAAC;QACD,KAAK;QACL,KAAK;KACN;AACH;;AC5NA;;AAEG;;;;"}
1
+ {"version":3,"file":"mmstack-mesh.mjs","sources":["../../../../../packages/mesh/client/src/lib/generation.ts","../../../../../packages/mesh/client/src/lib/session-journal.ts","../../../../../packages/mesh/client/src/lib/session.ts","../../../../../packages/mesh/client/src/lib/session-journal-handle.ts","../../../../../packages/mesh/client/src/lib/session-boot.ts","../../../../../packages/mesh/client/src/lib/lock-broker.ts","../../../../../packages/mesh/client/src/lib/mesh-sync.ts","../../../../../packages/mesh/client/src/lib/agent-seat.ts","../../../../../packages/mesh/client/src/lib/transport.ts","../../../../../packages/mesh/client/src/lib/peer-lifecycle.ts","../../../../../packages/mesh/client/src/lib/peer-links.ts","../../../../../packages/mesh/client/src/lib/webrtc-mesh.ts","../../../../../packages/mesh/client/src/lib/rtc-presence.ts","../../../../../packages/mesh/client/src/mmstack-mesh.ts"],"sourcesContent":["import {\n admits,\n createRanges,\n recordAdmission,\n type CoverContext,\n type Dot,\n type GenerationReason,\n type Hlc,\n type Key,\n type OpEnvelope,\n type Ranges,\n type Receipts,\n type RegisterStore,\n type StoreOp,\n type TailPolicy,\n type VersionRange,\n} from '@mmstack/mesh-protocol';\nimport type { Intent } from './session-journal';\n\nexport type { Intent } from './session-journal';\n\n/**\n * The client half of a room generation: the record fields a snapshot welcome carries, the admission\n * evidence the client keeps for its pre-check, and the pure decisions the session takes on them\n * (which welcome to install, what a new generation does with the pending tail, whether a replayed\n * envelope may be sent, when a member is ready for a consensus cut). Nothing here touches a socket,\n * a store or a timer, so a harness can drive the same decisions the session does.\n */\n\n/** The immutable fields of the installed generation, as the client keeps them in its record. */\nexport type InstalledGeneration = {\n readonly instance: string;\n readonly index: number;\n readonly reason: GenerationReason;\n readonly policy: TailPolicy;\n readonly extent: Readonly<Record<string, Readonly<Record<string, Hlc>>>>;\n readonly preCutMax: Readonly<Record<string, Hlc>>;\n /** The seq of the snapshot welcome that installed it (or a later one of the same generation). */\n readonly seq: number;\n};\n\n/**\n * The admission evidence of the installed generation as this client knows it: the welcome's ranges,\n * settled vector and first stamps, then every envelope the client ingests (its own included).\n * A lead or lag against the relay's view only ever yields a refusal the client lands as a conflict.\n */\nexport type ClientAdmission = {\n readonly ranges: Map<string, Ranges>;\n readonly settled: Map<string, Hlc>;\n readonly firstStamps: Map<string, Hlc>;\n};\n\n/** The serializable form of {@link ClientAdmission}. */\nexport type ClientAdmissionRecord = {\n readonly ranges: Readonly<Record<string, readonly VersionRange[]>>;\n readonly settled: Readonly<Record<string, Hlc>>;\n readonly firstStamps: Readonly<Record<string, Hlc>>;\n};\n\nexport const emptyAdmission = (): ClientAdmission => ({\n ranges: new Map(),\n settled: new Map(),\n firstStamps: new Map(),\n});\n\n/** The admission evidence a snapshot welcome carries, as of its seq. */\nexport const admissionOf = (src: ClientAdmissionRecord): ClientAdmission => ({\n ranges: new Map(\n Object.entries(src.ranges).map(([o, r]) => [o, createRanges(r)]),\n ),\n settled: new Map(Object.entries(src.settled)),\n firstStamps: new Map(Object.entries(src.firstStamps)),\n});\n\n/** How one envelope reaches the client's admission evidence: see {@link admitLocal}. */\nexport type LocalAdmission = 'admitted' | 'duplicate' | 'below-max';\n\n/**\n * One envelope reaches this client's view (its own emission, a relay delivery, a replayed or\n * re-applied own write). A version it already holds is a `'duplicate'`. One it does not hold, below\n * its origin's held maximum, is `'below-max'`: on a relay delivery that means the feed broke the\n * origin's order. Neither is recorded. Otherwise the version joins the evidence exactly as the\n * relay records it (`'admitted'`).\n */\nexport function admitLocal(\n a: ClientAdmission,\n env: { readonly origin: string; readonly version: number; readonly hlc: Hlc },\n): LocalAdmission {\n const held = a.ranges.get(env.origin);\n if (held?.has(env.version)) return 'duplicate';\n if (held && env.version < held.max()) return 'below-max';\n recordAdmission(a, env);\n return 'admitted';\n}\n\n/** The context `admits` reads: the installed record's extent and preCutMax, the client's evidence. */\nexport const coverContext = (\n gen: Pick<InstalledGeneration, 'extent' | 'preCutMax'>,\n a: ClientAdmission,\n): CoverContext => ({\n extent: gen.extent,\n preCutMax: gen.preCutMax,\n firstStamp: (origin) => a.firstStamps.get(origin),\n settled: (origin) => a.settled.get(origin),\n});\n\n/**\n * The replay pre-check: every cite of `env` (its own dot excepted) the installed state does not\n * cover, by the same `admits` the relay runs, over the client's register store. An envelope with\n * an uncovered cite is never sent; it is a conflict.\n */\nexport function uncoveredCites(\n store: RegisterStore,\n ctx: CoverContext,\n env: OpEnvelope,\n): { readonly path: readonly Key[]; readonly dot: Dot }[] {\n const out: { path: readonly Key[]; dot: Dot }[] = [];\n for (const op of env.ops) {\n for (const dot of op.cites ?? []) {\n if (\n dot.origin === env.origin &&\n dot.hlc.p === env.hlc.p &&\n dot.hlc.l === env.hlc.l\n )\n continue;\n if (!admits(store, ctx, op.path, dot)) out.push({ path: op.path, dot });\n }\n }\n return out;\n}\n\n/** What the client knows of its installed generation when a snapshot welcome arrives. */\nexport type WelcomeFence = {\n readonly index: number;\n readonly instance: string | undefined;\n /** The seq of the installed snapshot. */\n readonly seq: number;\n /** The highest seq of a relay-delivered envelope of this generation, deduplicated or not. */\n readonly maxSeq: number;\n};\n\n/**\n * Which snapshot welcome installs. A newer generation (higher index) always does. One of the\n * installed generation does when it is not older than the installed snapshot (`stale` otherwise)\n * and not older than relay traffic already delivered (`older-than-traffic`): installing it would\n * replace that traffic with an earlier state. Anything else is stale.\n */\nexport function welcomeVerdict(\n installed: WelcomeFence,\n msg: {\n readonly index: number;\n readonly instance: string;\n readonly seq: number;\n },\n): 'newer' | 'same' | 'stale' | 'older-than-traffic' {\n if (msg.index > installed.index) return 'newer';\n if (msg.instance !== installed.instance || msg.seq < installed.seq)\n return 'stale';\n if (msg.seq < installed.maxSeq) return 'older-than-traffic';\n return 'same';\n}\n\n/** A pending envelope of an earlier generation, as the tail policy reads it. */\ntype Pending = {\n readonly env: Pick<OpEnvelope, 'origin' | 'instance' | 'version'> & {\n readonly hlc?: Hlc;\n readonly ops?: readonly { readonly cites?: readonly Dot[] }[];\n };\n};\n\nconst dotKey = (origin: string, hlc: Hlc): string =>\n `${origin} ${hlc.p} ${hlc.l}`;\n\n/**\n * The replay order of a pending tail: each origin's entries by version, and an entry after every\n * entry of the tail whose dot it cites (a write made after a restart cites the restored tail).\n * Among the entries free to go, the lowest version goes first, then the lower origin. Causality\n * only: no clock is compared across origins.\n */\nfunction causalOrder<T extends Pending>(pending: readonly T[]): T[] {\n const byVersion = [...pending].sort(\n (a, b) =>\n a.env.version - b.env.version || (a.env.origin < b.env.origin ? -1 : 1),\n );\n const at = new Map<string, number>();\n byVersion.forEach((t, i) => {\n if (t.env.hlc) at.set(dotKey(t.env.origin, t.env.hlc), i);\n });\n const before = byVersion.map(() => new Set<number>());\n const lastOf = new Map<string, number>();\n byVersion.forEach((t, i) => {\n const prev = lastOf.get(t.env.origin);\n if (prev !== undefined) before[i].add(prev);\n lastOf.set(t.env.origin, i);\n for (const op of t.env.ops ?? [])\n for (const c of op.cites ?? []) {\n const j = at.get(dotKey(c.origin, c.hlc));\n if (j !== undefined && j !== i) before[i].add(j);\n }\n });\n const done = new Set<number>();\n const out: T[] = [];\n while (out.length < byVersion.length) {\n let next = byVersion.findIndex(\n (_, i) => !done.has(i) && [...before[i]].every((j) => done.has(j)),\n );\n // honest stamps cite only earlier dots, so no cycle; a forged one falls back to version order\n if (next < 0) next = byVersion.findIndex((_, i) => !done.has(i));\n done.add(next);\n out.push(byVersion[next]);\n }\n return out;\n}\n\n/**\n * A new generation's first step with the pending tail: in causal order (each origin's entries by\n * version, an entry after every entry of the tail it cites), an envelope whose version\n * the receipts of its origin hold — in ANY generation — was admitted and is never resent; the rest\n * is kept for the tail policy. Membership is instance-agnostic: a replayed envelope carries the\n * current instance, so the relay receipts it there while the tail entry still names the generation\n * it was authored in, and a crash between the wire and the record would otherwise replay it again\n * after the next cut. An origin's versions never repeat (the counter runs through replay; a restart\n * that loses it mints a new origin), so the version alone identifies the write.\n */\nexport function trimByReceipts<T extends Pending>(\n pending: readonly T[],\n receipts: Receipts,\n): { readonly trimmed: T[]; readonly keep: T[] } {\n const sorted = causalOrder(pending);\n const trimmed: T[] = [];\n const keep: T[] = [];\n for (const t of sorted) {\n if (receiptsHold(receipts, t.env.origin, t.env.version)) trimmed.push(t);\n else keep.push(t);\n }\n return { trimmed, keep };\n}\n\n/** Whether a welcome's receipts name a version of an origin: it was admitted somewhere in the lineage. */\nexport const receiptsHold = (\n receipts: Receipts,\n origin: string,\n version: number,\n): boolean =>\n (receipts[origin] ?? []).some(\n ([from, to]) => from <= version && version <= to,\n );\n\n/**\n * A member's readiness for a consensus cut: it pressed Compact, it is connected, and nothing it\n * wrote is outstanding (its outbox empty, no replay running). A conflict is never outstanding: it\n * is out of the outbox the moment it is classified.\n */\nexport const readyValue = (s: {\n readonly pressed: boolean;\n readonly connected: boolean;\n readonly replaying: boolean;\n readonly outstanding: number;\n}): boolean => s.pressed && s.connected && !s.replaying && s.outstanding === 0;\n\n/**\n * The authored intent of an envelope: its raw op list and one bump flag, what a re-author rebuilds\n * from. The raws are the stamped ops without their expansion clears (a diffed write never emits a\n * `clear` of its own, so every `clear` is one) and without cites and epoch. The envelope bumped when\n * an op's epoch rises above the register baseline at its path as the client held it before the\n * envelope (the relay's own test for a bump).\n */\nexport function intentOf(\n env: OpEnvelope,\n baseline: (path: readonly Key[]) => number,\n): Intent {\n const raws: StoreOp[] = [];\n let bump = false;\n for (const op of env.ops) {\n if ((op.epoch ?? 0) > baseline(op.path)) bump = true;\n if (op.kind === 'clear') continue;\n const raw: Record<string, unknown> = { ...op };\n delete raw['cites'];\n delete raw['epoch'];\n raws.push(raw as StoreOp);\n }\n return { raws, bump };\n}\n","import {\n compareHlc,\n type Hlc,\n type OpEnvelope,\n type StoreOp,\n validateEnvelope,\n} from '@mmstack/primitives/core';\n\n/** The authored intent of an own envelope: its raw ops and one bump flag, what a re-author rebuilds from. */\nexport type Intent = {\n readonly raws: readonly StoreOp[];\n readonly bump: boolean;\n};\n\n/** A register path, as an op names it. */\nexport type JournalPath = readonly (string | number)[];\n\n/** An epoch at a path. */\nexport type PathEpoch = {\n readonly path: JournalPath;\n readonly epoch: number;\n};\n\n/** A room generation as a welcome names it. */\nexport type JournalGeneration = {\n readonly lineage: string;\n readonly instance: string;\n readonly index: number;\n readonly replayBase: number;\n};\n\n/** The generation an own write belongs to: the one the journal held when the write was recorded. */\nexport type JournalBinding = {\n readonly lineage: string;\n readonly instance: string;\n readonly index: number;\n};\n\n/** Every terminal verdict an own write can get. */\nexport const JOURNAL_VERDICTS = [\n 'discarded',\n 'uncovered',\n 'citation',\n 'epoch-bump',\n 'schema',\n 'order',\n 'compacting',\n 'subsumed',\n 'seeded',\n 'fenced',\n 'superseded',\n 'incompatible',\n] as const;\n\n/** A terminal verdict on an own write. */\nexport type JournalVerdict = (typeof JOURNAL_VERDICTS)[number];\n\nconst CONFLICT_VERDICTS: readonly JournalVerdict[] = [\n 'uncovered',\n 'citation',\n 'epoch-bump',\n];\nconst UNSTORED_VERDICTS: readonly JournalVerdict[] = [\n 'discarded',\n 'schema',\n 'order',\n 'compacting',\n 'incompatible',\n];\n\n/** Whether a verdict leaves the write held as a conflict the application answers. */\nexport const isConflictVerdict = (v: JournalVerdict): boolean =>\n CONFLICT_VERDICTS.includes(v);\n\n/** Whether a verdict lists the write among those that were not stored. */\nexport const isUnstoredVerdict = (v: JournalVerdict): boolean =>\n UNSTORED_VERDICTS.includes(v);\n\n/** One fact the client must not lose, as the journal stores it. */\nexport type JournalRecord =\n /** The journal's origin, minted once when the journal is created. */\n | { readonly k: 'born'; readonly origin: string }\n /** An own envelope as minted, with the intent it was stamped from. */\n | { readonly k: 'write'; readonly env: OpEnvelope; readonly intent: Intent }\n /**\n * A seed envelope, the versions of the pending writes it carries, the versions of the refused writes (held\n * conflicts and writes not stored) whose content it carries, and the schema version of the boot that minted it\n * (absent reads as 0).\n */\n | {\n readonly k: 'seed';\n readonly env: OpEnvelope;\n readonly carried: readonly number[];\n readonly conflicts: readonly number[];\n readonly schema?: number;\n }\n /**\n * An installed or bound generation. `evidence` is what an installed snapshot holds of the client's own writes:\n * present for a snapshot install, empty for an empty welcome, absent for a delta or an up-to-date welcome.\n */\n | {\n readonly k: 'adopted';\n readonly gen: JournalGeneration;\n readonly evidence?: readonly PathEpoch[];\n }\n /** An own write the relay admitted; `receipt` when a welcome's receipts named it. */\n | {\n readonly k: 'acked';\n readonly origin: string;\n readonly version: number;\n readonly receipt?: true;\n }\n /** A terminal verdict on an own write. */\n | {\n readonly k: 'judged';\n readonly origin: string;\n readonly version: number;\n readonly verdict: JournalVerdict;\n }\n /** The application's answer to a held conflict, with the version of the replacement write when it re-authored. */\n | {\n readonly k: 'answered';\n readonly origin: string;\n readonly version: number;\n readonly how: 'discard' | 'reauthor';\n readonly replacement: number | null;\n }\n /** The application dismissed a write that was not stored. */\n | {\n readonly k: 'reported';\n readonly origin: string;\n readonly version: number;\n readonly verdict: JournalVerdict;\n };\n\n/**\n * An own write the state still holds: pending (no verdict), held as a conflict, or not stored and not dismissed.\n * `intent` is null for a seed; `bind` is null until the first generation is adopted.\n */\nexport type JournalEntry = {\n readonly env: OpEnvelope;\n readonly intent: Intent | null;\n readonly bind: JournalBinding | null;\n readonly verdict: JournalVerdict | null;\n};\n\n/**\n * The pending seed: its version, what it carries, and the schema version it was minted with. `conflicts` lists the\n * refused writes whose content it carries that the state still holds with their verdict.\n */\nexport type JournalSeed = {\n readonly version: number;\n readonly carried: readonly number[];\n readonly conflicts: readonly number[];\n readonly schema: number;\n};\n\n/**\n * A seed the relay refused whose fate is not decided yet: the pending writes it parked and the refused writes it\n * carried that the state still holds with their verdict. Every own write recorded until the next adoption joins\n * what it parked.\n */\nexport type JournalLostSeed = {\n readonly version: number;\n readonly parked: readonly number[];\n readonly conflicts: readonly number[];\n};\n\n/**\n * What the client knows about its own writes, as plain JSON data. It holds no settled write: an acknowledged write\n * leaves it at once, a judged one once nothing still needs it.\n */\nexport type JournalState = {\n readonly origin: string | null;\n /** The highest version of any own write or seed recorded. */\n readonly versionHigh: number;\n /** The highest stamp of any own write or seed recorded. */\n readonly clockHigh: Hlc | null;\n readonly gen: JournalGeneration | null;\n /** Whether the last adoption changed the generation. */\n readonly changed: boolean;\n /** What the installed snapshot of the current generation held of the client's own writes. */\n readonly evidence: readonly PathEpoch[];\n /** Per path, the highest epoch of the acknowledged own writes that count toward the floor. */\n readonly settled: readonly PathEpoch[];\n /** Own writes in the order they were recorded. */\n readonly entries: readonly JournalEntry[];\n /** The pending writes a seed carries: they count toward no floor. */\n readonly carried: readonly number[];\n readonly seed: JournalSeed | null;\n readonly lost: JournalLostSeed | null;\n};\n\n/** The state of a journal that holds no record. */\nexport const INITIAL_JOURNAL_STATE: JournalState = {\n origin: null,\n versionHigh: 0,\n clockHigh: null,\n gen: null,\n changed: false,\n evidence: [],\n settled: [],\n entries: [],\n carried: [],\n seed: null,\n lost: null,\n};\n\n// one register per path: a numeric segment and its string form are one path\nconst pathKey = (path: JournalPath): string =>\n path.map(String).join(String.fromCharCode(0x1f));\n\nconst raise = (\n xs: readonly PathEpoch[],\n path: JournalPath,\n epoch: number,\n): readonly PathEpoch[] => {\n const key = pathKey(path);\n const old = xs.find((x) => pathKey(x.path) === key);\n if (old ? old.epoch >= epoch : epoch <= 0) return xs;\n return [...xs.filter((x) => pathKey(x.path) !== key), { path, epoch }];\n};\n\nconst bindingOf = (g: JournalGeneration | null): JournalBinding | null =>\n g && { lineage: g.lineage, instance: g.instance, index: g.index };\n\nconst higherClock = (a: Hlc | null, b: Hlc): Hlc =>\n a && compareHlc(a, b) >= 0 ? a : { p: b.p, l: b.l };\n\nconst indexOf = (s: JournalState, origin: string, version: number): number =>\n origin === s.origin\n ? s.entries.findIndex((e) => e.env.version === version)\n : -1;\n\nconst pendingSet = (s: JournalState): Set<number> =>\n new Set(\n s.entries.filter((e) => e.verdict === null).map((e) => e.env.version),\n );\n\nfunction parkedVersions(s: JournalState): number[] {\n const seed = s.seed;\n if (!seed) return [];\n const at = s.entries.findIndex((e) => e.env.version === seed.version);\n const carried = new Set(seed.carried);\n return s.entries\n .filter(\n (e, i) =>\n e.verdict === null &&\n (carried.has(e.env.version) || (at >= 0 && i > at)),\n )\n .map((e) => e.env.version);\n}\n\nfunction place(s: JournalState, r: JournalRecord & { env: OpEnvelope }): void {\n const what = `a ${r.k} record of origin ${JSON.stringify(r.env.origin)} version ${r.env.version}`;\n const why =\n s.origin === null\n ? 'the journal has no origin yet'\n : r.env.origin !== s.origin\n ? `the journal's origin is ${JSON.stringify(s.origin)}`\n : s.entries.some((e) => e.env.version === r.env.version)\n ? 'the journal already holds a write of that version'\n : r.k === 'seed' && s.seed !== null\n ? `the seed of version ${s.seed.version} is still pending`\n : null;\n if (why) throw new Error(`[@mmstack/mesh] cannot fold ${what}: ${why}`);\n}\n\nfunction recorded(\n s: JournalState,\n env: OpEnvelope,\n intent: Intent | null,\n): JournalState {\n return {\n ...s,\n versionHigh: Math.max(s.versionHigh, env.version),\n clockHigh: higherClock(s.clockHigh, env.hlc),\n entries: [\n ...s.entries,\n { env, intent, bind: bindingOf(s.gen), verdict: null },\n ],\n };\n}\n\nfunction step(s: JournalState, r: JournalRecord): JournalState {\n switch (r.k) {\n case 'born':\n return s.origin === null ? { ...s, origin: r.origin } : s;\n case 'write': {\n place(s, r);\n const out = recorded(s, r.env, r.intent);\n return s.lost\n ? {\n ...out,\n lost: { ...s.lost, parked: [...s.lost.parked, r.env.version] },\n }\n : out;\n }\n case 'seed': {\n place(s, r);\n const out = recorded(s, r.env, null);\n return {\n ...out,\n carried: [\n ...s.carried,\n ...r.carried.filter((v) => !s.carried.includes(v)),\n ],\n seed: {\n version: r.env.version,\n carried: [...r.carried],\n conflicts: [...r.conflicts],\n schema: r.schema ?? 0,\n },\n lost: null,\n };\n }\n case 'adopted': {\n const changed = s.gen === null || s.gen.instance !== r.gen.instance;\n const gen = { ...r.gen };\n const bind = bindingOf(gen);\n return {\n ...s,\n gen,\n changed,\n evidence: changed\n ? (r.evidence ?? []).map((x) => ({ ...x }))\n : s.evidence,\n settled: changed ? [] : s.settled,\n entries: s.entries.map((e) => (e.bind === null ? { ...e, bind } : e)),\n lost: null,\n };\n }\n case 'acked': {\n const i = indexOf(s, r.origin, r.version);\n const e = i < 0 ? undefined : s.entries[i];\n if (!e || e.verdict !== null) return s;\n const isSeed = s.seed?.version === r.version;\n const counts =\n !isSeed &&\n !s.carried.includes(r.version) &&\n !(r.receipt === true && s.changed);\n return {\n ...s,\n entries: s.entries.filter((_, j) => j !== i),\n settled: counts\n ? e.env.ops.reduce(\n (acc, op) => raise(acc, op.path, op.epoch),\n s.settled,\n )\n : s.settled,\n seed: isSeed ? null : s.seed,\n };\n }\n case 'judged': {\n const i = indexOf(s, r.origin, r.version);\n const e = i < 0 ? undefined : s.entries[i];\n if (!e) return s;\n if (e.env.seed && isConflictVerdict(r.verdict))\n throw new Error(\n `[@mmstack/mesh] cannot fold a judged record of origin ${JSON.stringify(r.origin)} version ${r.version}: a seed is never judged ${JSON.stringify(r.verdict)}`,\n );\n const out: JournalState = {\n ...s,\n entries: s.entries.map((x, j) =>\n j === i ? { ...x, verdict: r.verdict } : x,\n ),\n };\n if (e.verdict !== null || s.seed?.version !== r.version) return out;\n const lostNow = r.verdict === 'seeded' || r.verdict === 'order';\n return {\n ...out,\n seed: null,\n lost: lostNow\n ? {\n version: r.version,\n parked: parkedVersions(s).filter((v) => v !== r.version),\n conflicts: [...s.seed.conflicts],\n }\n : out.lost,\n };\n }\n case 'answered': {\n const i = indexOf(s, r.origin, r.version);\n const v = i < 0 ? null : s.entries[i].verdict;\n if (v === null || !isConflictVerdict(v)) return s;\n return { ...s, entries: s.entries.filter((_, j) => j !== i) };\n }\n case 'reported': {\n const i = indexOf(s, r.origin, r.version);\n const e = i < 0 ? undefined : s.entries[i];\n if (\n !e ||\n e.verdict !== r.verdict ||\n !isUnstoredVerdict(r.verdict) ||\n e.env.seed\n )\n return s;\n return { ...s, entries: s.entries.filter((_, j) => j !== i) };\n }\n }\n}\n\nconst kept = (e: JournalEntry): boolean =>\n e.verdict === null ||\n isConflictVerdict(e.verdict) ||\n (isUnstoredVerdict(e.verdict) && !e.env.seed);\n\nfunction compact(s: JournalState): JournalState {\n const entries = s.entries.every(kept) ? s.entries : s.entries.filter(kept);\n const pending = pendingSet({ ...s, entries });\n const refused = new Set(\n entries\n .filter(\n (e) =>\n e.verdict !== null &&\n !e.env.seed &&\n (isConflictVerdict(e.verdict) || isUnstoredVerdict(e.verdict)),\n )\n .map((e) => e.env.version),\n );\n const seed = s.seed && pending.has(s.seed.version) ? s.seed : null;\n return {\n ...s,\n entries,\n carried: s.carried.filter((v) => pending.has(v)),\n seed: seed && {\n ...seed,\n carried: seed.carried.filter((v) => pending.has(v)),\n conflicts: seed.conflicts.filter((v) => refused.has(v)),\n },\n lost: s.lost && {\n ...s.lost,\n parked: s.lost.parked.filter((v) => pending.has(v)),\n conflicts: s.lost.conflicts.filter((v) => refused.has(v)),\n },\n };\n}\n\n/**\n * The journal's fold: the state after one more record. Pure: it reads only its arguments and changes neither.\n *\n * Throws an `Error` naming the record for a record that holds an own envelope and cannot be placed: a `write` or\n * `seed` before `born`, of another origin, or with a version the state already holds, and a `seed` while a seed\n * is pending; also for a `judged` that gives a seed a conflict verdict. A second `born`, and a settling record the\n * state cannot place (an `acked` for a write that is not pending, an `answered` for a write not held as a\n * conflict, a `reported` with no matching unstored verdict, a `judged` for a write it does not hold), change\n * nothing.\n */\nexport function foldJournal(\n state: JournalState,\n record: JournalRecord,\n): JournalState {\n return compact(step(state, record));\n}\n\n// ---------------------------------------------------------------- readers\n\n/** The pending own envelopes, in the order they were recorded. */\nexport const pendingEnvelopes = (s: JournalState): OpEnvelope[] =>\n s.entries.filter((e) => e.verdict === null).map((e) => e.env);\n\n/** Whether an own write is pending: recorded, and neither acknowledged nor judged. */\nexport const isPendingWrite = (\n s: JournalState,\n origin: string,\n version: number,\n): boolean => {\n const i = indexOf(s, origin, version);\n return i >= 0 && s.entries[i].verdict === null;\n};\n\n/** The versions a pending seed keeps out of the send queue: what it carries and the writes recorded after it. */\nexport const parkedBySeed = (s: JournalState): number[] => parkedVersions(s);\n\n/** The pending writes a refused seed parked whose fate is not decided yet. */\nexport const lostParked = (s: JournalState): number[] => {\n const pending = pendingSet(s);\n return (s.lost?.parked ?? []).filter((v) => pending.has(v));\n};\n\n/** The pending seed's envelope, what it carries, and its schema version; null when no seed is pending. */\nexport function pendingSeed(s: JournalState): {\n readonly env: OpEnvelope;\n readonly carried: readonly number[];\n readonly conflicts: readonly number[];\n readonly schema: number;\n} | null {\n const seed = s.seed;\n if (!seed) return null;\n const e = s.entries.find((x) => x.env.version === seed.version);\n return e\n ? {\n env: e.env,\n carried: seed.carried,\n conflicts: seed.conflicts,\n schema: seed.schema,\n }\n : null;\n}\n\n/** The refused seed whose fate is not decided yet, with the pending writes it parked and the conflicts it carried. */\nexport const lostSeed = (s: JournalState): JournalLostSeed | null =>\n s.lost && { ...s.lost, parked: lostParked(s) };\n\n/**\n * The pending own envelopes the send queue may take, in the order they were recorded: bound to a generation, and\n * not parked by a pending seed or behind a refused one.\n */\nexport function sendQueue(s: JournalState): OpEnvelope[] {\n if (s.gen === null) return [];\n const out = new Set([...parkedVersions(s), ...lostParked(s)]);\n return s.entries\n .filter(\n (e) => e.verdict === null && e.bind !== null && !out.has(e.env.version),\n )\n .map((e) => e.env);\n}\n\n/** A write the state holds with its verdict. */\nexport type JournalJudgedWrite = {\n readonly env: OpEnvelope;\n readonly intent: Intent | null;\n readonly verdict: JournalVerdict;\n};\n\n/** The held conflicts, in the order the writes were recorded. */\nexport const heldConflicts = (s: JournalState): JournalJudgedWrite[] =>\n s.entries.flatMap((e) =>\n e.verdict !== null && isConflictVerdict(e.verdict)\n ? [{ env: e.env, intent: e.intent, verdict: e.verdict }]\n : [],\n );\n\n/** The own writes that were not stored and not dismissed, in the order the writes were recorded. */\nexport const unstoredWrites = (s: JournalState): JournalJudgedWrite[] =>\n s.entries.flatMap((e) =>\n e.verdict !== null && isUnstoredVerdict(e.verdict) && !e.env.seed\n ? [{ env: e.env, intent: e.intent, verdict: e.verdict }]\n : [],\n );\n\n/**\n * The lowest epoch a new own op at a path may take: the highest of what the installed snapshot held of the\n * client's own writes there, the acknowledged own writes that count, and every op there of the pending writes no\n * seed carries; 0 where there is none.\n */\nexport function floorAt(s: JournalState, path: JournalPath): number {\n const key = pathKey(path);\n const carried = new Set(s.carried);\n let floor = 0;\n for (const x of [...s.evidence, ...s.settled])\n if (x.epoch > floor && pathKey(x.path) === key) floor = x.epoch;\n for (const e of s.entries) {\n if (e.verdict !== null || carried.has(e.env.version)) continue;\n for (const op of e.env.ops)\n if (op.epoch > floor && pathKey(op.path) === key) floor = op.epoch;\n }\n return floor;\n}\n\n/** The floor function of a state, in the form an engine takes it. */\nexport const emissionFloorOf =\n (s: JournalState) =>\n (path: JournalPath): number =>\n floorAt(s, path);\n\n/**\n * What an engine is restored with after a reboot: the pending own envelopes in the order they were recorded (with\n * a pending seed, the seed and the writes recorded after it only), the version high-water and the clock high-water.\n */\nexport function restoreInput(s: JournalState): {\n readonly envs: readonly OpEnvelope[];\n readonly highWater: number;\n readonly clock: Hlc | undefined;\n} {\n const pending = s.entries.filter((e) => e.verdict === null);\n const at = s.seed\n ? pending.findIndex((e) => e.env.version === s.seed?.version)\n : -1;\n return {\n envs: pending.slice(Math.max(at, 0)).map((e) => e.env),\n highWater: s.versionHigh,\n clock: s.clockHigh ?? undefined,\n };\n}\n\n// ---------------------------------------------------------------- validators\n\ntype Obj = Record<string, unknown>;\n\nconst isObj = (v: unknown): v is Obj =>\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n (Object.getPrototypeOf(v) === Object.prototype ||\n Object.getPrototypeOf(v) === null);\n\nfunction hasKeys(\n v: Obj,\n required: readonly string[],\n optional: readonly string[] = [],\n): boolean {\n const keys = Object.keys(v);\n return (\n required.every((k) => k in v && v[k] !== undefined) &&\n keys.every(\n (k) =>\n required.includes(k) || (optional.includes(k) && v[k] !== undefined),\n )\n );\n}\n\nconst isNat = (v: unknown): v is number =>\n typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;\nconst isVersion = (v: unknown): v is number => isNat(v) && v > 0;\nconst isEpoch = (v: unknown): v is number =>\n typeof v === 'number' && Number.isFinite(v) && v >= 0;\nconst isText = (v: unknown): v is string => typeof v === 'string';\nconst isId = (v: unknown): v is string => typeof v === 'string' && v !== '';\nconst isVersions = (v: unknown): v is number[] =>\n Array.isArray(v) && v.every(isVersion);\nconst isSegment = (v: unknown): boolean => typeof v === 'string' || isNat(v);\nconst isPath = (v: unknown): v is JournalPath =>\n Array.isArray(v) && v.every(isSegment);\nconst isVerdict = (v: unknown): v is JournalVerdict =>\n (JOURNAL_VERDICTS as readonly unknown[]).includes(v);\nconst isHlc = (v: unknown): v is Hlc =>\n isObj(v) &&\n hasKeys(v, ['p', 'l']) &&\n Number.isFinite(v['p']) &&\n Number.isFinite(v['l']);\n\nconst isPathEpoch = (v: unknown): v is PathEpoch =>\n isObj(v) &&\n hasKeys(v, ['path', 'epoch']) &&\n isPath(v['path']) &&\n isEpoch(v['epoch']);\nconst isPathEpochs = (v: unknown): v is PathEpoch[] =>\n Array.isArray(v) && v.every(isPathEpoch);\n\nconst isGeneration = (v: unknown): v is JournalGeneration =>\n isObj(v) &&\n hasKeys(v, ['lineage', 'instance', 'index', 'replayBase']) &&\n isText(v['lineage']) &&\n isText(v['instance']) &&\n isNat(v['index']) &&\n isNat(v['replayBase']);\n\nconst isBinding = (v: unknown): v is JournalBinding =>\n isObj(v) &&\n hasKeys(v, ['lineage', 'instance', 'index']) &&\n isText(v['lineage']) &&\n isText(v['instance']) &&\n isNat(v['index']);\n\nconst isRawOp = (v: unknown): boolean =>\n isObj(v) &&\n (v['kind'] === 'set' || v['kind'] === 'delete') &&\n isPath(v['path']);\n\nconst isIntent = (v: unknown): v is Intent =>\n isObj(v) &&\n hasKeys(v, ['raws', 'bump']) &&\n Array.isArray(v['raws']) &&\n v['raws'].every(isRawOp) &&\n typeof v['bump'] === 'boolean';\n\nfunction isEnvelope(v: unknown, seed: boolean): v is OpEnvelope {\n if (!isObj(v)) return false;\n const env = v as unknown as OpEnvelope;\n return (\n validateEnvelope(env) === null &&\n isNat(v['proto']) &&\n isNat(v['policyVersion']) &&\n env.ops.every((op) => isEpoch(op.epoch)) &&\n (seed ? env.seed === true : !('seed' in v))\n );\n}\n\nconst isKeyed = (v: Obj): boolean =>\n isId(v['origin']) && isVersion(v['version']);\n\n/** Whether a value is a record this version of the client wrote, read strictly. */\nexport function isJournalRecord(value: unknown): value is JournalRecord {\n if (!isObj(value)) return false;\n const v = value;\n switch (v['k']) {\n case 'born':\n return hasKeys(v, ['k', 'origin']) && isId(v['origin']);\n case 'write':\n return (\n hasKeys(v, ['k', 'env', 'intent']) &&\n isEnvelope(v['env'], false) &&\n isIntent(v['intent'])\n );\n case 'seed':\n return (\n hasKeys(v, ['k', 'env', 'carried', 'conflicts'], ['schema']) &&\n isEnvelope(v['env'], true) &&\n isVersions(v['carried']) &&\n isVersions(v['conflicts']) &&\n (v['schema'] === undefined || isNat(v['schema']))\n );\n case 'adopted':\n return (\n hasKeys(v, ['k', 'gen'], ['evidence']) &&\n isGeneration(v['gen']) &&\n (v['evidence'] === undefined || isPathEpochs(v['evidence']))\n );\n case 'acked':\n return (\n hasKeys(v, ['k', 'origin', 'version'], ['receipt']) &&\n isKeyed(v) &&\n (v['receipt'] === undefined || v['receipt'] === true)\n );\n case 'judged':\n case 'reported':\n return (\n hasKeys(v, ['k', 'origin', 'version', 'verdict']) &&\n isKeyed(v) &&\n isVerdict(v['verdict'])\n );\n case 'answered':\n return (\n hasKeys(v, ['k', 'origin', 'version', 'how', 'replacement']) &&\n isKeyed(v) &&\n ((v['how'] === 'discard' && v['replacement'] === null) ||\n (v['how'] === 'reauthor' && isVersion(v['replacement'])))\n );\n default:\n return false;\n }\n}\n\nconst isEntry = (v: unknown): v is JournalEntry => {\n if (!isObj(v) || !hasKeys(v, ['env', 'intent', 'bind', 'verdict'], [])) {\n return false;\n }\n const seed = isObj(v['env']) && v['env']['seed'] === true;\n return (\n isEnvelope(v['env'], seed) &&\n (seed ? v['intent'] === null : isIntent(v['intent'])) &&\n (v['bind'] === null || isBinding(v['bind'])) &&\n (v['verdict'] === null || isVerdict(v['verdict']))\n );\n};\n\nconst STATE_KEYS = [\n 'origin',\n 'versionHigh',\n 'clockHigh',\n 'gen',\n 'changed',\n 'evidence',\n 'settled',\n 'entries',\n 'carried',\n 'seed',\n 'lost',\n];\n\n/** Whether a value is a state this version of the client folded, read strictly. */\nexport function isJournalState(value: unknown): value is JournalState {\n if (!isObj(value)) return false;\n const v = value;\n if (!hasKeys(v, STATE_KEYS)) return false;\n const seed = v['seed'];\n const lost = v['lost'];\n return (\n (v['origin'] === null || isId(v['origin'])) &&\n isNat(v['versionHigh']) &&\n (v['clockHigh'] === null || isHlc(v['clockHigh'])) &&\n (v['gen'] === null || isGeneration(v['gen'])) &&\n typeof v['changed'] === 'boolean' &&\n isPathEpochs(v['evidence']) &&\n isPathEpochs(v['settled']) &&\n Array.isArray(v['entries']) &&\n v['entries'].every(isEntry) &&\n isVersions(v['carried']) &&\n (seed === null ||\n (isObj(seed) &&\n hasKeys(seed, ['version', 'carried', 'conflicts', 'schema']) &&\n isVersion(seed['version']) &&\n isVersions(seed['carried']) &&\n isVersions(seed['conflicts']) &&\n isNat(seed['schema']))) &&\n (lost === null ||\n (isObj(lost) &&\n hasKeys(lost, ['version', 'parked', 'conflicts']) &&\n isVersion(lost['version']) &&\n isVersions(lost['parked']) &&\n isVersions(lost['conflicts'])))\n );\n}\n","import { isDevMode } from '@angular/core';\nimport {\n checkEnvelope,\n createRegisterStore,\n MESH_DIRECT_VERSION,\n MESH_PROTO_VERSION,\n type ClientMsg,\n type ClientSignalMsg,\n type DropMsg,\n type OpPolicy,\n type PolicyViolation,\n type PresenceState,\n type PrincipalCtx,\n type RegisterCheckpoint,\n type RegisterStore,\n type SeqEnvelope,\n type ServerDirectMsg,\n type ServerMsg,\n type WelcomeMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createConvergingApply,\n OP_PROTO_VERSION,\n ownEpochs,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n validateEnvelope,\n validateOps,\n} from '@mmstack/primitives/core';\nimport {\n admissionOf,\n admitLocal,\n coverContext,\n emptyAdmission,\n intentOf,\n readyValue,\n receiptsHold,\n trimByReceipts,\n uncoveredCites,\n welcomeVerdict,\n type ClientAdmission,\n type InstalledGeneration,\n} from './generation';\nimport {\n heldConflicts,\n isConflictVerdict,\n isPendingWrite,\n isUnstoredVerdict,\n lostParked,\n parkedBySeed,\n pendingEnvelopes,\n sendQueue,\n unstoredWrites,\n type Intent,\n type JournalBinding,\n type JournalEntry,\n type JournalRecord,\n type JournalSeed,\n type JournalState,\n type JournalVerdict,\n} from './session-journal';\nimport type { SessionJournal } from './session-journal-handle';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\nexport type { Intent } from './session-journal';\n\n/**\n * Why a write is a conflict: its replay into a new generation cites something the generation does\n * not hold (`'uncovered'`, never sent), or the relay refused it — a cite it does not cover\n * (`'citation'`) or an epoch raised without the authority to (`'epoch-bump'`).\n */\nexport type ConflictCause = 'uncovered' | 'citation' | 'epoch-bump';\n\n/**\n * A write that will never be admitted as it stands. Its local effect is retracted (a replay that\n * failed its pre-check is never applied; a refused write is dropped by the snapshot that follows).\n * The two verbs are the whole surface: `discard()` lets it go, `reauthor()` writes its raw ops again\n * as a new write citing the current state. Neither can submit the original envelope. A conflict is\n * listed once its verdict is stored, and stays listed across reboots until it is answered.\n */\nexport type MeshConflict = {\n /** The envelope as it was authored (its values, cites and epoch). */\n readonly env: OpEnvelope;\n readonly intent: Intent;\n readonly cause: ConflictCause;\n /** Let the write go. Nothing happens once the session has ended. */\n discard(): void;\n /**\n * Write the raw ops again as a new write; false when the shell cannot write (no `reauthor`).\n * Also false when the conflict's ops cannot be written again as one write (a path twice, or an\n * op under another op's path that is not an earlier set of a plain record); the conflict then\n * stays, so it can still be discarded. Also false once the session has ended (closed or\n * ejected): nothing is written and the conflict stays held. Also false inside\n * {@link MeshSession.recordTogether}, with the same outcome.\n * `true` means the write was emitted, not that it shows: one whose parent is gone by now, or\n * that loses its fold, leaves the store as it was. The answer and the new write are stored\n * together: after a crash either both are there or neither is. A write made before the call is\n * not part of them: it is recorded on its own, first. False when the re-author emitted nothing.\n */\n reauthor(): boolean;\n};\n\n/**\n * Why an own write was not stored: `'generation'` (written in a room generation a cut or a lost\n * room creation closed), `'schema'` (a data shape older than the room's), `'order'` (a version below\n * this origin's admitted maximum that was never admitted: a second writer on one origin),\n * `'compacting'` (a host refused it while this client was declared ready for a cut) or\n * `'incompatible'` (a restored write this client can no longer send).\n */\nexport type UnstoredReason =\n | 'generation'\n | 'schema'\n | 'order'\n | 'compacting'\n | 'incompatible';\n\n/**\n * An own write that is not in the room and never will be, listed until the application dismisses it.\n * It is listed once its verdict is stored, and again after a reboot until its dismissal is stored.\n */\nexport type UnstoredWrite = {\n /** The envelope as it was authored: its values, so the application can offer to write them again. */\n readonly env: OpEnvelope;\n readonly intent: Intent;\n readonly reason: UnstoredReason;\n /** Remove the entry; it leaves the list at once. Nothing happens once the session has ended. */\n dismiss(): void;\n};\n\n/** The room's compaction state, as the relay last announced it. */\nexport type CompactionState = {\n /** Droppable tombstones counted against the budget. */\n readonly count: number;\n /** The hard budget, 0 when the room arms none. */\n readonly budget: number;\n /** Origins of the members currently declared ready for a consensus cut. */\n readonly ready: readonly string[];\n};\n\n/** The room generation the client installed, as its snapshot welcome named it. */\nexport type GenerationState = Pick<\n InstalledGeneration,\n 'instance' | 'index' | 'reason' | 'policy'\n>;\n\nexport type MeshStatus =\n | 'connecting'\n /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */\n | 'waiting'\n | 'live'\n | 'reconnecting'\n | 'ejected'\n | 'closed';\n\n/** A `direct` frame as a seat or a synced store hands it over: `from` is the sender's origin. */\nexport type MeshDirect = {\n readonly from: string;\n readonly v: number;\n readonly data: unknown;\n};\n\n/**\n * Hands `msg` to every listener; a throwing listener never interrupts the session or the others.\n * @internal\n */\nexport const deliverDirect = (\n listeners: ReadonlySet<(msg: MeshDirect) => void>,\n msg: ServerDirectMsg,\n): void => {\n const out: MeshDirect = { from: msg.from, v: msg.v, data: msg.data };\n for (const cb of [...listeners]) {\n try {\n cb(out);\n } catch {\n // a consumer's failure stays its own\n }\n }\n};\n\n/** One sequenced remote envelope's ops, attributed to the writer that made them. */\nexport type RemoteBatch = {\n /** The relay's total-order stamp for this batch. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Environment callbacks a session shell provides. All are optional except `onStatus`; the\n * session never touches signals, timers beyond `schedule`, storage, or the DOM itself. None is\n * called while a clear runs or once the session has ended, except by the ending itself. What a hook\n * throws is handed to `onCallbackError` and changes nothing; what that one throws is dropped. A\n * hook does not write through the engine before it returns: a write it makes that way while a\n * snapshot installs is recorded and sent, and missing from the document until the next snapshot.\n */\nexport type MeshSessionHooks = {\n onStatus(status: MeshStatus, reason?: string): void;\n /** The current op engine's origin, published immediately before each hello. */\n onOrigin?(origin: string): void;\n /** Relay membership, independent of presence; undefined while disconnected or before welcome. */\n onMembers?(members: readonly string[] | undefined): void;\n /**\n * A room message after the session has processed it, for consumers sharing its connection.\n * `direct` frames never pass here; they go to {@link MeshSessionHooks.onDirect} only.\n */\n onMessage?(msg: ServerMsg): void;\n /**\n * A `direct` frame addressed to this session, in the frame version this side speaks; any other\n * version is refused unread. One that arrives before the current connection's welcome is held\n * (up to 256) and handed over right after it, unless its sender leaves first.\n */\n onDirect?(msg: ServerDirectMsg): void;\n /** A welcome or envelope arrived — the shell's \"last synced\" moment. */\n onSynced?(): void;\n /** The presence roster changed (welcome replace, join/leave, teardown clear). */\n onPeers?(peers: ReadonlyMap<string, PresenceState>): void;\n /** A remote (non-own) envelope was ingested, in seq order. */\n onRemote?(batch: RemoteBatch): void;\n /**\n * Seq continuity broke: a snapshot welcome (or a relay instance change) established state\n * without delivering the individual envelopes in between. Any consumer deriving from the\n * `onRemote` stream must rebuild from current state at this seq; appending across a resync\n * would silently skip history.\n */\n onResync?(seq: number): void;\n /**\n * The session's own writes may read differently now: `conflicts()`, `unstored()`, `hasUnacked()`,\n * `unackedEnvs()` or `instance()`. Fired after a record is submitted, after one is stored, and when\n * the session ends.\n */\n onChange?(): void;\n /**\n * A local write violated the room policy. The session ejects itself immediately after —\n * the outcome the relay's own independent check would have produced one hop later. The\n * emit-side check spares the room the round trip; it is never the enforcement.\n */\n onLocalReject?(violation: PolicyViolation): void;\n /** The transport closed and a reconnect is scheduled; `code` is the close code (1009 = message too big). */\n onDisconnect?(code: number, reason: string): void;\n /**\n * The session is ending (eject, close, a storage ending or a clear), called before anything else of\n * the ending: before the transport closes, before any other hook and before the status changes.\n */\n onTerminal?(state: 'ejected' | 'closed', reason?: string): void;\n /**\n * The transport factory or a transport's `send` threw. The session treats it as a lost connection\n * and reconnects; the error is handed here to be reported. A hook that threw is reported here too.\n */\n onCallbackError?(error: unknown): void;\n /** The listed conflicts changed (a write judged, discarded or re-authored, once that is stored). */\n onConflicts?(conflicts: readonly MeshConflict[]): void;\n /** The relay announced the room's compaction state (count, budget, ready members). */\n onCompaction?(state: CompactionState): void;\n /**\n * A snapshot welcome of a NEW generation installed (a cut's welcome, a new room, or the first\n * snapshot of the session). A later welcome of the installed generation never fires it.\n */\n onGeneration?(generation: GenerationState | undefined): void;\n};\n\nexport type MeshSessionOptions<T extends object> = {\n readonly room: string;\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** The op engine this session feeds. The shell creates (and destroys) it. */\n readonly sync: OpSync<T>;\n /**\n * The journal of this client's own writes, loaded, with its origin recorded and stored. The engine\n * mints under that origin and takes its emission floors from the journal's state.\n */\n readonly journal: SessionJournal;\n readonly policies?: readonly MergePolicyEntry[];\n readonly policy?: OpPolicy;\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion: number;\n readonly schemaVersion?: number;\n /**\n * Write a conflict's raw ops again (a new write citing the current state), on the shell's store;\n * with `bump`, as an authority override. It must emit synchronously through `sync`. Without it a\n * conflict can only be discarded.\n */\n readonly reauthor?: (intent: Intent) => void;\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * How long a hello may go unanswered before its connection is reset: `timeoutMs` (default\n * 15 000), doubled for every hello in a row that timed out, up to `maxTimeoutMs` (default\n * 120 000), plus up to 100 ms of jitter. An answered hello starts the count again.\n */\n readonly handshake?: {\n readonly timeoutMs?: number;\n readonly maxTimeoutMs?: number;\n };\n /** Timer seam (tests, deterministic harnesses). Defaults to global timers. */\n readonly schedule?: {\n set(fn: () => void, ms: number): unknown;\n clear(handle: unknown): void;\n };\n readonly hooks: MeshSessionHooks;\n /** For tests only: the first hello id of the first connection, to reach the id counter's limit. */\n readonly firstHelloIdForTests?: number;\n};\n\n/**\n * The relay-room session protocol, shell-agnostic: hello/welcome handshakes, own writes from their\n * stored record to their stored answer, reconnect backoff, presence, eject/reject, the generation\n * fence and settled-vector garbage collection. Every own write is stored before it is sent, and\n * every answer about it is stored before it is shown. `meshSync` wraps it for Angular; `agentSeat`\n * wraps it for injector-free environments.\n */\nexport type MeshSession = {\n /** Open the first connection. Call once. */\n connect(): void;\n status(): MeshStatus;\n /** Highest relay seq observed. With no unacked writes, local state is the pure fold of the room at this seq. */\n lastSeq(): number;\n /**\n * Some own write is neither acknowledged nor judged on storage, or a write recorded in this boot\n * has not reached storage yet. A held conflict is judged and does not count. True for good once a\n * write is made that is never recorded, so never sent: after the session ended, or inside a\n * {@link MeshSession.recordTogether} or a re-author that threw. False after `clear()`.\n */\n hasUnacked(): boolean;\n /**\n * Every own write is stored as the room's, or the relay refused it and it is listed in\n * {@link MeshSession.unstored} (such a write does not hold this false): nothing is pending or\n * unsaved on storage and no conflict is held. Once the session has ended by an eject or a close, true exactly when nothing was\n * outstanding at the ending and nothing was written since; false after an ending of the journal\n * and from the call of `clear()`. After an ending it reads true exactly when {@link MeshSession.whenAcked} resolves.\n */\n acked(): boolean;\n /**\n * The client owes itself a snapshot (a refused write is still applied locally, or the room moved\n * to another generation): true until a snapshot that answers a hello sent after the latest such\n * event installs.\n */\n snapshotOwed(): boolean;\n /**\n * Resolves once no own write is outstanding and that is stored: the acknowledgement barrier a\n * caller awaits before treating its writes as the room's. Rejects with the terminal reason if the\n * session ends (eject or close) while writes remain, with the journal's reason once it ended\n * (`'storage'`, `'moved'` or `'exhausted'`) and with `'cleared'` after `clear()`; the first ending's\n * reason stands. While a conflict is held it\n * rejects with `conflict: <cause>` of the oldest one. A write the relay refused rejects the waiters\n * pending when its verdict is stored with `refused: <reason>`; a later call does not wait for it.\n *\n * With a relay whose adapter confirms durability before echoing, acknowledged means\n * stored; against a relay that echoes eagerly it means only \"the relay has it\".\n */\n whenAcked(): Promise<void>;\n /** Every own write not yet stored as acknowledged or judged, in the order they were made. */\n unackedEnvs(): readonly OpEnvelope[];\n /** The room generation this client's writes are bound to, once a welcome named one. */\n instance(): string | undefined;\n /** The room generation this boot installed from a snapshot welcome; undefined before the first. */\n generation(): GenerationState | undefined;\n peers(): ReadonlyMap<string, PresenceState>;\n setPresence(data: unknown): void;\n /** Send peer signaling over the current connection without a second hello. */\n sendSignal(msg: ClientSignalMsg): void;\n /** Send a `direct` frame to one member over the current connection; lost when there is none. */\n sendDirect(to: string, data: unknown): void;\n /** Writes that will never be admitted as they stand, each with its two verbs, in the order they were made. */\n conflicts(): readonly MeshConflict[];\n /** Own writes that were not stored, in the order they were made, each with `dismiss()`. */\n unstored(): readonly UnstoredWrite[];\n /**\n * The member pressed (or released) Compact. While pressed, the session declares itself ready for\n * a consensus cut whenever nothing it wrote is outstanding, and re-declares on every change; a\n * reconnect and a new generation release the press. Safety never depends on it.\n */\n declareReady(pressed: boolean): void;\n /**\n * Discard every unsent write and end the session. From the call nothing more is sent or recorded,\n * `hasUnacked()` and `acked()` are false, and waiters reject `'cleared'`, those asked later too; the\n * status does not change yet. The session ends `closed` with reason `'cleared'` when the wipe is\n * stored, and the returned promise resolves then. It rejects when the wipe is refused (`'moved'`),\n * its outcome is not known, or the session ends first (a close rejects it `'closed'`); the session\n * then ends with that reason. A crash before the wipe is stored leaves storage as it was, and the\n * next boot sends what is pending. A second call while it runs returns the same promise.\n */\n clear(): Promise<void>;\n /**\n * Records every write `fn` makes through the engine as one group, after what is recorded already:\n * the writes are stored together or not at all. A write the emit-side policy refuses ends the\n * session as any write does, and then none of them is recorded; nor is any when `fn` throws, and\n * what it wrote then stays outstanding for good. `fn` makes writes; it does not answer a conflict.\n */\n recordTogether(fn: () => void): void;\n close(): void;\n};\n\nconst RECONNECT_BASE_MS = 500;\n/** The jitter bound of the reconnect backoff, which the hello timeout shares. */\nconst JITTER_MS = 100;\nconst HELLO_TIMEOUT_MS = 15_000;\nconst HELLO_MAX_TIMEOUT_MS = 120_000;\n/** `direct` frames held before a welcome, per connection: the bound peer links keep for signals. */\nconst HELD_DIRECTS = 256;\n\nconst UNSTORED_REASON: Partial<Record<JournalVerdict, UnstoredReason>> = {\n discarded: 'generation',\n schema: 'schema',\n order: 'order',\n compacting: 'compacting',\n incompatible: 'incompatible',\n};\n\ntype Ending = {\n readonly reason: string;\n /** Waiters reject with the reason whatever is outstanding (a storage failure, a clear). */\n readonly always: boolean;\n};\n\ntype Waiter = { resolve: () => void; reject: (cause: Error) => void };\n\ntype Installed = JournalBinding & { landed: boolean };\n\ntype SnapshotWelcome = Extract<WelcomeMsg, { mode: 'snapshot' }>;\n\n// what a hook throws is handed to the reporter; what the reporter throws is dropped\nconst reportTo = (hooks: MeshSessionHooks, error: unknown): void => {\n try {\n hooks.onCallbackError?.(error);\n } catch {\n // the reporter's own failure changes nothing\n }\n};\n\n// every hook called through one gate: none while `open()` says no, and a throw returns as if the\n// hook had returned\nfunction gateHooks(\n hooks: MeshSessionHooks,\n open: () => boolean,\n): MeshSessionHooks {\n const out: Record<string, unknown> = {};\n for (const [name, f] of Object.entries(hooks))\n out[name] =\n typeof f !== 'function'\n ? f\n : name === 'onCallbackError'\n ? (error: unknown): void => {\n if (open()) reportTo(hooks, error);\n }\n : (...args: unknown[]): unknown => {\n if (!open()) return undefined;\n try {\n return (f as (...a: unknown[]) => unknown).apply(hooks, args);\n } catch (error) {\n reportTo(hooks, error);\n return undefined;\n }\n };\n return out as MeshSessionHooks;\n}\n\nconst validRid = (rid: unknown): rid is number =>\n typeof rid === 'number' && Number.isSafeInteger(rid) && rid > 0;\n\nexport function meshSession<T extends object>(\n opt: MeshSessionOptions<T>,\n): MeshSession {\n const { sync, journal } = opt;\n const hooks = gateHooks(opt.hooks, () => told());\n const schedule = opt.schedule ?? {\n set: (fn: () => void, ms: number) => setTimeout(fn, ms),\n clear: (handle: unknown) =>\n clearTimeout(handle as ReturnType<typeof setTimeout>),\n };\n\n const state = (): JournalState => journal.state();\n const durable = (): JournalState => journal.durable();\n const heldInstance = (): string | undefined =>\n state().gen?.instance ?? undefined;\n\n let status: MeshStatus = 'connecting';\n const ownOrigins = new Set<string>([sync.origin]);\n const journalOrigin = state().origin;\n if (journalOrigin) ownOrigins.add(journalOrigin);\n let lastSeq = 0;\n // the highest seq of a relay-delivered envelope of the installed generation\n let maxSeq = 0;\n const restored = heldInstance();\n if (restored) sync.adopt(restored);\n // hello ids on the current connection: the last one issued, the ones unanswered with their\n // timers, the highest answered, and the last one issued before the latest debt\n let helloId = 0;\n let firstHelloId = opt.firstHelloIdForTests ?? 1;\n const asked = new Map<number, unknown>();\n let answeredId = 0;\n let owedAfter = 0;\n let owed = false;\n // hellos in a row that timed out since the last answered one (boot memory)\n let timedOut = 0;\n // the instance whose state this boot installed last: a hello names it, a non-snapshot welcome of\n // any other one cannot be used\n let lastInst: string | null = null;\n let suspended = false;\n\n // the generation this boot installed from a snapshot, its evidence and the client's register store\n let gen: InstalledGeneration | undefined;\n let admission: ClientAdmission = emptyAdmission();\n let cover: RegisterStore = createRegisterStore();\n // an own write that is recorded joins the evidence and the register store, at every place one is\n const ingestOwn = (env: OpEnvelope): void => {\n admitLocal(admission, env);\n cover.ingest(env);\n };\n let announcedInst: string | undefined;\n // what the last welcome said of the room, for the emit-side policy\n let lastEmpty = false;\n // refused writes whose local effect no snapshot has removed yet (memory of the boot)\n const inStore = new Set<number>();\n // the generations this boot knows by instance, to tell an older one from the held one\n const gens = new Map<string, JournalBinding>();\n const known = (b: JournalBinding | null): void => {\n if (b && b.instance) gens.set(b.instance, b);\n };\n known(state().gen);\n for (const e of state().entries) known(e.bind);\n // the seed's memory of the boot: the seeds minted here (only they carry conflicts), whether the\n // last installed welcome said the room is empty and no own seed was admitted since, a seed the\n // host refused (held back until the next install), the seeds a snapshot of a room that is not\n // empty replaced the store for while they were pending, the writes that replacement removed, and\n // the lost seeds whose carried conflicts were offered at the loss\n const seededHere = new Set<number>();\n let knownEmpty = false;\n let seedHeld: number | null = null;\n const replacedFor = new Set<number>();\n const outOfStore = new Set<number>();\n const offeredAtLoss = new Set<number>();\n // census: the press is per connection, never persisted; `declared` mirrors what the relay holds\n let pressed = false;\n let declared: { ready: boolean; instance: string } | undefined;\n\n let peers: ReadonlyMap<string, PresenceState> = new Map();\n let members: readonly string[] | undefined;\n let presenceData: unknown;\n let hasPresence = false;\n let transport: MeshTransport | null = null;\n let attempts = 0;\n let reconnectTimer: unknown;\n let unsubs: (() => void)[] = [];\n let closed = false;\n let connected = false;\n // a `direct` frame and a room envelope wait for the welcome of their connection\n let welcomedHere = false;\n let heldDirects: ServerDirectMsg[] = [];\n let versionWarned = false;\n let heldWarned = false;\n\n // what was handed to the current connection, per version and the instance it went into\n const sent = new Set<string>();\n const sentMark = (version: number, inst: string): string =>\n `${version}|${inst}`;\n let installed: Installed | null = null;\n // a welcome is being installed: nothing is handed over until its group is submitted\n let installing = false;\n // writes made after the session ended: never recorded, never sent\n let unsaved = 0;\n let ending: Ending | null = null;\n // after an ending, the one fact both `acked()` and the waiters read: set when something was\n // outstanding at the ending, when a write was made after it, or by a storage failure or a clear\n let ackFailure: Error | undefined;\n // `clear()` was called: the journal is discarded, whatever ended the session first\n let cleared = false;\n // a clear asked while the session ran: it sends and records nothing and tells nothing until the\n // clear's answer ends it\n let clearing: Promise<void> | null = null;\n // the ending's own step: what it tells is told although the session has closed\n let inEnding = false;\n let waiters: Waiter[] = [];\n // a refusal and the number of the group that holds its verdict\n type Refusal = {\n readonly reason: UnstoredReason;\n readonly group: number;\n };\n let refusals: Refusal[] = [];\n // a re-author's emission joins the group of its answer; held writes join one group\n let capture: JournalRecord[] | null = null;\n let lastConflicts = '';\n\n // every way control enters the session is one step; a message or a close that arrives while a\n // step runs waits in the inbox and is handled, in arrival order, when the outermost step ends\n let depth = 0;\n const inbox: (() => void)[] = [];\n const drain = (): void => {\n let failure: { error: unknown } | undefined;\n depth++;\n try {\n for (let next = inbox.shift(); next; next = inbox.shift()) {\n try {\n next();\n } catch (error) {\n failure ??= { error };\n }\n }\n } finally {\n depth--;\n }\n if (failure) throw failure.error;\n };\n const step = <R>(fn: () => R): R => {\n depth++;\n try {\n return fn();\n } finally {\n depth--;\n if (depth === 0 && inbox.length) drain();\n }\n };\n const arrive = (fn: () => void): void => {\n inbox.push(fn);\n if (depth === 0) drain();\n };\n\n const quiet = (): boolean => closed || clearing !== null;\n const usable = (): boolean => !quiet() && journal.ended() === null;\n const discarded = (): boolean =>\n cleared || journal.ended()?.kind === 'cleared';\n // every status change, hook and timer passes here: nothing once the session has ended or while it\n // clears, except what the ending itself tells\n const told = (): boolean => inEnding || !quiet();\n\n const settledDurably = (): boolean =>\n pendingEnvelopes(durable()).length === 0 && !journal.ownUnlanded();\n // a write that was emitted and never recorded is outstanding for good\n const outstanding = (): boolean =>\n unsaved > 0 || !settledDurably() || heldConflicts(durable()).length > 0;\n\n const lostConflictsHidden = (s: JournalState): readonly number[] =>\n !s.lost || offeredAtLoss.has(s.lost.version) ? [] : s.lost.conflicts;\n\n const setStatus = (next: MeshStatus, reason?: string): void => {\n if (!told()) return;\n status = next;\n hooks.onStatus(next, reason);\n };\n\n // every frame goes out here, on the transport its caller is working on: none once the session has\n // closed or while it clears, and none on a transport the session no longer holds. A send that\n // throws loses the connection\n const send = (on: MeshTransport | null, frame: ClientMsg): void => {\n if (quiet() || !on || on !== transport) return;\n try {\n on.send(frame);\n } catch (error) {\n hooks.onCallbackError?.(error);\n if (on === transport) broken(on, 'send');\n }\n };\n\n // nothing is recorded once the session has closed or while it clears, whoever asks\n const submit = (group: readonly JournalRecord[]): Promise<void> | null => {\n if (quiet()) return null;\n const landed = journal.submit(group);\n // a refused append ends the journal, which ends the session through `onEnd`\n landed?.catch(() => undefined);\n return landed;\n };\n\n const terminal = (\n state: 'ejected' | 'closed',\n reason?: string,\n always = false,\n ): void => {\n if (closed) return;\n closed = true;\n const why = reason ?? state;\n ending = { reason: why, always };\n // read before the hook: the shell closes the journal there. A clear begun counts as outstanding\n if (always || clearing !== null || outstanding())\n ackFailure = new Error(why);\n inEnding = true;\n try {\n hooks.onTerminal?.(state, reason);\n if (reconnectTimer !== undefined) {\n schedule.clear(reconnectTimer);\n reconnectTimer = undefined;\n }\n forgetHellos();\n for (const unsub of unsubs.splice(0)) unsub();\n // after a close the shell destroys the engine; after an eject a later write still counts\n if (state === 'closed') unsubLocal();\n heldDirects = [];\n transport?.close();\n transport = null;\n installed = null;\n peers = new Map();\n hooks.onPeers?.(peers);\n members = undefined;\n hooks.onMembers?.(members);\n setStatus(state, reason);\n release();\n } finally {\n inEnding = false;\n }\n };\n\n // the data shape is older than the room's: the session ends, nothing is judged or reported\n const outdated = (): void => terminal('ejected', 'schema');\n\n const forgetHellos = (): void => {\n for (const timer of asked.values()) schedule.clear(timer);\n asked.clear();\n };\n\n const helloLimit = (): number =>\n Math.min(\n (opt.handshake?.timeoutMs ?? HELLO_TIMEOUT_MS) * 2 ** timedOut,\n opt.handshake?.maxTimeoutMs ?? HELLO_MAX_TIMEOUT_MS,\n );\n\n // a hello names the instance this boot holds state of, unless it owes a snapshot or holds none;\n // its id and its timer are recorded before it is sent, as an answer may arrive inside the send\n const sendHello = (): void => {\n const t = transport;\n if (!t || quiet()) return;\n // ids never wrap: a counter at its limit reconnects\n if (helloId >= Number.MAX_SAFE_INTEGER) return reset('counter');\n hooks.onOrigin?.(sync.origin);\n // the hook can end the session or replace its transport: no timer is left behind for this hello\n if (quiet() || transport !== t) return;\n const named = lastInst !== null && !owed;\n const rid = ++helloId;\n asked.set(\n rid,\n schedule.set(\n () =>\n step(() => {\n if (transport !== t || !asked.has(rid)) return;\n timedOut++;\n reset('timeout');\n }),\n helloLimit() + Math.random() * JITTER_MS,\n ),\n );\n send(t, {\n t: 'hello',\n room: opt.room,\n origin: sync.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion,\n rid,\n ...(named ? { seq: lastSeq, instance: lastInst as string } : {}),\n schemaVersion: opt.schemaVersion,\n });\n };\n\n // one hello outstanding at a time: a debt raised while one is unanswered is asked for when its\n // answer comes\n const askSnapshot = (): void => {\n if (!transport || !owed || quiet()) return;\n if (helloId > owedAfter || answeredId < helloId) return;\n sendHello();\n };\n\n // the store no longer matches a snapshot: only a snapshot answering a hello sent after the latest\n // debt clears it, so every new debt moves the mark\n const raiseOwed = (): void => {\n owed = true;\n owedAfter = helloId;\n askSnapshot();\n };\n\n /** Send the census flag when the member's readiness (or its generation) changed. */\n const declare = (): void => {\n const inst = heldInstance();\n if (!inst || !transport || !welcomedHere || quiet()) return;\n // the op log is flushed before readiness is computed\n if (pressed) sync.flush();\n if (quiet() || !transport) return;\n // beside the member's own rule: live, no snapshot owed, no group on its way to storage\n const ready =\n readyValue({\n pressed,\n connected,\n replaying: !installed?.landed,\n outstanding:\n unsaved +\n pendingEnvelopes(durable()).length +\n (journal.ownUnlanded() ? 1 : 0),\n }) &&\n status === 'live' &&\n !suspended &&\n !owed &&\n !journal.inFlight();\n if (declared && declared.ready === ready && declared.instance === inst)\n return;\n declared = { ready, instance: inst };\n send(transport, { t: 'compact', room: opt.room, instance: inst, ready });\n };\n\n // ─── own writes: queue, sends, answers ───\n\n const isDurableWrite = (version: number): boolean =>\n durable().entries.some((e) => e.env.version === version);\n\n const canSend = (): boolean =>\n !installing &&\n usable() &&\n status === 'live' &&\n !!transport &&\n welcomedHere &&\n !suspended &&\n !!installed?.landed;\n\n // a seed minted under another schema version than this boot's is never sent by this boot\n const otherVersion = (seed: JournalSeed): boolean =>\n seed.schema !== (opt.schemaVersion ?? 0);\n\n const sendEnv = (\n on: MeshTransport | null,\n env: OpEnvelope,\n inst: string,\n ): void => {\n const seed = state().seed;\n // a seed carries the schema version it was minted under; an ordinary envelope carries none\n const schema =\n env.seed && seed?.version === env.version && seed.schema > 0\n ? { schemaVersion: seed.schema }\n : {};\n const out =\n env.instance === inst && !('schemaVersion' in schema)\n ? env\n : { ...env, instance: inst, ...schema };\n sent.add(sentMark(env.version, inst));\n send(on, { t: 'env', room: opt.room, env: out });\n };\n\n // one queue in the order the writes were made: a write is sent once its record is stored, once per\n // connection and generation, and never ahead of an earlier one that is not stored yet\n const pumpSends = (): void => {\n if (!canSend()) return;\n const on = transport;\n const inst = (installed as Installed).instance;\n const s = state();\n const ps = s.seed;\n // a seed acknowledged but not stored still keeps its dependents back\n const held = new Set(parkedBySeed(durable()));\n if (seedHeld !== null) held.add(seedHeld);\n if (ps && otherVersion(ps)) held.add(ps.version);\n for (const env of sendQueue(s)) {\n if (held.has(env.version) || sent.has(sentMark(env.version, inst)))\n continue;\n // a room known to be empty takes only a marked seed\n if (knownEmpty && env.version !== ps?.version) continue;\n if (!isDurableWrite(env.version)) break;\n sendEnv(on, env, inst);\n if (!canSend()) return;\n }\n };\n\n const offered = (): {\n env: OpEnvelope;\n intent: Intent;\n cause: ConflictCause;\n }[] => {\n // a cleared journal holds no answer to give, from the call on\n if (discarded()) return [];\n const s = state();\n const d = durable();\n // a conflict a pending seed carries is not offered, nor one a lost seed carried until what it\n // carried is decided\n const hidden = new Set([\n ...(s.seed?.conflicts ?? []),\n ...lostConflictsHidden(s),\n ]);\n const stored = new Map(\n heldConflicts(d).map((c) => [c.env.version, c.verdict]),\n );\n return heldConflicts(s)\n .filter(\n (c) =>\n !hidden.has(c.env.version) &&\n stored.get(c.env.version) === c.verdict &&\n c.intent !== null,\n )\n .map((c) => ({\n env: c.env,\n intent: c.intent as Intent,\n cause: c.verdict as ConflictCause,\n }));\n };\n\n const isOffered = (version: number): boolean =>\n offered().some((c) => c.env.version === version);\n\n const conflicts = (): readonly MeshConflict[] =>\n offered().map((c) => ({\n ...c,\n discard: () =>\n step(() => {\n if (!usable() || !isOffered(c.env.version)) return;\n void submit([\n {\n k: 'answered',\n origin: c.env.origin,\n version: c.env.version,\n how: 'discard',\n replacement: null,\n },\n ]);\n }),\n reauthor: () =>\n step(() => {\n if (\n capture !== null ||\n !usable() ||\n !opt.reauthor ||\n !isOffered(c.env.version)\n )\n return false;\n if (validateOps(c.intent.raws) !== null) return false;\n // a write made before the call is recorded on its own, not as part of the answer\n sync.flush();\n if (!usable()) return false;\n const caught: JournalRecord[] = [];\n capture = caught;\n let threw = true;\n try {\n opt.reauthor(c.intent);\n sync.flush();\n threw = false;\n } finally {\n capture = null;\n if (threw) neverSaved(caught);\n }\n const first = caught[0];\n if (!usable()) {\n neverSaved(caught);\n return false;\n }\n if (!first || first.k !== 'write') return false;\n for (const r of caught) if (r.k === 'write') ingestOwn(r.env);\n void submit([\n {\n k: 'answered',\n origin: c.env.origin,\n version: c.env.version,\n how: 'reauthor',\n replacement: first.env.version,\n },\n ...caught,\n ]);\n return true;\n }),\n }));\n\n const unstored = (): readonly UnstoredWrite[] => {\n if (discarded()) return [];\n const d = durable();\n const stored = new Map(\n unstoredWrites(d).map((w) => [w.env.version, w.verdict]),\n );\n return unstoredWrites(state()).flatMap((w) => {\n const reason = UNSTORED_REASON[w.verdict];\n if (!reason || !w.intent || stored.get(w.env.version) !== w.verdict)\n return [];\n return [\n {\n env: w.env,\n intent: w.intent,\n reason,\n dismiss: () =>\n step(() => {\n if (!usable()) return;\n if (!unstored().some((x) => x.env.version === w.env.version))\n return;\n void submit([\n {\n k: 'reported',\n origin: w.env.origin,\n version: w.env.version,\n verdict: w.verdict,\n },\n ]);\n }),\n },\n ];\n });\n };\n\n // the group holding a refusal's verdict has landed, as the journal counts its landings\n const refusalStored = (r: Refusal): boolean => journal.landed() >= r.group;\n\n const settleWaiters = (): void => {\n // a clear begun rejected every waiter at its call, and rejects each one asked since at once\n if (clearing !== null && !ending) return;\n // a refusal rejects the waiters pending when its verdict is stored, before anything resolves them\n for (const r of [...refusals]) {\n if (!refusalStored(r)) continue;\n refusals = refusals.filter((x) => x !== r);\n const pending = waiters;\n waiters = [];\n for (const w of pending) w.reject(new Error(`refused: ${r.reason}`));\n }\n if (!waiters.length) return;\n const keep: Waiter[] = [];\n const listed = offered();\n for (const w of waiters) {\n if (ending) {\n if (ackFailure) w.reject(ackFailure);\n else w.resolve();\n } else if (listed.length) {\n w.reject(new Error(`conflict: ${listed[0].cause}`));\n } else if (!outstanding()) {\n w.resolve();\n } else keep.push(w);\n }\n waiters = keep;\n };\n\n // the continuation after every change: release what storage allows, settle waiters, tell the shell\n let releasing = false;\n let again = false;\n const release = (): void => {\n if (!told()) return settleWaiters();\n if (releasing) {\n again = true;\n return;\n }\n releasing = true;\n try {\n do {\n again = false;\n pumpSends();\n settleWaiters();\n const list = offered();\n const key = list.map((c) => `${c.env.version}:${c.cause}`).join(',');\n if (key !== lastConflicts) {\n lastConflicts = key;\n hooks.onConflicts?.(conflicts());\n }\n declare();\n hooks.onChange?.();\n } while (again);\n } finally {\n releasing = false;\n }\n };\n\n const unsubChange = journal.onChange(() => step(release));\n // after either ending nothing more can become durable: a session that had already ended keeps its\n // reason, and its waiters reject with it\n const journalEnded = (): void => {\n if (ending) ackFailure ??= new Error(ending.reason);\n release();\n };\n const unsubEnd = journal.onEnd((end) =>\n step(() => {\n if (closed) return journalEnded();\n if (end.kind === 'cleared') terminal('closed', 'cleared', true);\n else terminal('ejected', end.kind, true);\n }),\n );\n\n // writes emitted and never recorded: they are never sent and stay outstanding\n const neverSaved = (caught: readonly JournalRecord[]): void => {\n if (!caught.length) return;\n unsaved += caught.length;\n if (ending) ackFailure ??= new Error(ending.reason);\n release();\n };\n\n // a group is submitted; a verdict in it that is not a conflict rejects the waiters pending once\n // it is stored\n const record = (group: readonly JournalRecord[]): Promise<void> | null => {\n const n = journal.submitted() + 1;\n const mine = group.flatMap((r): Refusal[] => {\n const reason = r.k === 'judged' ? UNSTORED_REASON[r.verdict] : undefined;\n return r.k === 'judged' && reason ? [{ reason, group: n }] : [];\n });\n // noted before the submission, whose own change notification already settles waiters\n refusals.push(...mine);\n const landed = submit(group);\n if (!landed) refusals = refusals.filter((r) => !mine.includes(r));\n return landed;\n };\n\n const judged = (version: number, verdict: JournalVerdict): JournalRecord => ({\n k: 'judged',\n origin: journalOrigin as string,\n version,\n verdict,\n });\n const ackedRec = (version: number, receipt = false): JournalRecord => ({\n k: 'acked',\n origin: journalOrigin as string,\n version,\n ...(receipt ? { receipt: true as const } : {}),\n });\n\n const pendingVersion = (version: number): boolean =>\n !!journalOrigin && isPendingWrite(state(), journalOrigin, version);\n\n const entryOf = (\n s: JournalState,\n version: number,\n ): JournalEntry | undefined =>\n s.entries.find((e) => e.env.version === version);\n\n // the writes a pending seed keeps out of the send queue: what it carries and the writes after it\n const parkedOf = (s: JournalState): number[] =>\n s.seed ? parkedBySeed(s) : [];\n\n // a seed admitted: it and every pending entry it carries are acknowledged, and each refused write\n // whose effect it carries is subsumed, a held conflict and a write listed as not stored alike\n const seedAcked = (seed: JournalSeed, receipt = false): JournalRecord[] => {\n const s = state();\n const answerable = new Set(\n s.entries\n .filter(\n (e) =>\n e.verdict !== null &&\n !e.env.seed &&\n (isConflictVerdict(e.verdict) || isUnstoredVerdict(e.verdict)),\n )\n .map((e) => e.env.version),\n );\n return [\n ackedRec(seed.version, receipt),\n ...seed.carried\n .filter((v) => pendingVersion(v))\n .map((v) => ackedRec(v, receipt)),\n ...seed.conflicts\n .filter((v) => answerable.has(v))\n .map((v) => judged(v, 'subsumed')),\n ];\n };\n\n const admittedOwn = (origin: string, version: number): void => {\n if (origin !== journalOrigin) return;\n // an own seed admitted: the room is no longer empty\n if (entryOf(state(), version)?.env.seed) knownEmpty = false;\n if (!installed || !pendingVersion(version)) return;\n const seed = state().seed;\n void record(\n seed?.version === version ? seedAcked(seed) : [ackedRec(version)],\n );\n };\n\n // a refused write's local effect stays in the store until a snapshot installs, so one is owed\n const refusedEffect = (version: number): void => {\n inStore.add(version);\n raiseOwed();\n };\n\n // a seed the relay refused (`'seeded'`, or `order`: the room is not empty): it is judged and a\n // snapshot is owed. What it carried is discarded now only where a snapshot of a room that is not\n // empty already removed it from the store in this boot (the seed was contested), and its carried\n // conflicts are offered then; everything else stays parked or hidden until the next install\n const seedLost = (version: number, verdict: 'seeded' | 'order'): void => {\n if (!pendingVersion(version)) return raiseOwed();\n const replaced = replacedFor.has(version);\n const s = state();\n const gone =\n s.seed?.version === version\n ? parkedOf(s).filter((v) => outOfStore.has(v))\n : [];\n void record([\n judged(version, verdict),\n ...gone.map((v) => judged(v, 'discarded')),\n ]);\n if (replaced) offeredAtLoss.add(version);\n raiseOwed();\n };\n\n // a host refusal of a seed is no verdict: nothing is judged or reported, what it carries and parks\n // stays so, a snapshot is owed; the answer frees the seed to be handed over again on this\n // connection, at or after the next installing welcome\n const seedHostRefused = (version: number, inst: string): void => {\n if (pendingVersion(version)) {\n sent.delete(sentMark(version, inst));\n seedHeld = version;\n }\n raiseOwed();\n };\n\n const onDrop = (msg: DropMsg): void => {\n if (!ownOrigins.has(msg.origin)) return;\n if (msg.reason === 'duplicate') {\n admittedOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement\n return;\n }\n if (msg.reason === 'generation') {\n // not a verdict: the write stays pending. A drop stamped with the held generation or a newer\n // one raises a debt, compared by index; one stamped with an older index of the same lineage\n // does not: the install past it already sent the write again under the held generation\n const at = installed;\n const of = gens.get(msg.instance);\n const older =\n !!at && !!of && of.lineage === at.lineage && of.index < at.index;\n if (!older) raiseOwed();\n return;\n }\n // nothing is judged while the handshake is suspended: the write stays pending\n if (suspended) return;\n // a write has one terminal verdict, the first: an answer about a write that is not pending changes nothing\n if (msg.origin !== journalOrigin || !pendingVersion(msg.version)) return;\n const isSeed = !!entryOf(state(), msg.version)?.env.seed;\n if (msg.reason === 'schema' && isSeed) return outdated();\n if (msg.reason === 'compacting' && isSeed)\n return seedHostRefused(msg.version, msg.instance);\n if (msg.reason === 'seeded') return seedLost(msg.version, 'seeded');\n if (msg.reason === 'order' && isSeed) return seedLost(msg.version, 'order');\n void record([judged(msg.version, msg.reason)]);\n refusedEffect(msg.version);\n };\n\n const newerShape = (env: SeqEnvelope): boolean =>\n opt.schemaVersion !== undefined &&\n env.schemaVersion !== undefined &&\n env.schemaVersion > opt.schemaVersion;\n\n /** One relay delivery; true when it broke its origin's order, so a snapshot is now owed. */\n const applyRemote = (env: SeqEnvelope): boolean => {\n if (closed) return false; // a delta welcome keeps iterating after an eject — nothing lands past it\n // a newer data shape is the room's, whatever generation carried it (a migration row belongs to\n // the generation it closes)\n if (newerShape(env)) {\n terminal('ejected', 'schema');\n return false;\n }\n const inst = heldInstance();\n // the generation fence: an envelope of another generation is never ingested, and teaches nothing\n if (inst !== undefined && env.instance !== inst) return false;\n // sequence knowledge advances on every relay-delivered envelope, before any deduplication\n lastSeq = Math.max(lastSeq, env.seq);\n maxSeq = Math.max(maxSeq, env.seq);\n hooks.onSynced?.();\n if (ownOrigins.has(env.origin)) {\n admittedOwn(env.origin, env.version);\n return false;\n }\n // an envelope the engine will drop is handed to it for the drop alone: it is no delivery\n if (env.proto !== OP_PROTO_VERSION || validateEnvelope(env) !== null) {\n sync.receive(env);\n return false;\n }\n const verdict = admitLocal(admission, env);\n if (verdict === 'duplicate') return false; // a duplicate delivery applies nothing\n if (verdict === 'below-max') {\n // a version below one already delivered: the feed broke this origin's order. Nothing of it is\n // ingested; a snapshot holds it\n return true;\n }\n cover.ingest(env);\n sync.receive(env);\n hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });\n return false;\n };\n\n /** Hydrate the op engine from `registers` with `pending` own writes re-applied over them. */\n const hydrateWith = (\n registers: readonly RegisterCheckpoint[],\n wm: Readonly<Record<string, number>>,\n pending: readonly OpEnvelope[],\n ): void => {\n const conv = createConvergingApply({ policies: opt.policies });\n conv.load(registers);\n // own origins are left out of the watermark: exactly `pending` is re-applied, nothing else\n const theirs: Record<string, number> = {};\n for (const [o, v] of Object.entries(wm))\n if (!ownOrigins.has(o)) theirs[o] = v;\n sync.hydrate(\n { root: conv.materialize() as T, registers: [...registers], wm: theirs },\n pending,\n );\n };\n\n const eligible = (\n b: JournalBinding,\n g: JournalBinding & { replayBase: number },\n ) => b.lineage === g.lineage && b.index >= g.replayBase;\n\n const adoptedRec = (\n msg: WelcomeMsg,\n evidence: ReturnType<typeof ownEpochs> | undefined,\n ): JournalRecord => ({\n k: 'adopted',\n gen: {\n lineage: msg.lineage,\n instance: msg.instance,\n index: msg.index,\n replayBase: msg.replayBase,\n },\n ...(evidence ? { evidence: evidence.map((x) => ({ ...x })) } : {}),\n });\n\n // nothing is sent on this connection before the install's group is stored: the new installation\n // is the current one before its group is submitted, as submitting runs the send queue\n const submitInstall = (\n msg: WelcomeMsg,\n group: readonly JournalRecord[],\n ): boolean => {\n const mine: Installed = {\n lineage: msg.lineage,\n instance: msg.instance,\n index: msg.index,\n landed: false,\n };\n installed = mine;\n const landed = record(group);\n if (!landed) return false;\n landed.then(\n () =>\n step(() => {\n mine.landed = true;\n if (installed === mine) release();\n }),\n () => undefined,\n );\n return true;\n };\n\n const takeGeneration = (\n msg: SnapshotWelcome,\n ): readonly RegisterCheckpoint[] => {\n const registers = msg.seed ?? msg.registers;\n gen = {\n instance: msg.instance,\n index: msg.index,\n reason: msg.reason,\n policy: msg.policy,\n extent: msg.extent,\n preCutMax: msg.preCutMax,\n seq: msg.seq,\n };\n admission = admissionOf(msg);\n cover = createRegisterStore();\n cover.load(registers);\n return registers;\n };\n\n // the seed of a room that is empty: one root `set` of the store as it stands, through the engine,\n // checked by the emit-side policy as a seed; null when the policy ended the session\n const mintSeed = (): OpEnvelope | null => {\n const caught: JournalRecord[] = [];\n capture = caught;\n try {\n sync.seed();\n } finally {\n capture = null;\n }\n if (closed) return null;\n const r = caught.find((x) => x.k === 'write' && x.env.seed === true);\n return r && r.k === 'write' ? r.env : null;\n };\n\n /**\n * A welcome of a room that is empty. With no pending seed, a seed of the store as it stands that\n * carries every pending write and, in a live session, the refused writes whose effect is still in\n * the store; with a pending seed of this instance and version, the same seed stays pending; with\n * one of another instance or version, a new seed supersedes it. `adopted` first, in one group.\n */\n const emptyWelcome = (msg: WelcomeMsg, carriedRefused: number[]): boolean => {\n if (msg.mode === 'snapshot') takeGeneration(msg);\n // the op log is flushed before the seed is minted, so what it held is carried\n sync.flush();\n if (quiet()) return false;\n const s = state();\n const ps = s.seed;\n const receipts = msg.mode === 'snapshot' ? msg.receipts : undefined;\n const named = pendingEnvelopes(s)\n .filter(\n (env) =>\n env.version !== ps?.version &&\n !!receipts &&\n receiptsHold(receipts, env.origin, env.version),\n )\n .map((env) => env.version);\n const group: JournalRecord[] = [\n adoptedRec(msg, msg.mode === 'snapshot' ? [] : undefined),\n ...named.map((v) => ackedRec(v, true)),\n ];\n const psBind = ps ? entryOf(s, ps.version)?.bind : undefined;\n const same = !!ps && psBind?.instance === msg.instance && !otherVersion(ps);\n sync.adopt(msg.instance);\n if (!same) {\n if (ps) group.push(judged(ps.version, 'superseded'));\n // a write a snapshot of a room that is not empty removed from the store is not held by the\n // store, so the new seed neither holds nor lists it: it is discarded\n const pending = pendingEnvelopes(s)\n .map((env) => env.version)\n .filter((v) => v !== ps?.version && !named.includes(v));\n for (const v of pending)\n if (outOfStore.has(v)) group.push(judged(v, 'discarded'));\n const tail = pending.filter((v) => !outOfStore.has(v));\n // only a live session carries conflicts: what this boot took off the wire, and what a seed it\n // minted carried (pending and superseded now, or lost with its conflicts still hidden)\n const lostHidden = lostConflictsHidden(s);\n const oldKey =\n ps?.version ?? (lostHidden.length ? s.lost?.version : null);\n const replacedOld = !!ps && replacedFor.has(ps.version);\n const old =\n oldKey != null && !replacedOld && seededHere.has(oldKey)\n ? ps\n ? ps.conflicts\n : (s.lost?.conflicts ?? [])\n : [];\n const conflicts = [...new Set([...old, ...carriedRefused])];\n const env = mintSeed();\n if (!env) return false;\n ingestOwn(env);\n seededHere.add(env.version);\n group.push({\n k: 'seed',\n env,\n carried: tail,\n conflicts,\n ...(opt.schemaVersion !== undefined\n ? { schema: opt.schemaVersion }\n : {}),\n });\n }\n return submitInstall(msg, group);\n };\n\n /**\n * An install of a welcome of a room that is not empty, as one group: `adopted`; `acked` for every\n * pending write the receipts name; `judged` for every write that will not continue. A snapshot\n * replaces the store with its registers and replays exactly the writes that continue.\n */\n const install = (msg: WelcomeMsg): boolean => {\n const s = state();\n const snapshot = msg.mode === 'snapshot';\n const registers = snapshot ? takeGeneration(msg) : undefined;\n const receipts = snapshot ? msg.receipts : undefined;\n const named = (v: number): boolean =>\n !!receipts && !!journalOrigin && receiptsHold(receipts, journalOrigin, v);\n const acks: JournalRecord[] = [];\n const verdicts: JournalRecord[] = [];\n let skip = new Set<number>();\n // a seed lost to the relay meets a welcome that is not empty: the store is replaced, so what it\n // carried and the writes recorded behind it are discarded here, receipts first\n const lost = lostParked(s);\n for (const v of lost)\n if (named(v)) acks.push(ackedRec(v, true));\n else verdicts.push(judged(v, 'discarded'));\n if (lost.length) skip = new Set(lost);\n // a pending seed meets a welcome that is not empty: named by the receipts it was admitted (the\n // writes after it go on as ordinary pending writes of its generation); of its own instance and\n // version it is contested and stays pending with what it parks; otherwise it is fenced\n const ps = s.seed;\n if (ps) {\n const parked = parkedOf(s);\n const unnamed = parked.filter((v) => !named(v));\n const bind = entryOf(s, ps.version)?.bind;\n if (named(ps.version)) {\n for (const r of seedAcked(ps, true))\n (r.k === 'acked' ? acks : verdicts).push(r);\n skip = new Set([ps.version, ...ps.carried]);\n } else if (bind?.instance === msg.instance && !otherVersion(ps)) {\n skip = new Set([ps.version, ...unnamed]);\n // a snapshot of a room that is not empty replaces the store outright: the seed and what it\n // parks are not replayed over it\n if (snapshot) {\n replacedFor.add(ps.version);\n for (const v of unnamed) outOfStore.add(v);\n }\n } else {\n verdicts.push(\n judged(ps.version, 'fenced'),\n ...unnamed.map((v) => judged(v, 'discarded')),\n );\n skip = new Set([ps.version, ...unnamed]);\n }\n }\n const ctx = gen ? coverContext(gen, admission) : undefined;\n const target = {\n lineage: msg.lineage,\n instance: msg.instance,\n index: msg.index,\n replayBase: msg.replayBase,\n };\n const replay: OpEnvelope[] = [];\n // the pending tail in causal order: what the receipts name is acknowledged, the rest goes on\n const tail = trimByReceipts(\n s.entries.filter((e) => e.verdict === null && !skip.has(e.env.version)),\n receipts ?? {},\n );\n for (const e of tail.trimmed) acks.push(ackedRec(e.env.version, true));\n for (const e of tail.keep) {\n const env = e.env;\n const v = env.version;\n const b = e.bind ?? target;\n // the pre-check gates a handoff into a newer generation: a write already handed into this\n // instance on this connection is inside it, and the relay's answer to that copy is on its way\n if (b.instance !== msg.instance && !sent.has(sentMark(v, msg.instance))) {\n if (!eligible(b, target)) {\n verdicts.push(judged(v, 'discarded'));\n continue;\n }\n if (ctx && uncoveredCites(cover, ctx, env).length) {\n verdicts.push(judged(v, 'uncovered'));\n continue;\n }\n }\n if (snapshot) ingestOwn(env);\n replay.push(env);\n }\n const evidence = registers ? ownEpochs(registers, sync.origin) : undefined;\n if (!submitInstall(msg, [adoptedRec(msg, evidence), ...acks, ...verdicts]))\n return false;\n sync.adopt(msg.instance);\n if (snapshot && registers) hydrateWith(registers, msg.wm, replay);\n return true;\n };\n\n // a snapshot welcome of the held lineage that would install an earlier state: an older generation,\n // or the installed one older than its snapshot or than traffic already delivered. Before this boot\n // installed anything only the generation the journal holds is compared. Another lineage is a room\n // created anew, never fenced\n const earlierState = (msg: SnapshotWelcome): boolean => {\n const held = state().gen;\n if (!held || held.lineage !== msg.lineage) return false;\n const verdict = welcomeVerdict(\n gen\n ? { index: gen.index, instance: gen.instance, seq: gen.seq, maxSeq }\n : { index: held.index, instance: held.instance, seq: 0, maxSeq: 0 },\n msg,\n );\n return verdict === 'stale' || verdict === 'older-than-traffic';\n };\n\n const handle = (msg: ServerMsg): void => {\n if (msg.room !== opt.room) return;\n // a hook can close or clear the session, so it is asked again after each one\n const t = transport;\n const gone = (): boolean => quiet() || transport !== t;\n switch (msg.t) {\n case 'welcome': {\n const fenced = msg.mode === 'snapshot' && earlierState(msg);\n // an echoed id this connection did not issue, or that was answered before, is dropped: the\n // welcome is then handled as one sent unprompted. A fenced welcome answers no hello\n const rid =\n !fenced && validRid(msg.rid) && asked.has(msg.rid)\n ? msg.rid\n : undefined;\n if (rid !== undefined) {\n schedule.clear(asked.get(rid));\n asked.delete(rid);\n answeredId = Math.max(answeredId, rid);\n }\n // a room whose data shape is newer than this client's: the session ends before anything of\n // the welcome is installed\n if (\n opt.schemaVersion !== undefined &&\n msg.schemaVersion > opt.schemaVersion\n )\n return outdated();\n peers = new Map(msg.peers.map((p) => [p.origin, p]));\n hooks.onPeers?.(peers);\n members = [\n ...new Set(msg.members.filter((origin) => origin !== sync.origin)),\n ];\n hooks.onMembers?.(members);\n // nothing of an earlier state is installed: it records nothing, teaches no sequence and\n // pays no debt\n if (fenced || gone()) return;\n const heldBefore = heldInstance();\n const snapshot = msg.mode === 'snapshot';\n // a non-snapshot welcome of an instance this boot holds no state of cannot be used: the\n // handshake is suspended (nothing is sent, acked or judged) until a snapshot installs\n if (!snapshot && (suspended || lastInst !== msg.instance)) {\n suspended = true;\n welcomedHere = false;\n installed = null;\n if (status !== 'reconnecting') setStatus('reconnecting');\n raiseOwed();\n release();\n return;\n }\n // the refused writes whose effect is still in the store, read before anything below clears them\n const carriedRefused = [...inStore];\n seedHeld = null;\n lastInst = msg.instance;\n lastSeq = msg.seq;\n lastEmpty = msg.empty;\n known({\n lineage: msg.lineage,\n instance: msg.instance,\n index: msg.index,\n });\n if (snapshot && rid !== undefined && rid > owedAfter) owed = false;\n // every installed snapshot of a room that is not empty replaces the store and so removes the\n // refused effects, prompted or not; an empty one removes nothing\n if (snapshot && !msg.empty) inStore.clear();\n askSnapshot();\n knownEmpty = msg.empty;\n if (msg.instance !== heldBefore) {\n // a new generation starts with nobody pressed, and with no traffic of its own yet\n pressed = false;\n maxSeq = 0;\n declared = { ready: false, instance: msg.instance };\n }\n // an empty welcome is a snapshot welcome first: everything above applies to it\n installing = true;\n let ok: boolean;\n try {\n ok = msg.empty ? emptyWelcome(msg, carriedRefused) : install(msg);\n } finally {\n installing = false;\n }\n if (!ok || quiet()) return;\n suspended = false;\n if (rid !== undefined) {\n // an answered hello starts both ladders again\n timedOut = 0;\n attempts = 0;\n }\n if (msg.mode === 'delta')\n for (const env of msg.envs) if (applyRemote(env)) raiseOwed();\n // a delta can end the session (a newer data shape): never revive to live\n if (quiet()) return;\n hooks.onSynced?.();\n if (snapshot) hooks.onResync?.(lastSeq);\n if (snapshot && gen && msg.instance !== announcedInst) {\n announcedInst = msg.instance;\n hooks.onGeneration?.({\n instance: gen.instance,\n index: gen.index,\n reason: gen.reason,\n policy: gen.policy,\n });\n }\n if (gone()) return;\n setStatus('live');\n if (hasPresence)\n send(t, {\n t: 'presence',\n room: opt.room,\n data: presenceData,\n });\n welcomedHere = true;\n // the relay resets every declaration at a join and at a cut\n const inst = heldInstance();\n declared = inst ? { ready: false, instance: inst } : undefined;\n declare();\n release();\n const replay = heldDirects;\n heldDirects = [];\n for (const held of replay) {\n if (gone()) return;\n hooks.onDirect?.(held);\n }\n return;\n }\n case 'env':\n // nothing of the room before this connection's welcome: the welcome carries what came before it\n if (!welcomedHere) return;\n if (applyRemote(msg.env)) raiseOwed();\n return;\n case 'presence': {\n const next = new Map(peers);\n if (msg.gone) next.delete(msg.peer.origin);\n else next.set(msg.peer.origin, msg.peer);\n peers = next;\n hooks.onPeers?.(peers);\n return;\n }\n case 'member': {\n // a leave discards what that origin sent before the welcome\n if (msg.gone)\n heldDirects = heldDirects.filter((h) => h.from !== msg.origin);\n if (members === undefined || msg.origin === sync.origin) return;\n members = msg.gone\n ? members.filter((origin) => origin !== msg.origin)\n : members.includes(msg.origin)\n ? members\n : [...members, msg.origin];\n hooks.onMembers?.(members);\n return;\n }\n case 'eject':\n if (msg.writer === opt.writer) terminal('ejected', msg.reason);\n return;\n case 'reject':\n // a later hello of this origin took the seat: a reset, and a reconnect\n if (msg.reason === 'displaced') return reset('displaced');\n // a hello older than the room's data shape\n if (msg.reason === 'schema') return outdated();\n terminal('ejected', msg.reason);\n return;\n case 'settled':\n sync.settle(msg.settled);\n cover.settle(msg.settled);\n return;\n case 'compaction':\n hooks.onCompaction?.({\n count: msg.count,\n budget: msg.budget,\n ready: msg.ready,\n });\n return;\n case 'drop':\n onDrop(msg);\n return;\n }\n };\n\n const receiveDirect = (msg: ServerDirectMsg): void => {\n // a frame version this side does not speak is refused whole: nothing else of it is read\n if (msg.v !== MESH_DIRECT_VERSION) {\n if (isDevMode() && !versionWarned) {\n versionWarned = true;\n console.warn(\n `[@mmstack/mesh] dropped a direct frame of version ${String(msg.v)}; this side speaks ${MESH_DIRECT_VERSION}`,\n );\n }\n return;\n }\n if (welcomedHere) hooks.onDirect?.(msg);\n else if (heldDirects.length < HELD_DIRECTS) heldDirects.push(msg);\n else if (isDevMode() && !heldWarned) {\n heldWarned = true;\n console.warn(\n `[@mmstack/mesh] more than ${HELD_DIRECTS} direct frames arrived before the welcome; the rest are dropped`,\n );\n }\n };\n\n // the connection is gone (closed by the transport, or reset by this client): a reconnect is\n // scheduled on the one backoff ladder\n const lost = (code: number, reason: string): void => {\n if (quiet()) return;\n transport = null;\n connected = false;\n welcomedHere = false;\n installed = null;\n forgetHellos();\n pressed = false; // a reconnect is a leave and a join: the press does not carry over\n declared = undefined;\n heldDirects = [];\n members = undefined;\n hooks.onMembers?.(members);\n setStatus('reconnecting');\n hooks.onDisconnect?.(code, reason);\n // a hook can end the session or begin a clear: no timer is left behind\n if (quiet()) return;\n const delay = Math.min(\n opt.reconnect?.maxDelayMs ?? 15_000,\n RECONNECT_BASE_MS * 2 ** attempts++,\n );\n reconnectTimer = schedule.set(\n () =>\n step(() => {\n reconnectTimer = undefined;\n connect();\n }),\n delay + Math.random() * JITTER_MS,\n );\n };\n\n // a hello timed out, the seat was taken by a later hello, or the id counter is at its limit:\n // every frame of this connection is ignored from here on\n const reset = (why: 'timeout' | 'displaced' | 'counter'): void => {\n const t = transport;\n if (!t || quiet()) return;\n for (const unsub of unsubs.splice(0)) unsub();\n t.close();\n lost(1000, why);\n };\n\n // the application's transport threw: its connection is given up and a reconnect scheduled\n const broken = (t: MeshTransport | null, why: 'transport' | 'send'): void => {\n for (const unsub of unsubs.splice(0)) unsub();\n try {\n t?.close();\n } catch {\n // the transport has failed already: its close changes nothing\n }\n lost(1006, why);\n };\n\n const connect = (): void => {\n if (quiet()) return;\n for (const unsub of unsubs.splice(0)) unsub();\n // a transport still held is closed once nothing listens to it, so its close is not a loss\n transport?.close();\n transport = null;\n let t: MeshTransport;\n try {\n t = opt.transport();\n } catch (error) {\n hooks.onCallbackError?.(error);\n return broken(null, 'transport');\n }\n // the factory can end the session or begin a clear: the new transport is not taken up\n if (quiet()) return t.close();\n transport = t;\n connected = true;\n welcomedHere = false;\n installed = null;\n sent.clear();\n helloId = firstHelloId - 1;\n firstHelloId = 1;\n answeredId = 0;\n owedAfter = 0;\n forgetHellos();\n heldDirects = [];\n // a replaced transport was welcomed, this one is not yet\n if (status === 'live') setStatus('reconnecting');\n unsubs = [\n t.onMessage((msg) =>\n arrive(() => {\n if (closed || transport !== t || msg.room !== opt.room) return;\n if (msg.t === 'direct') {\n receiveDirect(msg);\n return;\n }\n const before = ending;\n handle(msg);\n // an eject or a reject that ended the session is still handed on: it is the ending's own\n const own =\n before === null &&\n (msg.t === 'reject' || msg.t === 'eject') &&\n ending?.reason === msg.reason;\n if (told()) hooks.onMessage?.(msg);\n else if (own)\n try {\n opt.hooks.onMessage?.(msg);\n } catch (error) {\n reportTo(opt.hooks, error);\n }\n }),\n ),\n t.onClose((code, reason) =>\n arrive(() => {\n if (closed || transport !== t) return;\n lost(code, reason);\n }),\n ),\n ];\n // a boot sends nothing before its welcome\n sendHello();\n };\n\n const unsubLocal = sync.subscribe((env, ctx) =>\n step(() => {\n if (!usable()) {\n // nothing is recorded after the session ended: the write is never sent\n unsaved++;\n ackFailure ??= new Error(ending?.reason ?? 'closed');\n release();\n return;\n }\n const violation = checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n // the last sequence this client observed; it can only lag the relay's, so a rule that\n // keys off an empty room is at worst more permissive here than it is at the relay\n { seq: lastSeq, empty: lastEmpty },\n );\n if (violation) {\n // same outcome the relay's own check would produce one hop later — the emit-side\n // check is an optimization, never the enforcement\n hooks.onLocalReject?.(violation);\n terminal('ejected', violation.reason);\n return;\n }\n // the intent the engine stamped this envelope from; without one its baseline is unknown, so it\n // is never read as a bump\n const intent: Intent = ctx?.raws\n ? { raws: ctx.raws, bump: !!ctx.bump }\n : intentOf(env, () => Number.POSITIVE_INFINITY);\n const record: JournalRecord = { k: 'write', env, intent };\n if (capture) {\n capture.push(record);\n return;\n }\n ingestOwn(env);\n void submit([record]);\n }),\n );\n\n return {\n // asked while a step runs, it waits its turn in the inbox: it replaces the transport the running\n // step's message arrived on\n connect: () => arrive(connect),\n status: () => status,\n lastSeq: () => lastSeq,\n hasUnacked: () => {\n if (discarded()) return false;\n return unsaved > 0 || !settledDurably();\n },\n acked: () =>\n ending\n ? ackFailure === undefined && !discarded()\n : usable() && !outstanding(),\n snapshotOwed: () => owed,\n whenAcked: () =>\n new Promise<void>((resolve, reject) => {\n if (clearing !== null && !ending) return reject(new Error('cleared'));\n waiters.push({ resolve, reject });\n settleWaiters();\n }),\n unackedEnvs: () => {\n const d = pendingEnvelopes(durable());\n const known = new Set(d.map((e) => e.version));\n return [\n ...d,\n ...pendingEnvelopes(state()).filter((e) => !known.has(e.version)),\n ];\n },\n instance: heldInstance,\n generation: () =>\n gen && {\n instance: gen.instance,\n index: gen.index,\n reason: gen.reason,\n policy: gen.policy,\n },\n peers: () => peers,\n sendSignal: (msg) =>\n step(() => {\n if (msg.room === opt.room) send(transport, msg);\n }),\n sendDirect: (to, data) =>\n step(() => {\n send(transport, {\n t: 'direct',\n room: opt.room,\n to,\n v: MESH_DIRECT_VERSION,\n data,\n });\n }),\n setPresence: (data) =>\n step(() => {\n presenceData = data;\n hasPresence = true;\n if (status === 'live') {\n send(transport, { t: 'presence', room: opt.room, data });\n }\n }),\n conflicts,\n unstored,\n declareReady: (next) =>\n step(() => {\n pressed = next;\n declare();\n }),\n clear: () =>\n step(() => {\n if (clearing) return clearing;\n cleared = true;\n if (ending) ackFailure ??= new Error(ending.reason);\n const wipe = journal.clear();\n wipe.catch(() => undefined);\n if (ending) return wipe;\n // the session ends at the wipe's answer, through the journal's ending; until then it tells nothing\n clearing = wipe;\n const pending = waiters;\n waiters = [];\n for (const w of pending) w.reject(new Error('cleared'));\n return wipe;\n }),\n recordTogether: (fn) =>\n step(() => {\n if (capture) {\n fn();\n return;\n }\n const caught: JournalRecord[] = [];\n capture = caught;\n let threw = true;\n try {\n fn();\n sync.flush();\n threw = false;\n } catch (error) {\n // what fn left in the op log is caught too, so it is never saved\n try {\n sync.flush();\n } catch {\n // fn's error stands\n }\n throw error;\n } finally {\n capture = null;\n // never recorded, so never sent\n if (threw || !usable()) neverSaved(caught);\n else if (caught.length) {\n for (const r of caught) if (r.k === 'write') ingestOwn(r.env);\n void submit(caught);\n }\n }\n }),\n close: () =>\n step(() => {\n // after an eject the session already ended; close() only releases the engine\n if (closed) unsubLocal();\n else terminal('closed');\n // a clear begun is cut short: its promise rejects 'closed'\n if (clearing) journal.close();\n unsubChange();\n unsubEnd();\n }),\n };\n}\n","import type {\n Journal,\n JournalOptions,\n JournalTip,\n} from '@mmstack/primitives/core';\nimport {\n foldJournal,\n INITIAL_JOURNAL_STATE,\n isJournalRecord,\n isJournalState,\n type JournalRecord,\n type JournalState,\n} from './session-journal';\n\n/** The options a mesh client's journal is created with: its fold, initial state and readers. */\nexport const SESSION_JOURNAL_OPTIONS: JournalOptions<\n JournalRecord,\n JournalState\n> = {\n fold: foldJournal,\n initial: INITIAL_JOURNAL_STATE,\n isRecord: isJournalRecord,\n isState: isJournalState,\n};\n\n/**\n * Why a session's journal stopped taking records: another journal took the place it claimed\n * (`'moved'`), its sequence numbers ran out (`'exhausted'`), storage failed or the outcome of a write\n * is not known (`'storage'`, with the reason), or its clear is stored (`'cleared'`).\n */\nexport type SessionJournalEnd =\n | { readonly kind: 'storage'; readonly reason: string }\n | { readonly kind: 'moved' }\n | { readonly kind: 'exhausted' }\n | { readonly kind: 'cleared' };\n\n/**\n * The one way a mesh session reaches its journal. `state()` is the fold of everything submitted in\n * this boot on top of what was on storage at load; `durable()` is that fold up to the last group\n * announced as landed.\n */\nexport type SessionJournal = {\n /** The fold of every record submitted so far: a record counts from the moment it is submitted. */\n state(): JournalState;\n /**\n * The fold of what was on storage at load and of every group announced as landed since. It moves\n * with `landed()`, one group at a time, so it never shows a later group of a batch that is on\n * storage but not yet announced.\n */\n durable(): JournalState;\n /**\n * Folds one group into `state()` at once and records it as one group. Resolves when the group is on\n * storage; groups land, and their continuations run, in the order they were submitted. Returns null,\n * recording nothing, once the journal has ended, while it clears and after `close()`. A group that\n * cannot be folded is not recorded and ends the journal as a storage failure with the fold's reason;\n * so is a group holding a record the journal would refuse to read back at the next load, and the\n * reason names that record.\n */\n submit(group: readonly JournalRecord[]): Promise<void> | null;\n /** Whether a submitted `write` or `seed` record has not landed yet. */\n ownUnlanded(): boolean;\n /** Whether any submitted group has not landed yet. */\n inFlight(): boolean;\n /** How many groups have been submitted: a group's number is this count right after its submission. */\n submitted(): number;\n /**\n * How many groups have landed. It rises before the landing is announced through `onChange`, so a\n * group numbered n is on storage once this has reached n.\n */\n landed(): number;\n /**\n * How many submitted groups are in the journal's hands, neither landed nor rejected. It falls to\n * zero at `close()` and at the ending, before the ending is announced.\n */\n storing(): number;\n /** Why the journal stopped taking records, or null while it takes them. The first ending stands. */\n ended(): SessionJournalEnd | null;\n /** Whether `clear()` was called and the journal has neither ended nor been closed since. */\n clearing(): boolean;\n /** Called once, when the journal ends. */\n onEnd(cb: (end: SessionJournalEnd) => void): () => void;\n /**\n * Called after every submission, every landing, every group dropped by a clear, and the ending;\n * never after `close()`.\n */\n onChange(cb: () => void): () => void;\n /**\n * Discards the journal: from the call no group is taken, and the journal ends `'cleared'` once the\n * wipe is on storage. The promise resolves then, and rejects when the wipe is refused, its outcome\n * is not known, or the journal is closed first. Until it resolves a crash leaves storage as it was.\n * A second call returns the first call's promise.\n */\n clear(): Promise<void>;\n /**\n * Stops the journal at once: no group is taken from the call, nothing more is announced, and\n * `storing()` is zero. A group already in storage's hands may still be stored.\n */\n close(): void;\n /** The journal's position: the last batch it loaded or was told is stored. */\n tip(): JournalTip | null;\n};\n\nconst holdsOwnEnvelope = (r: JournalRecord): boolean =>\n r.k === 'write' || r.k === 'seed';\n\nconst describe = (r: unknown): string => {\n try {\n return JSON.stringify(r, (_k, v: unknown) =>\n typeof v === 'number' && !Number.isFinite(v) ? String(v) : v,\n );\n } catch {\n return String(r);\n }\n};\n\nconst reasonOf = (e: unknown): string =>\n e instanceof Error ? e.message : String(e);\n\n// what a reason the journal gives means for the session; null for a stop the session asked for\nconst endOf = (reason: string): SessionJournalEnd | null => {\n if (reason === 'closed' || reason === 'cleared') return null;\n if (reason === 'moved') return { kind: 'moved' };\n if (reason === 'exhausted') return { kind: 'exhausted' };\n return { kind: 'storage', reason };\n};\n\n/** Wraps a journal the caller has created with {@link SESSION_JOURNAL_OPTIONS} and loaded. */\nexport function sessionJournal(\n journal: Journal<JournalRecord, JournalState>,\n): SessionJournal {\n let mem = journal.durable();\n let dur = mem;\n let unlandedOwn = 0;\n let unlanded = 0;\n let submittedCount = 0;\n let landedCount = 0;\n let end: SessionJournalEnd | null = null;\n let closed = false;\n let wipe: Promise<void> | null = null;\n // the groups in the journal's hands; emptied at once by a close and by the ending\n const holding = new Set<number>();\n const endCbs = new Set<(end: SessionJournalEnd) => void>();\n const changeCbs = new Set<() => void>();\n\n const quiet = (): boolean => closed || end !== null;\n\n const changed = (): void => {\n for (const cb of [...changeCbs]) cb();\n };\n\n const finish = (next: SessionJournalEnd): void => {\n if (quiet()) return;\n end = next;\n holding.clear();\n for (const cb of [...endCbs]) cb(next);\n changed();\n };\n\n const failedNow = (): boolean => {\n const why = journal.failed();\n const next = why === null ? null : endOf(why);\n if (next) finish(next);\n return end !== null;\n };\n\n // a stop no promise of this handle will announce: the journal's own compaction, with nothing in hand\n journal.onEnd((reason) => {\n const next = endOf(reason);\n if (next && holding.size === 0 && !wipe) finish(next);\n });\n\n return {\n state: () => mem,\n durable: () => dur,\n submit: (group) => {\n if (quiet() || wipe || failedNow()) return null;\n const unreadable = group.find((r) => !isJournalRecord(r));\n if (unreadable !== undefined) {\n finish({\n kind: 'storage',\n reason: `a record the journal could not read back: ${describe(unreadable)}`,\n });\n return null;\n }\n let next = mem;\n try {\n for (const r of group) next = foldJournal(next, r);\n } catch (e) {\n finish({ kind: 'storage', reason: reasonOf(e) });\n return null;\n }\n mem = next;\n const after = next;\n const own = group.some(holdsOwnEnvelope);\n if (own) unlandedOwn++;\n unlanded++;\n const n = ++submittedCount;\n holding.add(n);\n const landed = journal.record(group).then(\n () => {\n if (quiet()) return;\n holding.delete(n);\n if (own) unlandedOwn--;\n unlanded--;\n dur = after;\n landedCount++;\n changed();\n },\n (e: unknown) => {\n const had = holding.delete(n);\n const why = endOf(reasonOf(e));\n if (why) finish(why);\n else if (had && !quiet()) changed();\n throw e;\n },\n );\n changed();\n return landed;\n },\n ownUnlanded: () => unlandedOwn > 0,\n inFlight: () => unlanded > 0,\n submitted: () => submittedCount,\n landed: () => landedCount,\n storing: () => holding.size,\n ended: () => end,\n clearing: () => wipe !== null && !quiet(),\n onEnd: (cb) => {\n endCbs.add(cb);\n return () => endCbs.delete(cb);\n },\n onChange: (cb) => {\n changeCbs.add(cb);\n return () => changeCbs.delete(cb);\n },\n clear: () => {\n if (wipe) return wipe;\n const p = journal.clear();\n wipe = p;\n p.then(\n () => finish({ kind: 'cleared' }),\n (e: unknown) => {\n const why = endOf(reasonOf(e));\n if (why) finish(why);\n },\n );\n return p;\n },\n close: () => {\n if (closed) return;\n closed = true;\n holding.clear();\n journal.close();\n },\n tip: () => journal.tip(),\n };\n}\n","import {\n createJournal,\n diffOps,\n memoryJournalPort,\n storeJournalPort,\n type DiffOpsOptions,\n type DotFrontier,\n type Journal,\n type JournalStore,\n type JournalTip,\n type OpEnvelope,\n type OpSync,\n type StoreOp,\n} from '@mmstack/primitives/core';\nimport {\n heldConflicts,\n pendingEnvelopes,\n restoreInput,\n type JournalRecord,\n type JournalState,\n} from './session-journal';\nimport type {\n GenerationState,\n MeshConflict,\n MeshSession,\n UnstoredWrite,\n} from './session';\nimport {\n SESSION_JOURNAL_OPTIONS,\n sessionJournal,\n type SessionJournal,\n} from './session-journal-handle';\n\n// The boot both shells share: the journal opened (or a memory one in its place), its origin, the\n// boot filter, the engine restored and the edits held while it booted.\n// Nothing here touches Angular or a browser API.\n\n/** One net change made while the boot was held; an override is its own, bumped. */\nexport type HeldSegment = {\n readonly ops: readonly StoreOp[];\n readonly bump: boolean;\n};\n\n/**\n * The edits made while a boot is held: the closed, non-empty segments in write order and the value\n * the open plain segment started from. Minted once the engine exists.\n */\nexport function bootHold<T>(\n read: () => T,\n emit: DiffOpsOptions | undefined,\n): {\n start(): void;\n active(): boolean;\n /** Whether anything held is a net change. */\n written(): boolean;\n override(fn: () => void): void;\n /** Ends the hold and returns what it held. */\n take(): HeldSegment[];\n drop(): void;\n} {\n // the engine's own emit options: opSync emits arrays as units unless told otherwise\n const opts: DiffOpsOptions = { ...emit, arrays: emit?.arrays ?? 'unit' };\n const net = (from: T, to: T): StoreOp[] =>\n from === to ? [] : diffOps(from, to, opts);\n let hold: { segments: HeldSegment[]; from: T } | undefined;\n let overriding = false;\n const record = (h: { segments: HeldSegment[]; from: T }, before: T): void => {\n if (hold !== h) return; // ended inside fn: nothing is held any more\n const after = read();\n const bumped = net(before, after);\n if (!bumped.length) return; // wrote nothing: the open plain segment stays open\n const segments = [\n ...h.segments,\n { ops: net(h.from, before), bump: false },\n { ops: bumped, bump: true },\n ].filter((s) => s.ops.length > 0);\n hold = { segments, from: after };\n };\n return {\n start: () => {\n hold = { segments: [], from: read() };\n },\n active: () => hold !== undefined,\n written: () =>\n !!hold && (hold.segments.length > 0 || net(hold.from, read()).length > 0),\n override: (fn) => {\n const h = hold;\n if (!h || overriding) {\n fn();\n return;\n }\n const before = read();\n overriding = true;\n let failed = false;\n let error: unknown;\n try {\n fn();\n } catch (e) {\n failed = true;\n error = e;\n } finally {\n overriding = false;\n }\n // the writes fn made keep the override's authority, also when fn threw\n record(h, before);\n if (failed) throw error;\n },\n take: () => {\n const h = hold;\n hold = undefined;\n if (!h) return [];\n return [...h.segments, { ops: net(h.from, read()), bump: false }].filter(\n (s) => s.ops.length > 0,\n );\n },\n drop: () => {\n hold = undefined;\n },\n };\n}\n\n/** A session journal, opened, with its origin stored. */\nexport type OpenedJournal = {\n /** The handle the session is given. */\n readonly journal: SessionJournal;\n readonly origin: string;\n /** The stored journal could not be read: this boot runs over a memory journal of its own. */\n readonly unreadable: string | null;\n /** Whether the journal is held in memory: no store was given, or the stored one could not be read. */\n readonly memory: boolean;\n};\n\nconst mintOrigin = (): string => {\n const c = globalThis.crypto;\n if (c?.randomUUID) return c.randomUUID();\n if (c?.getRandomValues)\n return Array.from(c.getRandomValues(new Uint8Array(16)), (b) =>\n b.toString(16).padStart(2, '0'),\n ).join('');\n return Date.now().toString(36) + Math.random().toString(36).substring(2);\n};\n\n/** What a boot's load read. */\nexport type BootRead = {\n /** What storage holds; null when the stored journal could not be read. */\n readonly stored: JournalState | null;\n /** The stored journal could not be read, and why; this boot then runs over a memory journal. */\n readonly unreadable: string | null;\n /** Whether the journal is held in memory: no store was given, or the stored one could not be read. */\n readonly memory: boolean;\n};\n\n/** A boot's journal, opened: the handle exists from here, and its first record is beside it. */\nexport type BootOpen = OpenedJournal & {\n /**\n * Resolves once the journal holds its origin: at once when it had one, else when the record that\n * stores it is stored. Rejects with `'moved'` when that record is refused, `'exhausted'`, `'storage'`\n * when its outcome is not known, and `'closed'` when the boot ends first.\n */\n readonly born: Promise<void>;\n};\n\n/**\n * One boot of a session journal, from the removal of the old slot to the first record. It can be\n * ended at any moment, and no step is started after it has ended.\n */\nexport type SessionBoot = {\n /**\n * Resolves with what the load read. A boot ended while the load's reads are out lets them answer,\n * closes the journal unwritten, and resolves from them all the same. Rejects with `'closed'` when\n * the boot ended before any read was issued, and with `'unreadable'` when it ended while a stored\n * journal that cannot be read was being read.\n */\n readonly loaded: Promise<BootRead>;\n /**\n * Opens the loaded journal: the handle at once, and the record that stores a new origin when the\n * journal has none. Call it once, after `loaded` resolved and before `end()`.\n */\n open(): BootOpen;\n /** Ends the boot: no step is started after it, and an opened journal is closed. */\n end(): void;\n /** Whether a load's reads are out. */\n reading(): boolean;\n /** The position the boot's journal knew last: readable once the load has answered, and after `end()`. */\n tip(): JournalTip | null;\n /** The name the boot's journal writes its batches under; null before a load is issued. */\n instance(): string | null;\n};\n\n/** What a boot tells while it runs. */\nexport type SessionBootHooks = {\n /** The stored journal cannot be read, and the boot goes on over a memory journal. */\n readonly onUnreadable?: (reason: string) => void;\n};\n\nconst bornReason = (e: unknown): string => {\n const why = e instanceof Error ? e.message : String(e);\n return why === 'moved' || why === 'exhausted' || why === 'closed'\n ? why\n : 'storage';\n};\n\n/**\n * Boots the journal under `key` in `store` (a memory journal without one): removes the old client's\n * slot under `key` unread, when the store can delete, then reads the journal. Nothing is written\n * until `open()`. A stored journal that cannot be read is left untouched and this boot runs over a\n * memory journal.\n */\nexport function sessionBoot(\n outbox: { readonly store: JournalStore; readonly key: string } | undefined,\n hooks: SessionBootHooks = {},\n): SessionBoot {\n let ended = false;\n let reading = false;\n let j: Journal<JournalRecord, JournalState> | null = null;\n let handle: SessionJournal | null = null;\n let unreadable: string | null = null;\n const memory = () =>\n createJournal(memoryJournalPort(), SESSION_JOURNAL_OPTIONS);\n\n const read = async (\n journal: Journal<JournalRecord, JournalState>,\n ): Promise<boolean> => {\n j = journal;\n reading = true;\n try {\n await journal.load();\n return true;\n } catch {\n unreadable ??= journal.failed() ?? 'unreadable';\n return false;\n } finally {\n reading = false;\n if (ended) journal.close();\n }\n };\n\n const run = async (): Promise<BootRead> => {\n if (outbox) {\n const del = outbox.store.del;\n if (del) {\n try {\n await del.call(outbox.store, outbox.key);\n } catch {\n // the old slot is never read: a failure to remove it changes nothing\n }\n }\n if (ended) throw new Error('closed');\n const stored = createJournal(\n storeJournalPort(outbox.store, outbox.key),\n SESSION_JOURNAL_OPTIONS,\n );\n if (await read(stored))\n return { stored: stored.durable(), unreadable: null, memory: false };\n if (ended) throw new Error('unreadable');\n stored.close();\n hooks.onUnreadable?.(unreadable as string);\n if (ended) throw new Error('closed');\n }\n const mem = memory();\n if (!(await read(mem))) throw new Error('unreadable');\n return {\n stored: outbox ? null : mem.durable(),\n unreadable,\n memory: true,\n };\n };\n\n const loaded = run();\n return {\n loaded,\n open: () => {\n if (ended || !j || reading) throw new Error('closed');\n if (handle) throw new Error('opened');\n const journal = sessionJournal(j);\n handle = journal;\n const opened = {\n journal,\n unreadable,\n memory: !outbox || unreadable !== null,\n };\n const had = journal.state().origin;\n if (had) return { ...opened, origin: had, born: Promise.resolve() };\n const origin = mintOrigin();\n const landed = journal.submit([{ k: 'born', origin }]);\n const stop = journal.ended();\n const born = landed\n ? landed.catch((e: unknown) => {\n throw new Error(bornReason(e));\n })\n : Promise.reject(\n new Error(\n stop && stop.kind !== 'cleared' && stop.kind !== 'storage'\n ? stop.kind\n : 'storage',\n ),\n );\n return { ...opened, origin, born };\n },\n end: () => {\n if (ended) return;\n ended = true;\n if (handle) handle.close();\n else if (!reading) j?.close();\n },\n reading: () => reading,\n tip: () => j?.tip() ?? null,\n instance: () => j?.instance() ?? null,\n };\n}\n\n/**\n * Opens the journal under `key` in `store` (a memory journal without one), removes the old client's\n * slot under `key` unread, and stores a new origin when the journal has none. A stored journal that\n * cannot be read is left untouched and this boot runs over a memory journal. Rejects when the\n * origin cannot be stored.\n */\nexport async function openSessionJournal(\n outbox: { readonly store: JournalStore; readonly key: string } | undefined,\n): Promise<OpenedJournal> {\n const boot = sessionBoot(outbox);\n await boot.loaded;\n const { born, ...opened } = boot.open();\n await born;\n return opened;\n}\n\n/** Whether a journal's state holds nothing pending and no held conflict. */\nexport const holdsNothingOutstanding = (s: JournalState): boolean =>\n pendingEnvelopes(s).length === 0 && heldConflicts(s).length === 0;\n\n/**\n * Judges every restored pending write `sendable` refuses as incompatible, in one group, and returns\n * how many it judged.\n */\nexport function judgeIncompatible(\n journal: SessionJournal,\n sendable: (env: OpEnvelope) => boolean,\n): number {\n const s = journal.state();\n const origin = s.origin;\n if (!origin) return 0;\n const bad = pendingEnvelopes(s).filter((env) => !sendable(env));\n if (!bad.length) return 0;\n void journal.submit(\n bad.map((env): JournalRecord => ({\n k: 'judged',\n origin,\n version: env.version,\n verdict: 'incompatible',\n })),\n );\n return bad.length;\n}\n\n/**\n * Continues the engine from the journal and returns the frontier captured before it, which observes\n * nothing of the restored writes.\n */\nexport function restoreEngine<T>(\n sync: OpSync<T>,\n journal: SessionJournal,\n): DotFrontier {\n const observed = sync.captureFrontier();\n const r = restoreInput(journal.state());\n sync.restore(r.envs, r.highWater, undefined, r.clock);\n return observed;\n}\n\n/**\n * One write per held segment, in order, citing nothing the frontier did not observe. Given\n * `together` (a session's `recordTogether`), the writes are recorded as one group.\n */\nexport function mintHeld<T>(\n sync: OpSync<T>,\n observed: DotFrontier,\n held: readonly HeldSegment[],\n together: (fn: () => void) => void = (fn) => fn(),\n): void {\n if (!held.length) return;\n together(() =>\n sync.commitScope(observed, () => {\n for (const s of held) sync.emitOps(s.ops, { bump: s.bump });\n }),\n );\n}\n\n/** What a session shows its shell, read at each of its changes. */\nexport type SessionView = {\n readonly acked: boolean;\n readonly conflicts: readonly MeshConflict[];\n readonly unstored: readonly UnstoredWrite[];\n readonly generation: GenerationState | undefined;\n};\n\nconst conflictsKey = (list: readonly MeshConflict[]): string =>\n list.map((c) => `${c.env.version}:${c.cause}`).join(',');\nconst unstoredKey = (list: readonly UnstoredWrite[]): string =>\n list.map((u) => `${u.env.version}:${u.reason}`).join(',');\nconst sameGeneration = (\n a: GenerationState | undefined,\n b: GenerationState | undefined,\n): boolean =>\n a === b ||\n (!!a &&\n !!b &&\n a.instance === b.instance &&\n a.index === b.index &&\n a.reason === b.reason &&\n a.policy === b.policy);\n\n/** What the session shows now, keeping the previous lists and generation when they are unchanged. */\nexport const sessionView = (\n session: MeshSession,\n prev: SessionView | undefined,\n): SessionView => {\n const conflicts = session.conflicts();\n const unstored = session.unstored();\n const generation = session.generation();\n return {\n acked: session.acked(),\n conflicts:\n prev && conflictsKey(prev.conflicts) === conflictsKey(conflicts)\n ? prev.conflicts\n : conflicts,\n unstored:\n prev && unstoredKey(prev.unstored) === unstoredKey(unstored)\n ? prev.unstored\n : unstored,\n generation:\n prev && sameGeneration(prev.generation, generation)\n ? prev.generation\n : generation,\n };\n};\n","/** What a user of a lock broker does at each answer. */\nexport type LockAsk = {\n /** Told \"not available\", it keeps waiting for the lock. */\n readonly waits: boolean;\n readonly granted: () => void;\n readonly refused: () => void;\n /** The lock manager failed: the user goes on without the lock. */\n readonly broken: () => void;\n};\n\nexport type LockBrokerState =\n | 'none'\n | 'probing'\n | 'queued'\n | 'held'\n | 'returning';\n\ntype User = LockAsk & {\n readonly seq: number;\n waiter: boolean;\n ended: boolean;\n};\n\ntype Manager = Pick<LockManager, 'request'>;\n\nconst report = (e: unknown): void => {\n const r = (globalThis as { reportError?: (e: unknown) => void }).reportError;\n if (typeof r === 'function') r(e);\n else console.error(e);\n};\nconst call = (f: () => void): void => {\n try {\n f();\n } catch (e) {\n report(e);\n }\n};\n\n// One party per lock manager and name: at most one request out, never aborted, a probe first and a\n// queued request only right after a refusal; what this page itself holds or queues for, it answers.\nclass Broker {\n state: LockBrokerState = 'none';\n private req: number | null = null;\n private count = 0;\n private seqs = 0;\n private queued = false;\n private probeFor: User | null = null;\n private holder: User | null = null;\n private release: { readonly req: number; readonly go: () => void } | null =\n null;\n private readonly line: User[] = [];\n private deciding = false;\n private again = false;\n\n constructor(\n private readonly m: Manager,\n private readonly name: string,\n private readonly idle: (b: Broker) => void,\n ) {}\n\n ask(a: LockAsk): () => void {\n const u: User = { ...a, seq: ++this.seqs, waiter: false, ended: false };\n this.line.push(u);\n this.redecide();\n return () => this.end(u);\n }\n\n private end(u: User): void {\n if (u.ended) return;\n u.ended = true;\n if (this.holder === u) return this.letGo();\n const at = this.line.indexOf(u);\n if (at >= 0) this.line.splice(at, 1);\n }\n\n private letGo(): void {\n this.holder = null;\n this.giveBack();\n }\n\n private giveBack(): void {\n this.state = 'returning';\n const r = this.release;\n if (r && r.req === this.req) {\n this.release = null;\n r.go();\n }\n this.redecide();\n }\n\n private settled(): void {\n this.state = 'none';\n this.req = null;\n this.queued = false;\n this.redecide();\n }\n\n private send(u: User, ifAvailable: boolean): void {\n const req = ++this.count;\n this.req = req;\n this.queued = !ifAvailable;\n this.state = ifAvailable ? 'probing' : 'queued';\n this.probeFor = ifAvailable ? u : null;\n // its callback has run: a rejection after that is a settling, not a broken manager\n const seen = { called: false };\n let p: Promise<unknown>;\n try {\n p = this.m.request(\n this.name,\n ifAvailable\n ? { mode: 'exclusive', ifAvailable }\n : { mode: 'exclusive' },\n (lock) => this.callback(req, lock, seen),\n );\n } catch {\n return this.broke(req);\n }\n p.then(\n () => this.heard('settle', req),\n () => (seen.called ? this.heard('settle', req) : this.broke(req)),\n );\n }\n\n private callback(\n req: number,\n lock: unknown,\n seen: { called: boolean },\n ): Promise<void> | undefined {\n seen.called = true;\n if (req !== this.req) return undefined;\n if (lock === null) {\n this.heard('not', req);\n return undefined;\n }\n return new Promise<void>((go) => {\n this.release = { req, go };\n this.heard('grant', req);\n });\n }\n\n private broke(req: number): void {\n if (req !== this.req) return;\n const p = this.probeFor;\n const told = [\n ...(p && !this.line.includes(p) ? [p] : []),\n ...this.line.splice(0),\n ];\n this.probeFor = null;\n this.state = 'none';\n this.req = null;\n this.queued = false;\n const outer = this.deciding;\n this.deciding = true;\n try {\n for (const u of told)\n if (!u.ended) {\n u.ended = true;\n call(u.broken);\n }\n } finally {\n this.deciding = outer;\n }\n this.redecide();\n }\n\n private heard(what: 'grant' | 'not' | 'settle', req: number): void {\n if (req !== this.req) return;\n if (this.deciding) return this.answer(what);\n this.deciding = true;\n try {\n this.answer(what);\n } finally {\n this.deciding = false;\n }\n this.redecide();\n }\n\n // a hearing is done whole before anyone waiting is decided: an ask made by a user it calls joins the end\n private answer(what: 'grant' | 'not' | 'settle'): void {\n if (what === 'settle') return this.settled();\n const p = this.probeFor;\n this.probeFor = null;\n if (what === 'not') {\n this.state = 'none';\n this.req = null;\n if (p && !p.ended && !p.waiter) this.tellNo(p);\n const waiter = this.line.find((x) => x.waiter && !x.ended);\n if (waiter) this.send(waiter, false);\n return this.redecide();\n }\n const to = !this.queued\n ? p && !p.ended\n ? p\n : null\n : (this.line.find((x) => x.waiter && !x.ended) ?? null);\n this.queued = false;\n if (!to) return this.giveBack();\n this.give(to);\n }\n\n private give(to: User): void {\n const at = this.line.indexOf(to);\n if (at >= 0) this.line.splice(at, 1);\n this.state = 'held';\n this.holder = to;\n call(to.granted);\n this.redecide();\n }\n\n private tellNo(u: User): void {\n if (u.waits) {\n u.waiter = true;\n const at = this.line.findIndex((x) => x.seq > u.seq);\n this.line.splice(at < 0 ? this.line.length : at, 0, u);\n }\n call(u.refused);\n }\n\n private redecide(): void {\n if (this.deciding) return void (this.again = true);\n this.deciding = true;\n try {\n do {\n this.again = false;\n this.pass();\n } while (this.again);\n } finally {\n this.deciding = false;\n }\n // nothing at the manager and nobody to serve: a late hearing of an old request changes nothing\n if (this.state === 'none' && !this.holder && this.line.length === 0)\n this.idle(this);\n }\n\n private pass(): void {\n for (const u of [...this.line]) {\n if (!this.line.includes(u)) continue;\n if (u.ended) {\n this.line.splice(this.line.indexOf(u), 1);\n continue;\n }\n if (u.waiter) {\n if (this.state === 'none') this.send(u, true);\n continue;\n }\n const held = !!this.holder && !this.holder.ended;\n if (held || this.state === 'queued') {\n this.line.splice(this.line.indexOf(u), 1);\n this.tellNo(u);\n } else if (this.state === 'none') {\n this.line.splice(this.line.indexOf(u), 1);\n this.send(u, true);\n }\n }\n }\n}\n\n// one table per lock manager object: where the runtime has one lock manager for the whole process\n// (Node has one), every handle in that process is a handle of one page to it\nconst brokers = new WeakMap<object, Map<string, Broker>>();\n\nconst forget = (m: Manager, name: string, b: Broker): void => {\n const byName = brokers.get(m);\n if (byName?.get(name) !== b) return;\n byName.delete(name);\n if (byName.size === 0) brokers.delete(m);\n};\n\nconst brokerOf = (m: Manager, name: string): Broker => {\n let byName = brokers.get(m);\n if (!byName) brokers.set(m, (byName = new Map()));\n let b = byName.get(name);\n if (!b)\n byName.set(name, (b = new Broker(m, name, (x) => forget(m, name, x))));\n return b;\n};\n\n/**\n * Asks for the exclusive lock `name` of `locks`, through the one broker this page has for that\n * lock manager and name. Returns the user's one act: end (let go of the lock, or stop waiting).\n */\nexport const askLock = (\n locks: Manager,\n name: string,\n ask: LockAsk,\n): (() => void) => brokerOf(locks, name).ask(ask);\n\n/** The lock names `locks` has a broker for; a broker with nothing out and nobody to serve is forgotten. */\nexport const lockBrokerNames = (locks: Manager): readonly string[] => [\n ...(brokers.get(locks)?.keys() ?? []),\n];\n\n/** The state of the broker for `locks` and `name` (`'none'` when there is none). */\nexport const lockBrokerState = (\n locks: Manager,\n name: string,\n): LockBrokerState => brokers.get(locks)?.get(name)?.state ?? 'none';\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n runInInjectionContext,\n signal,\n untracked,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport {\n checkEnvelope,\n type IceServer,\n type OpPolicy,\n type PresenceState,\n type PrincipalCtx,\n type ServerDirectMsg,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n createJournal,\n forkStore,\n OP_PROTO_VERSION,\n opSync,\n registerResource,\n storeJournalPort,\n validateEnvelope,\n type DiffOpsOptions,\n type DotFrontier,\n type ForkStoreOptions,\n type Journal,\n type JournalStore,\n type JournalTip,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSync,\n type ResourceLike,\n type SyncedFork,\n type WritableSignalStore,\n} from '@mmstack/primitives/core';\nimport {\n meshSession,\n type CompactionState,\n type GenerationState,\n type MeshConflict,\n type MeshDirect,\n type MeshSession,\n type MeshStatus,\n type UnstoredWrite,\n} from './session';\nimport {\n bootHold,\n holdsNothingOutstanding,\n judgeIncompatible,\n mintHeld,\n restoreEngine,\n sessionBoot,\n sessionView,\n type BootRead,\n type OpenedJournal,\n type SessionBoot,\n type SessionView,\n} from './session-boot';\nimport {\n floorAt,\n type JournalRecord,\n type JournalState,\n} from './session-journal';\nimport {\n SESSION_JOURNAL_OPTIONS,\n type SessionJournal,\n} from './session-journal-handle';\nimport { askLock } from './lock-broker';\nimport type { MeshTransportFactory } from './transport';\nimport type { SignalingPort } from './peer-links';\n\nexport type {\n CompactionState,\n ConflictCause,\n GenerationState,\n Intent,\n MeshConflict,\n MeshDirect,\n MeshStatus,\n UnstoredReason,\n UnstoredWrite,\n} from './session';\n\nexport type MeshPeer = PresenceState;\n\n/**\n * A composed, user-facing health status for a synced store the surface that\n * turns a versioned reject from a dead socket into a speakable 'outdated' banner.\n * `'storage'`: the outbox can no longer save this handle's writes, and the session has ended and\n * sends nothing more. The reason says why: `'moved'` (another tab wrote the outbox in its place),\n * `'exhausted'` (the outbox ran out of sequence numbers) or `'storage'` (a save failed, or the\n * outcome of a write is not known: it is reported neither as saved nor as lost). A first read of\n * the outbox that fails does not end the handle; see `outboxUnreadable`.\n */\nexport type SyncHealthStatus =\n | 'live'\n | 'waiting'\n | 'offline'\n | 'outdated'\n | 'ejected'\n | 'degraded'\n | 'storage';\n\nexport type SyncHealth = {\n readonly status: SyncHealthStatus;\n /** Why, when the status is `outdated`/`ejected`/`degraded`/`storage`. */\n readonly reason?:\n | 'proto'\n | 'policy-version'\n | 'schema'\n | 'quota'\n | 'worker'\n | 'storage'\n | 'moved'\n | 'exhausted'\n | (string & {});\n /** `Date.now()` of the last successful sync (welcome or applied env). */\n readonly lastSyncedAt?: number;\n /**\n * How many groups of this handle's writes are in storage's hands and not yet saved. Nothing times\n * out: a store that never answers keeps it above zero until the handle closes.\n */\n readonly storing: number;\n /**\n * Saved offline writes this boot cannot send: written under another writer, protocol version or\n * policy version, malformed, or rejected by the room policy. They are never sent; each is listed\n * in `unstored` with the reason `'incompatible'`.\n */\n readonly droppedOfflineWrites?: number;\n /**\n * The saved outbox could not be read: it is in a format this build cannot read, or the store\n * failed the read. It is left as it is, and this boot's writes are kept in memory only, under an\n * origin of their own, until the handle closes. The handle runs live over memory, and its\n * health does not turn `'storage'` for this.\n */\n readonly outboxUnreadable?: true;\n /**\n * Received envelopes rejected as malformed by the deterministic well-formedness check (a bad id\n * or path segment, a non-integer version, an unknown op kind, a negative epoch, forged cites, a\n * root delete). Direct peer-to-peer rooms are trust-full for authority, so this is a peer's line\n * against a malformed neighbor; through a relay these are also rejected at the relay.\n */\n readonly droppedInvalidEnvelopes?: number;\n};\n\n// a versioned reject means \"your build is behind\" → prompt an update, not a dead socket\nconst OUTDATED_REASONS: ReadonlySet<string> = new Set([\n 'proto',\n 'policy-version',\n 'schema',\n]);\n\nexport type MeshSyncOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent:\n * whole-value adds, as before. A per-path `added` predicate keeps chosen collections leafy (so\n * concurrent first writers merge) while their entries stay one atomic `set`.\n */\n readonly emit?: DiffOpsOptions;\n /** Emit-side validation, symmetric with the relay's (tripwire honesty). */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal, so a shared policy evaluates identically on both sides. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n /**\n * The room's shared configuration pin, checked at hello against the relay's. Bump it\n * together whenever anything peers must agree on changes: the write policy, and just as\n * importantly the merge/fold configuration (`policies`). Peers folding the same register\n * state with different rules read different values, so one room means one fold config; a\n * client pinned to an older version is rejected `policy-version` and surfaces `outdated`.\n */\n readonly policyVersion?: number;\n /** The data shape this client speaks. Older-than-room → `outdated`, and a\n * newer-schema migration envelope arriving mid-session flips this client to `outdated` too. */\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * How long a hello may go unanswered before the connection is closed and opened again:\n * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to\n * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A hello that goes\n * unanswered also counts as a failed attempt for the reconnect backoff. A relay that never\n * answers a hello within `maxTimeoutMs` leaves the client resetting the connection at that pace\n * for as long as it lasts: nothing is lost, and nothing gets through.\n */\n readonly handshake?: {\n readonly timeoutMs?: number;\n readonly maxTimeoutMs?: number;\n };\n readonly injector?: Injector;\n /** Register with the nearest transition scope so (re)connection surfaces as `pending`. */\n readonly register?: 'track' | 'suspend';\n /**\n * Called once when the handle ends by itself (`ejected`, with the reason) and when a\n * `clearOutbox()` ends it (`'cleared'`); never for `close()`. A callback that throws is reported\n * and changes nothing.\n */\n readonly onEject?: (reason: string) => void;\n /**\n * The connection dropped and a reconnect is scheduled; `code` is the close code (1009 = message\n * too big, 1006 = dropped). The client also closes a connection itself, with code 1000 and the\n * reason `'timeout'` (a hello went unanswered), `'displaced'` (a later connection of this client\n * took its place) or `'counter'` (the connection used up its request ids). A transport factory or\n * a `send` that throws is reported and loses the connection, with code 1006 and the reason\n * `'transport'` or `'send'`.\n */\n readonly onDisconnect?: (code: number, reason: string) => void;\n /**\n * Hold the connection until the local base is assembled. `meshSync` awaits this before it connects\n * (and before it restores an `outbox`), so a store hydrated from another source first (a worker\n * graph, a disk snapshot) is in place when the room welcome arrives and rebases pending on top.\n * The status stays `connecting` while it is pending. A rejection is treated as ready, so a base\n * that fails to load never wedges the connection.\n */\n readonly whenReady?: () => PromiseLike<void> | void;\n /**\n * Keep this client's own writes in `store` under `key`, so offline writes survive a reboot, not\n * just a live reconnect. Every write is saved before it is sent, and every answer about it is\n * saved before it shows, so a crash at any moment loses nothing that was sent. On boot the saved\n * writes that are still pending are restored and sent again, unchanged, after the next welcome.\n * The saved outbox also keeps this client's origin, so every boot that reads it continues as the\n * same client. Without an outbox, writes are kept in memory only and each boot has an origin of\n * its own.\n *\n * The store is a `JournalStore` (build one over idb-keyval's shape with `journalStore`). Two\n * keys are written, `<key>:log` and `<key>:snap`. A value saved under `key` itself by an earlier\n * version of this library is deleted unread at each boot, when the store can delete.\n *\n * Storage decides between tabs: when another tab has written the outbox in this handle's place,\n * this handle ends `ejected` with the reason `'moved'`. A write it had not saved by then is not\n * saved, and no other tab can send it: `acked` reads `false` and `whenAcked()` rejects, and the\n * application decides what to do with it. A Web Lock on `key` keeps live tabs from taking each\n * other's place; `crossTab` sets what a tab that did not get the lock does. Within one page, a handle\n * made in the turn another handle over the same key was closed takes over from it (unless another\n * tab asked for the lock first). A handle made while another handle of this page over the\n * same key is still open is treated as a second tab would be: `'queue'` waits for it, `'ephemeral'`\n * runs over memory for its life. So close the old handle first. Two copies of this library in one\n * page behave as two tabs. Store writes made while the boot\n * waits (for the lock or the read) are held in memory and sent, as their net change, when the tab\n * boots. Nothing times out: a store call that never answers keeps the handle live and holding the\n * lock, and `health().storing` above zero, until it closes.\n */\n readonly outbox?: {\n readonly key: string;\n readonly store: JournalStore;\n /**\n * What a tab does when another tab holds the lock for `key`.\n * `'queue'` (default): it WAITS (`status` reads `'waiting'`) and takes over when the owner\n * closes; store writes made while it waits are sent, as their net change, when it takes over.\n * `'ephemeral'`: it runs live at once, as a client of its own, and never touches the saved\n * outbox: its writes live in memory only and are lost if that tab ends before the room\n * acknowledges them. It stays ephemeral for life, also after the owner leaves. When the lock is\n * free both behave the same (take it, restore, save).\n * A `'queue'` handle closed while it waits for another tab keeps its place in the browser's lock\n * queue until its turn; then the lock is taken and given back at once. Until then a new handle\n * of this page is treated as it would be while that other tab holds the lock.\n * `'off'` skips the lock: every tab that opens the key continues the same saved client, and\n * when two tabs write it, one of them ends `ejected` with the reason `'moved'`. Without the\n * lock a tab that has only read the outbox does not keep another tab's `clearOutbox()` from\n * wiping what it is about to send. In development mode it warns once.\n */\n readonly crossTab?: 'queue' | 'off' | 'ephemeral';\n };\n};\n\n/**\n * The authority surface of a peer's op-sync, for callers that compose over a seat rather than\n * inside it: `override` for authority-bumped writes (`rebalanceContainer`, an owner's\n * authoritative commit), `captureFrontier` + `commitScope` for a commit that cites what was\n * observed earlier (a fork whose base is kept elsewhere), `liveUnder` / `liveAt` to read live\n * registers and `appliedFrontier` for the observation vector they are compared against (a\n * conflict projection: \"did the writer see this sibling\", answered by causality, never by order).\n * Deliberately narrow: no `receive`, `flush`, or `destroy` — those stay the seat's own.\n */\nexport type SeatSync<T = unknown> = Pick<\n OpSync<T>,\n | 'override'\n | 'captureFrontier'\n | 'commitScope'\n | 'liveUnder'\n | 'liveAt'\n | 'appliedFrontier'\n>;\n\nexport type MeshSyncRef<T extends object = Record<string, unknown>> = {\n readonly status: Signal<MeshStatus>;\n /**\n * This client's origin: the saved outbox's, the same on every boot that reads it, or one of its\n * own for a boot without a saved outbox. Null until the outbox has loaded.\n */\n readonly origin: Signal<string | null>;\n /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */\n readonly members: Signal<readonly string[]>;\n /** Peer signaling on this session's connection; buffers up to 256 early signals until the first listener. */\n readonly signaling: SignalingPort;\n /** Composed sync-health for a user-facing surface. */\n readonly health: Signal<SyncHealth>;\n /**\n * Everything written through this handle is saved as the room's: nothing is pending or still\n * being saved and no conflict is held. The signal follows the sync engine, which takes a store\n * write up a moment later, at its next tick: read in the same turn as a write, it still gives\n * the earlier answer. `whenAcked()` counts a write made in this turn, and from that call this\n * signal counts it too. To ask whether everything is saved, including what was just written,\n * call `whenAcked()`. `false` until the outbox has\n * loaded (what is pending is not known before), while a write waits for the room or for storage,\n * while a conflict is held (until it is discarded or written again), and for good once a write\n * can no longer land: a write after an eject, or a write the emit-side policy\n * rejected. After an eject it is `true` exactly when nothing was outstanding at the ejection\n * and nothing was written since. A close freezes it: it keeps the value it had at the close,\n * and a write after the close does not change it. After a storage failure or `clearOutbox()` it\n * is `false`. Writes inside `whenReady` are the local base, not writes of their own. Writes made\n * while the boot is held (waiting for the outbox lock or its read) are saved and sent, as their\n * net change, when the boot ends; each `sync.override` made in the hold is its own authority\n * write, in order. A write the relay refused is listed in `unstored`, not here.\n */\n readonly acked: Signal<boolean>;\n /**\n * Resolves once nothing written through this handle is outstanding and that is saved\n * (immediately if it already is). Before the outbox has loaded it waits for the load. Rejects\n * with the terminal reason if the session ends while writes are outstanding or a write can no\n * longer land (`'closed'` for writes held in a boot that is closed before it connects), with\n * `'storage'`, `'moved'` or `'exhausted'` once the outbox can no longer save, with `'cleared'`\n * after `clearOutbox()`, and with `'schema'` when this client's data shape is older than the\n * room's. While a conflict is held it rejects at once with `conflict: <cause>`; a terminal reason\n * wins. A write the relay refused rejects the calls pending when its answer is saved with\n * `refused: <reason>`; a later call does not wait for it. The barrier to await before publishing\n * something that must contain every edit; `synced()` is a connection indicator, not a save\n * barrier.\n */\n whenAcked(): Promise<void>;\n readonly peers: Signal<readonly MeshPeer[]>;\n /** Publish this client's ephemeral presence payload (cursor, section, activity…). */\n setPresence(data: unknown): void;\n /**\n * Send an ephemeral payload to one member, by origin. The relay routes it to that member only\n * and never persists it; with no connection, or `to` not in the room, it is lost.\n */\n send(to: string, data: unknown): void;\n /**\n * Listen for `direct` frames addressed to this client; returns the unsubscribe. A frame that\n * arrives with no listener is lost. Peer links on {@link MeshSyncRef.signaling} never see them.\n * A listener that throws is reported, and the others still hear the frame.\n */\n direct(cb: (msg: MeshDirect) => void): () => void;\n /**\n * Fork the synced store for isolated, reviewable edits (an agent branch, a staged change). The\n * fork observes the room as it is now; committing emits its diff citing only those observed\n * writes, so an edit that lands on the room while the fork is open stays a concurrent value the\n * merge policy decides rather than being overwritten by the commit. Call `rebase()` to re-observe\n * the room and commit on top of the latest instead. `discard()` drops the staged edits and also\n * re-observes the room, so a later commit on the same fork cites the room as it is at the discard.\n * Before the boot nothing has been observed, so a fork commit made then is a plain held write.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /**\n * Authority surface over this handle's op-sync; see {@link SeatSync}. It is one object for the\n * handle's life: taken before the boot, it works over the engine once the outbox has loaded.\n * When the callback of `override` throws, the error reaches the caller and the writes it made are\n * still sent with the override's authority, also while the boot is held. Before the boot nothing\n * has been observed, so a `commitScope` run then is a plain held write.\n */\n readonly sync: SeatSync<T>;\n /**\n * Writes that will never be admitted as they stand: a write a compaction cut could not replay\n * (it cites something the cut folded away) or one the relay refused. Each offers `discard()` or\n * `reauthor()` (write its values again, citing the current state). Saved with the outbox: a\n * conflict stays listed across reboots until it is answered.\n */\n readonly conflicts: Signal<readonly MeshConflict[]>;\n /**\n * Own writes that are not in the room and never will be, in the order they were made: refused by\n * the relay, discarded with a room generation, or saved offline and no longer sendable by this\n * boot (`'incompatible'`). Each entry holds the write, so it can be offered again, its reason, and\n * `dismiss()`, which removes it. An entry is listed once its answer is saved and stays listed\n * across reboots until its dismissal is saved. Empty before the outbox has loaded.\n */\n readonly unstored: Signal<readonly UnstoredWrite[]>;\n /** The room's compaction state as the relay last announced it; undefined before any notice. */\n readonly compaction: Signal<CompactionState | undefined>;\n /**\n * The room generation this client installed: set by every snapshot welcome of a new generation\n * (a cut's welcome flips it), untouched by one of the installed generation. Undefined until the\n * first snapshot welcome of this boot.\n */\n readonly generation: Signal<GenerationState | undefined>;\n /**\n * The member pressed (`true`) or released Compact: the client declares itself ready for a\n * consensus cut whenever nothing it wrote is outstanding, re-declaring on every change. A\n * reconnect or a new generation releases it.\n */\n declareReady(pressed: boolean): void;\n /**\n * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the\n * session. From the call nothing more is sent or saved, `acked` reads `false` and `whenAcked()`\n * rejects with `'cleared'`; the handle keeps the outbox lock and its status until storage answers.\n * The session ends `closed` with the reason `'cleared'` once storage holds the wipe, and the\n * promise resolves then. It rejects with `'moved'` when another tab wrote the outbox first, with\n * `'storage'` when the outcome is not known, and with the reason of any ending that comes first\n * (`'closed'` for `close()`). A crash before it resolves leaves the outbox as it was, and the next\n * boot continues it and sends what is pending. Called before the boot has finished, it clears\n * once the boot is done, or rejects with the boot's reason.\n *\n * A handle runs over memory when it was given no `outbox`, when it is an `'ephemeral'` tab beside\n * another tab that holds the outbox, or when the saved outbox could not be read. Called while\n * such a handle is live, the clear discards this handle's own writes, resolves, and ends the\n * handle `closed` with `'cleared'`, calling `onEject('cleared')`. A saved outbox the handle never\n * held is left exactly as it is, and the next boot that can read it sends what it holds. An\n * outbox that could not be read is not removed by `clearOutbox()`: the application removes it\n * from its own store, under the key it gave, when it wants it gone.\n *\n * Called once the session has ended by itself (ejected, outdated, a storage ending), it takes the\n * outbox lock if it is free (else it rejects with `'busy'`), reads the outbox again and wipes it\n * only when no other tab has written it since this handle ended (else it rejects with `'moved'`);\n * it rejects with `'unreadable'` when the outbox cannot be read again, and with `'storage'` when\n * the store does not say whether the wipe was stored. It\n * holds the lock until storage answers, and `close()` meanwhile rejects it with `'closed'`.\n * After `close()`, and for a handle that never held the saved outbox, it rejects with\n * `'closed'`. A second call while one runs joins it.\n */\n clearOutbox(): Promise<void>;\n /**\n * Leave the room, release the outbox lock and destroy the op engine. A write made in the same\n * tick is handed to storage, before the lock is released, only when nothing of this handle is in\n * storage's hands: no earlier write still being saved, and not the record the handle saves as it\n * goes live, which storage holds for a moment as the status turns `'live'`. A write queued behind\n * anything still out is not saved. Either way nobody is told it is stored: `acked` reads `false`\n * and `whenAcked()` rejects with `'closed'`. To know that every write is saved, wait for\n * `whenAcked()`, or for `acked` to read `true`, before closing.\n * A save in storage's hands may still land after the lock is released, and storage decides\n * between it and the next tab's writes.\n * Closed while the boot is still held, the writes made in the hold are dropped: they were never\n * saved, and with a net change `acked` reads `false` and `whenAcked()` rejects with `'closed'`.\n * Without one, an outbox read in flight is let finish, writing nothing, and both answer from it:\n * nothing pending and no conflict held reads `true` and resolves; anything else, or an outbox\n * that cannot be read, reads `false` and rejects with `'closed'`. Until then `acked` is `false`\n * and `whenAcked()` waits.\n * The handle is frozen from then on: the store keeps working locally, but nothing is sent or\n * saved, and `acked`, `conflicts`, `unstored` and `generation` keep the value they had at close.\n * Destroying the injector closes it the same way.\n */\n close(): void;\n};\n\n/**\n * Reports a throw of application code: through the global `reportError` where it exists, else\n * `console.error`. A reporter that throws changes nothing.\n * @internal\n */\nexport const reportThrown = (error: unknown): void => {\n try {\n const report = (globalThis as { reportError?: (e: unknown) => void })\n .reportError;\n if (typeof report === 'function') report(error);\n else console.error(error);\n } catch {\n // the reporter's own failure is not tried again\n }\n};\n\n/**\n * Runs application code: a throw is reported once and goes no further.\n * @internal\n */\nexport const guarded = (fn: () => void): void => {\n try {\n fn();\n } catch (error) {\n reportThrown(error);\n }\n};\n\n/**\n * Hands a `direct` frame to every listener through {@link guarded}.\n * @internal\n */\nexport const deliverGuarded = (\n listeners: ReadonlySet<(msg: MeshDirect) => void>,\n msg: ServerDirectMsg,\n): void => {\n const out: MeshDirect = { from: msg.from, v: msg.v, data: msg.data };\n for (const cb of [...listeners]) guarded(() => cb(out));\n};\n\n/**\n * What a journal's stop means for a caller: the journal's own words stay, anything else is a\n * storage failure.\n * @internal\n */\nexport const shellReason = (error: unknown): string => {\n const why = error instanceof Error ? error.message : String(error);\n return why === 'moved' ||\n why === 'exhausted' ||\n why === 'closed' ||\n why === 'cleared' ||\n why === 'unreadable'\n ? why\n : 'storage';\n};\n\ntype Owed = { resolve(): void; reject(error: Error): void };\nconst owed = (): { promise: Promise<void>; owed: Owed } => {\n let o!: Owed;\n const promise = new Promise<void>((resolve, reject) => {\n o = { resolve, reject };\n });\n return { promise, owed: o };\n};\n\ntype Ending = {\n readonly status: 'closed' | 'ejected';\n readonly reason: string | undefined;\n /** The storage reason, for an ending of the journal or of the boot. */\n readonly storage: string | null;\n};\n\n// a clear after an ending: its own lock, its own fresh journal, the calls joined to it\ntype Attempt = {\n readonly owed: Owed[];\n done: boolean;\n release: (() => void) | null;\n fresh: Journal<JournalRecord, JournalState> | null;\n};\n\nconst sameTip = (a: JournalTip | null, b: JournalTip): boolean =>\n !!a && a.rank === b.rank && a.instance === b.instance;\n\n/**\n * Replicates a signal store across clients through a relay room: local writes emit stamped\n * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot\n * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.\n * A synced store reads exactly like a local one — connection state surfaces only through\n * `status` and the transition scope.\n */\nexport function meshSync<T extends object>(\n source: WritableSignal<T>,\n opt: MeshSyncOptions,\n): MeshSyncRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const status = signal<MeshStatus>('connecting');\n const origin = signal<string | null>(null);\n const members = signal<readonly string[]>([]);\n let membership: readonly string[] | undefined;\n // the last roster the links on the port were given; a socket drop blanks the session's, not this\n let roster: readonly string[] = [];\n const signalingListeners = new Set<(msg: ServerMsg) => void>();\n const directListeners = new Set<(msg: MeshDirect) => void>();\n let earlySignals: ServerMsg[] | null = [];\n // the ICE servers of the last welcome, for peer links that attach after it\n let welcomeIce: readonly IceServer[] | undefined;\n const signalMessage = (msg: ServerMsg): void => {\n if (msg.t === 'welcome') welcomeIce = msg.ice;\n if (msg.t === 'welcome' && earlySignals !== null) earlySignals = [];\n // a leave, or a join that takes over the origin on a new socket, voids what it sent before\n if (msg.t === 'member' && earlySignals !== null) {\n earlySignals = earlySignals.filter(\n (held) => held.t !== 'signal' || held.from !== msg.origin,\n );\n }\n if (\n msg.t === 'signal' &&\n earlySignals !== null &&\n earlySignals.length < 256\n ) {\n earlySignals.push(msg);\n }\n for (const cb of [...signalingListeners]) guarded(() => cb(msg));\n };\n const lastReason = signal<string | undefined>(undefined);\n const lastSyncedAt = signal<number | undefined>(undefined);\n const droppedOffline = signal(0);\n const droppedInvalid = signal(0);\n // every change of what `acked` and `health` derive from; they read the facts themselves\n const changes = signal(0);\n const changed = (): void => changes.update((n) => n + 1);\n // what the session shows, read at each of its changes; undefined until it exists\n const view = signal<SessionView | undefined>(undefined);\n const hold = bootHold(() => untracked(source), opt.emit);\n const peerMap = signal<ReadonlyMap<string, MeshPeer>>(new Map());\n const compaction = signal<CompactionState | undefined>(undefined);\n const peers = computed(() => [...peerMap().values()]);\n // a clear after the ending wipes the outbox past the session, so the view still lists them\n const conflicts = computed(() => {\n changes();\n return wiped ? [] : (view()?.conflicts ?? []);\n });\n const unstored = computed(() => {\n changes();\n return wiped ? [] : (view()?.unstored ?? []);\n });\n const generation = computed(() => view()?.generation);\n const policyVersion = opt.policyVersion ?? 0;\n const lockName = opt.outbox\n ? `@mmstack/mesh:outbox:${opt.outbox.key}`\n : undefined;\n\n // Created after the outbox has loaded: the engine mints under the outbox's origin and from its state\n let sync!: OpSync<T>;\n let session: MeshSession | undefined;\n let boot: SessionBoot | undefined;\n let handle: SessionJournal | undefined;\n let started = false;\n let destroyed = false;\n // the view keeps what it showed at close\n let frozen = false;\n let phase: 'ready' | 'lock' | 'load' | 'open' | 'run' = 'ready';\n let booting = false;\n let memory = false;\n let unreadableOutbox = false;\n let stored: JournalState | null = null;\n let ended: Ending | null = null;\n let appClosed = false;\n // ended while its load's reads were out: the waiters are answered from what the reads find\n let loadOut = false;\n let heldWrites = false;\n let closedClean: boolean | undefined;\n // why a write through this handle can no longer land, when one cannot\n let lost: string | undefined;\n let clearing = false;\n // a clear after the ending resolved: the outbox was wiped through this handle\n let wiped = false;\n let pendingPresence: { data: unknown } | undefined;\n // the boot's ask of the page's lock broker: ending it lets go of the lock, or stops waiting\n let lockAsk: (() => void) | null = null;\n let waiters: Owed[] = [];\n let queuedClears: Owed[] = [];\n let liveClears: Owed[] = [];\n let attempt: Attempt | null = null;\n // every journal this handle opened: the one it ran over, and each fresh one of a clear after it\n const ownInstances = new Set<string>();\n\n const ackedNow = (): boolean => {\n if (lost !== undefined || wiped) return false;\n if (session) return session.acked();\n if (ended) return closedClean === true;\n return (\n phase === 'open' &&\n stored !== null &&\n holdsNothingOutstanding(stored) &&\n !hold.written()\n );\n };\n const acked = computed(() => {\n changes();\n // before the session, a write into the hold changes the answer\n if (!session && !ended && phase === 'open') source();\n return ackedNow();\n });\n\n const health = computed<SyncHealth>(() => {\n changes();\n const at = lastSyncedAt();\n const dropped = droppedOffline();\n const invalid = droppedInvalid();\n const extra = {\n storing: handle?.storing() ?? 0,\n ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),\n ...(unreadableOutbox ? { outboxUnreadable: true as const } : undefined),\n ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),\n };\n const reason = lastReason();\n if (ended?.storage)\n return {\n status: 'storage',\n reason: ended.storage,\n lastSyncedAt: at,\n ...extra,\n };\n if (reason && OUTDATED_REASONS.has(reason))\n return { status: 'outdated', reason, lastSyncedAt: at, ...extra };\n switch (status()) {\n case 'live':\n return { status: 'live', lastSyncedAt: at, ...extra };\n case 'waiting':\n return { status: 'waiting', lastSyncedAt: at, ...extra };\n case 'ejected':\n return { status: 'ejected', reason, lastSyncedAt: at, ...extra };\n default: // connecting / reconnecting / closed\n return { status: 'offline', lastSyncedAt: at, ...extra };\n }\n });\n\n const refresh = (): void => {\n if (frozen || !session) return;\n view.set(sessionView(session, untracked(view)));\n changed();\n };\n\n // nothing about the status is told once the handle has ended, or while it clears\n const setStatus = (s: MeshStatus): void => {\n if (ended || clearing) return;\n status.set(s);\n changed();\n };\n\n const releaseLock = (): void => {\n const endAsk = lockAsk;\n lockAsk = null;\n endAsk?.();\n };\n\n const waitReason = (): string =>\n wiped\n ? 'cleared'\n : !ended || (ended.status === 'closed' && ended.reason === undefined)\n ? 'closed'\n : (ended.reason ?? 'closed');\n\n const answerWaiters = (): void => {\n const clean = closedClean === true && !wiped;\n for (const w of waiters.splice(0))\n if (clean) w.resolve();\n else w.reject(new Error(waitReason()));\n };\n\n // The one way a handle ends. In this order, with nothing between that waits: marked ended (the\n // first ending stands), the journal closed, the lock released or its request dropped, what callers\n // are owed settled, and only then the application told.\n const end = (\n s: 'closed' | 'ejected',\n reason: string | undefined,\n storage: string | null,\n ): void => {\n if (ended) return;\n ended = { status: s, reason, storage };\n const pre = !session;\n if (pre) {\n heldWrites = hold.written();\n hold.drop();\n loadOut = !!boot?.reading();\n if (!loadOut)\n closedClean =\n s === 'closed' &&\n reason === undefined &&\n !heldWrites &&\n (phase !== 'open' ||\n (stored !== null && holdsNothingOutstanding(stored)));\n }\n boot?.end();\n releaseLock();\n if (pre && !loadOut) answerWaiters();\n for (const c of queuedClears.splice(0))\n c.reject(new Error(reason ?? 'closed'));\n const cleared = s === 'closed' && reason === 'cleared';\n for (const c of liveClears.splice(0))\n if (cleared) c.resolve();\n else c.reject(new Error(reason ?? 'closed'));\n status.set(s);\n lastReason.set(reason);\n changed();\n if (s === 'ejected' || cleared) guarded(() => opt.onEject?.(reason ?? s));\n };\n\n // a handle ended while its load read: the reads are in, and the waiters answer from them\n const answerFromLoad = (read: JournalState | null): void => {\n if (!loadOut) return;\n loadOut = false;\n closedClean =\n ended?.status === 'closed' &&\n ended.reason === undefined &&\n !heldWrites &&\n read !== null &&\n holdsNothingOutstanding(read);\n changed();\n answerWaiters();\n };\n\n // Only a write this boot could actually get admitted is sent again: recorded under this writer,\n // on the current proto and policyVersion pins (the relay rejects a stale pin per envelope), well\n // formed, and passing the local policy, checked as the session checks each write it is handed\n // (a seed as the first write of an empty room).\n const sendable = (env: OpEnvelope): boolean =>\n validateEnvelope(env) === null &&\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n { seq: 0, empty: !!env.seed },\n ) === null;\n\n const beginClear = (asked: Owed[]): void => {\n liveClears.push(...asked);\n if (clearing) return;\n clearing = true;\n void (session as MeshSession).clear().catch(() => undefined);\n changed();\n };\n\n const initCore = (j: OpenedJournal): void => {\n const journal = j.journal;\n origin.set(j.origin);\n if (j.unreadable !== null && isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the saved outbox under \"${opt.outbox?.key}\" cannot be read by this build (${j.unreadable}). It is left as it is; this tab's writes are kept in memory only, as a new client, until it closes.`,\n );\n }\n const heldSegments = hold.take();\n sync = opSync(source, {\n writer: opt.writer,\n origin: j.origin,\n instance: journal.state().gen?.instance,\n policies: opt.policies,\n policyVersion,\n injector,\n emit: opt.emit,\n emissionFloor: (path) => floorAt(journal.state(), path),\n onReject: (_env, reason) => {\n droppedInvalid.update((n) => n + 1);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`,\n );\n }\n },\n });\n started = true;\n const dropped = judgeIncompatible(journal, sendable);\n if (dropped > 0) {\n droppedOffline.set(dropped);\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] ${dropped} saved offline write(s) cannot be sent by this build: recorded under a different writer, from an older protocol or policy version, malformed, or rejected by the room policy. They are listed in unstored as 'incompatible' (citations are never fabricated)`,\n );\n }\n }\n const stop = journal.ended();\n if (stop !== null) {\n const word = stop.kind === 'cleared' ? 'storage' : stop.kind;\n end('ejected', word, word);\n return;\n }\n const observed = restoreEngine(sync, journal);\n // set once this session ends: only then are the links riding on its port retired\n let sessionEnded = false;\n session = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync,\n journal,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n // the recorded raw ops re-stamped against the current registers, as one new envelope\n reauthor: (intent) => sync.emitOps(intent.raws, { bump: intent.bump }),\n reconnect: opt.reconnect,\n handshake: opt.handshake,\n hooks: {\n onOrigin: (value) => origin.set(value),\n onMembers: (value) => {\n membership = value;\n members.set(value ?? []);\n if (value !== undefined) {\n roster = value;\n return;\n }\n if (earlySignals !== null) earlySignals = [];\n // Peer links outlive a socket drop: the next welcome re-lists who is still there. A\n // borrowed port has no close of its own, so the session's end retires them here, from\n // the last roster the links saw (a drop before the close already blanked the session's).\n if (!sessionEnded) return;\n const retired = roster;\n roster = [];\n for (const peer of retired) {\n signalMessage({\n t: 'member',\n room: opt.room,\n origin: peer,\n gone: true,\n });\n }\n },\n onMessage: signalMessage,\n onDirect: (msg) => deliverGuarded(directListeners, msg),\n // an ending is told by the coordinator; the session's own word for it comes after\n onStatus: (s) => {\n if (s !== 'ejected' && s !== 'closed') setStatus(s);\n },\n onDisconnect: (code, reason) =>\n guarded(() => opt.onDisconnect?.(code, reason)),\n onSynced: () => lastSyncedAt.set(Date.now()),\n onPeers: (map) => peerMap.set(map),\n onCompaction: (state) => compaction.set(state),\n onChange: refresh,\n onTerminal: (state, reason) => {\n sessionEnded = true;\n const stopped = journal.ended();\n end(\n state,\n reason,\n stopped && stopped.kind !== 'cleared'\n ? (reason ?? 'storage')\n : null,\n );\n },\n onCallbackError: reportThrown,\n onLocalReject: (violation) => {\n lost ??= violation.reason;\n changed();\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] local write violates the room policy — not sent',\n violation,\n );\n }\n },\n },\n });\n phase = 'run';\n // a write changes `acked`, also one made after the session ended\n sync.subscribe(changed);\n refresh();\n mintHeld(sync, observed, heldSegments, session.recordTogether);\n const s = session;\n for (const w of waiters.splice(0)) s.whenAcked().then(w.resolve, w.reject);\n if (ended) return;\n if (queuedClears.length) {\n beginClear(queuedClears.splice(0));\n return;\n }\n if (pendingPresence) {\n s.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n s.connect();\n };\n\n if (opt.register) {\n const connection: ResourceLike = {\n status: computed(() => {\n const s = status();\n return s === 'connecting' || s === 'waiting'\n ? 'loading'\n : s === 'reconnecting'\n ? 'reloading'\n : s === 'ejected'\n ? 'error'\n : 'resolved';\n }),\n isLoading: computed(\n () =>\n status() === 'connecting' ||\n status() === 'waiting' ||\n status() === 'reconnecting',\n ),\n hasValue: () => true,\n };\n runInInjectionContext(injector, () =>\n registerResource(connection, { suspends: opt.register === 'suspend' }),\n );\n }\n\n const settleAttempt = (\n a: Attempt,\n ok: boolean,\n reason: string | null,\n ): void => {\n if (a.done) return;\n a.done = true;\n const release = a.release;\n a.release = null;\n release?.();\n if (ok) {\n wiped = true;\n changed();\n }\n for (const o of a.owed.splice(0))\n if (ok) o.resolve();\n else o.reject(new Error(reason ?? 'closed'));\n };\n\n // what this handle knew of the outbox stops at its journal's close; a batch at the tip written by\n // any journal this handle opened is its own\n const notMoved = (tip: JournalTip): boolean =>\n sameTip(boot?.tip() ?? null, tip) || ownInstances.has(tip.instance);\n\n const freshLoad = (a: Attempt): void => {\n const outbox = opt.outbox as { store: JournalStore; key: string };\n const fresh = createJournal(storeJournalPort(outbox.store, outbox.key), {\n ...SESSION_JOURNAL_OPTIONS,\n compactAfter: Infinity,\n });\n ownInstances.add(fresh.instance());\n a.fresh = fresh;\n fresh.load().then(\n ({ tip }) => {\n if (a.done) return;\n if (!notMoved(tip)) {\n fresh.close();\n return settleAttempt(a, false, 'moved');\n }\n fresh.clear().then(\n () => settleAttempt(a, true, null),\n (e: unknown) => settleAttempt(a, false, shellReason(e)),\n );\n },\n (e: unknown) => {\n if (a.done) return;\n fresh.close();\n settleAttempt(a, false, shellReason(e));\n },\n );\n };\n\n const clearAfterEnd = (o: Owed): void => {\n const a: Attempt = { owed: [o], done: false, release: null, fresh: null };\n attempt = a;\n const own = boot?.instance();\n if (own) ownInstances.add(own);\n const locks = globalThis.navigator?.locks;\n if (!locks) return freshLoad(a);\n // the attempt's end ends its ask (settleAttempt)\n const endAsk = askLock(locks, lockName as string, {\n waits: false,\n granted: () => freshLoad(a),\n refused: () => settleAttempt(a, false, 'busy'),\n // a broken lock manager: as with no lock manager\n broken: () => {\n if (!a.done && !a.fresh) freshLoad(a);\n },\n });\n if (a.done) endAsk();\n else a.release = endAsk;\n };\n\n // a close on an ended handle ends the clear still pending after its ending\n const endAttempt = (): void => {\n const a = attempt;\n if (!a || a.done) return;\n a.fresh?.close();\n settleAttempt(a, false, 'closed');\n };\n\n const teardown = (): void => {\n appClosed = true;\n if (session) {\n // a write made this tick reaches the journal, so the close can hand it to storage\n if (!destroyed) sync.flush();\n refresh();\n frozen = true;\n // the coordinator runs inside, unless the session has ended already\n session.close();\n } else end('closed', undefined, null);\n endAttempt();\n if (started && !destroyed) {\n destroyed = true;\n sync.destroy();\n }\n };\n\n injector.get(DestroyRef).onDestroy(teardown);\n\n // Load the outbox's journal (or a memory one), then boot under its origin. The coordinator ends\n // the boot; after every await the boot asks whether the handle has ended, and does nothing more if\n // it has.\n const runBoot = async (durable: boolean): Promise<void> => {\n if (ended || booting) return;\n booting = true;\n phase = 'load';\n const outbox =\n durable && opt.outbox\n ? { store: opt.outbox.store, key: opt.outbox.key }\n : undefined;\n memory = !outbox;\n const b = sessionBoot(outbox, {\n onUnreadable: () => {\n // a memory journal takes no place in the outbox: the lock goes to the next tab now\n memory = true;\n releaseLock();\n unreadableOutbox = true;\n changed();\n },\n });\n boot = b;\n let read: BootRead;\n try {\n read = await b.loaded;\n } catch {\n if (ended) return answerFromLoad(null);\n return end('ejected', 'storage', 'storage');\n }\n if (ended) return answerFromLoad(read.stored);\n memory = read.memory;\n stored = read.stored;\n phase = 'open';\n changed();\n if (ackedNow()) for (const w of waiters.splice(0)) w.resolve();\n const j = b.open();\n handle = j.journal;\n j.journal.onChange(changed);\n changed();\n try {\n await j.born;\n } catch (e: unknown) {\n if (ended) return;\n const why = shellReason(e);\n return end('ejected', why, why);\n }\n if (ended) return;\n initCore(j);\n };\n\n const beginConnect = (): void => {\n if (ended) return;\n phase = 'lock';\n // the lock and the outbox's read hold the boot\n hold.start();\n if (!opt.outbox) return void runBoot(false);\n const mode = opt.outbox.crossTab ?? 'queue';\n if (mode === 'off') {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] outbox crossTab:\"off\" runs without a lock: every tab that opens the key \"${opt.outbox.key}\" writes as the same client. Storage keeps the outbox whole, but when two tabs use it at once one of them ends ejected with the reason 'moved'. Make sure only one tab uses this key at a time.`,\n );\n }\n return void runBoot(true);\n }\n const locks = globalThis.navigator?.locks;\n if (!locks) {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] outbox crossTab:\"${mode}\" needs the Web Locks API (navigator.locks), unavailable here: running WITHOUT a lock ('queue' and 'ephemeral' both own the slot). Storage keeps the outbox whole, but two tabs sharing this key end one of them ejected with the reason 'moved'; coordinate ownership yourself, or set crossTab:\"off\" to silence this.`,\n );\n }\n return void runBoot(true);\n }\n // a granted lock is held until the ending (or a fallback to memory) ends the ask\n let waited = false;\n const endAsk = askLock(locks, lockName as string, {\n waits: mode === 'queue',\n granted: () => {\n if (ended) return;\n if (waited) setStatus('connecting');\n void runBoot(true);\n },\n // another tab (or another handle of this page) owns the outbox\n refused: () => {\n if (ended || booting) return;\n if (mode === 'ephemeral') return void runBoot(false);\n waited = true;\n setStatus('waiting');\n },\n // a broken lock manager: boot without a lock\n broken: () => {\n if (ended || booting) return;\n if (waited) setStatus('connecting');\n void runBoot(true);\n },\n });\n if (ended) endAsk();\n else lockAsk = endAsk;\n };\n\n if (opt.whenReady) {\n void Promise.resolve()\n .then(() => opt.whenReady?.())\n .then(\n () => beginConnect(),\n () => beginConnect(),\n );\n } else {\n beginConnect();\n }\n\n const whenAcked = (): Promise<void> => {\n if (started && !destroyed) sync.flush(); // a write made this tick counts as outstanding\n if (lost !== undefined) return Promise.reject(new Error(lost));\n if (wiped) return Promise.reject(new Error('cleared'));\n if (session) return session.whenAcked();\n if (ended && !loadOut)\n return closedClean\n ? Promise.resolve()\n : Promise.reject(new Error(waitReason()));\n if (!ended && ackedNow()) return Promise.resolve();\n // what is pending is not known before the load\n const w = owed();\n waiters.push(w.owed);\n return w.promise;\n };\n\n const clearOutbox = (): Promise<void> => {\n const o = owed();\n if (ended) {\n if (appClosed || memory || !boot?.instance())\n o.owed.reject(new Error('closed'));\n else if (attempt && !attempt.done) attempt.owed.push(o.owed);\n else clearAfterEnd(o.owed);\n } else if (session) beginClear([o.owed]);\n else queuedClears.push(o.owed);\n return o.promise;\n };\n\n return {\n status: status.asReadonly(),\n origin: origin.asReadonly(),\n members: members.asReadonly(),\n signaling: {\n members: () => membership,\n iceServers: () => welcomeIce,\n send: (msg) => session?.sendSignal(msg),\n onMessage: (cb) => {\n signalingListeners.add(cb);\n const early = earlySignals ?? [];\n earlySignals = null;\n for (const msg of early) guarded(() => cb(msg));\n return () => signalingListeners.delete(cb);\n },\n },\n health,\n acked,\n whenAcked,\n peers,\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n send: (to, data) => session?.sendDirect(to, data),\n direct: (cb) => {\n directListeners.add(cb);\n return () => directListeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(\n source as unknown as WritableSignalStore<T & Record<string, any>>,\n forkOpt,\n );\n\n let frontier: DotFrontier = started ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = started ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () =>\n started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n conflicts,\n unstored,\n compaction: compaction.asReadonly(),\n generation,\n declareReady: (pressed) => session?.declareReady(pressed),\n clearOutbox,\n sync: {\n override: (fn) => (started ? sync.override(fn) : hold.override(fn)),\n captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),\n commitScope: (frontier, fn) =>\n started ? sync.commitScope(frontier, fn) : fn(),\n liveUnder: (path) => (started ? sync.liveUnder(path) : []),\n liveAt: (path) => (started ? sync.liveAt(path) : []),\n appliedFrontier: () => (started ? sync.appliedFrontier() : {}),\n },\n close: teardown,\n };\n}\n","import { computed, signal, type Signal } from '@angular/core';\nimport { createWatch } from '@angular/core/primitives/signals';\nimport {\n checkEnvelope,\n type OpPolicy,\n type PresenceState,\n type PrincipalCtx,\n} from '@mmstack/mesh-protocol';\nimport {\n createStoreContext,\n forkStore,\n isStoreReservedKey,\n OP_PROTO_VERSION,\n opSync,\n store,\n validateEnvelope,\n type DotFrontier,\n type ForkStoreOptions,\n type DiffOpsOptions,\n type MergePolicyEntry,\n type OpLogDriver,\n type OpSync,\n type StoreOp,\n type SyncedFork,\n type toStoreOptions,\n type WritableSignalStore,\n type OpEnvelope,\n} from '@mmstack/primitives/core';\nimport {\n deliverGuarded,\n guarded,\n reportThrown,\n type SeatSync,\n} from './mesh-sync';\nimport {\n meshSession,\n type CompactionState,\n type MeshConflict,\n type MeshDirect,\n type MeshSession,\n type MeshStatus,\n type UnstoredWrite,\n} from './session';\nimport {\n bootHold,\n holdsNothingOutstanding,\n judgeIncompatible,\n mintHeld,\n restoreEngine,\n sessionBoot,\n sessionView,\n type BootOpen,\n type BootRead,\n type SessionBoot,\n type SessionView,\n} from './session-boot';\nimport { floorAt } from './session-journal';\nimport type { MeshTransportFactory } from './transport';\n\nconst microtaskDriver = (): OpLogDriver => (run) => {\n let scheduled = false;\n const watch = createWatch(\n () => run(),\n (w) => {\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n w.run();\n });\n },\n false,\n );\n watch.notify();\n return { destroy: () => watch.destroy() };\n};\n\n/** A sequenced batch of another writer's ops, delivered in relay order. */\nexport type SeatChange = {\n readonly kind: 'change';\n /** The relay's total-order stamp. Strictly increasing across `change` events between resyncs. */\n readonly seq: number;\n readonly writer: string;\n readonly ops: readonly StoreOp[];\n};\n\n/**\n * Seq continuity broke: the seat re-established state from a room snapshot (a reconnect past\n * the relay's retention, or a relay restart) without seeing the individual changes in\n * between. Anything accumulated from prior `change` events — narration buffers, cached\n * prompt prefixes — no longer extends the stream and must be rebuilt from current state.\n */\nexport type SeatResync = {\n readonly kind: 'resync';\n /** The seq the re-established state corresponds to. */\n readonly seq: number;\n};\n\nexport type SeatEvent = SeatChange | SeatResync;\n\n/** A base state provably derivable from the room's history alone — safe to cache. */\nexport type StableSnapshot<T> = {\n /** The relay seq this state is the fold of. */\n readonly seq: number;\n readonly doc: T;\n};\n\nexport type AgentSeatOptions = {\n readonly room: string;\n /** Opaque principal pseudonym — provided, never minted. One identity per seat. */\n readonly writer: string;\n readonly transport: MeshTransportFactory;\n /** Per-path merge policies for rebase/convergence (`lww` default). */\n readonly policies?: readonly MergePolicyEntry[];\n /**\n * How the seat's writes are diffed into ops (forwarded to its `opSync`; see `DiffOpsOptions`).\n * Absent: whole-value adds, as before. A per-path `added` predicate keeps chosen collections\n * leafy while each entry stays one atomic `set` (the whole-entry law the relay holds agents to).\n */\n readonly emit?: DiffOpsOptions;\n /**\n * Emit-side validation, symmetric with the relay's — an optimization, not the\n * enforcement (the relay validates every envelope regardless). A violating write is\n * never sent and ejects the seat exactly as the relay would have; the refused value\n * stays visible in the local replica for post-mortem, and `stableSnapshot` is `null`.\n */\n readonly policy?: OpPolicy;\n /** kind/claims of this principal (e.g. `{ kind: 'agent' }`), for policy evaluation. */\n readonly ctx?: Omit<PrincipalCtx, 'writer'>;\n readonly policyVersion?: number;\n readonly schemaVersion?: number;\n /** Exponential backoff cap for reconnects (default 15s; base 500ms + jitter). */\n readonly reconnect?: { readonly maxDelayMs?: number };\n /**\n * How long a hello may go unanswered before the connection is closed and opened again:\n * `timeoutMs` (default 15 000), doubled for every hello in a row that went unanswered, up to\n * `maxTimeoutMs` (default 120 000). An answered hello starts the count again. A relay that never\n * answers a hello within `maxTimeoutMs` leaves the seat resetting the connection at that pace for\n * as long as it lasts: nothing is lost, and nothing gets through.\n */\n readonly handshake?: {\n readonly timeoutMs?: number;\n readonly maxTimeoutMs?: number;\n };\n /**\n * Store context for the replica (from `createStoreContext()`). Defaults to a fresh one;\n * pass your own to share proxy caches across several seats in one process.\n */\n readonly context?: toStoreOptions;\n /**\n * Called once when the seat ends by itself (`ejected`, with the reason, an outdated data shape\n * included) and when a `clearOutbox()` ends it (`'cleared'`); never for `close()`. It is called\n * last: the seat has ended and every clear it owed has settled, so inside it `status()`,\n * `peers()`, `acked()` and `whenAcked()` answer as they do after it (`'ejected'`, or `'closed'`\n * after a clear). A callback that throws is reported and changes nothing.\n */\n readonly onEject?: (reason: string) => void;\n};\n\nexport type AgentSeat<T extends object> = {\n /** The live converging replica. Reads exactly like a local signal store. */\n readonly doc: WritableSignalStore<T & Record<string, any>>;\n status(): MeshStatus;\n peers(): readonly PresenceState[];\n /** The current document value — plain JSON-serializable data, for context assembly. */\n snapshot(): T;\n /**\n * The current document, stamped with the relay seq it is provably the pure fold of, or null\n * when that cannot be guaranteed: before the first welcome, while one of the seat's own writes\n * is still unacknowledged, and from a refused write until the snapshot that replaces it lands.\n * It stays null for good once the seat ended with writes outstanding, after an emit-side policy\n * reject, and after `close()`.\n */\n stableSnapshot(): StableSnapshot<T> | null;\n /** Run local writes and emit them to the room as one envelope, like any peer's edit. */\n write(fn: () => void): void;\n /**\n * The seat's writes that will never be admitted as they stand (a replay a compaction cut could not\n * carry, or a relay refusal), each with `discard()` and `reauthor()`.\n */\n conflicts(): readonly MeshConflict[];\n /**\n * The seat's writes that are not in the room and never will be, in the order they were made:\n * refused by the relay or discarded with a room generation. Each entry holds the write, its\n * reason and `dismiss()`, which removes it.\n */\n readonly unstored: Signal<readonly UnstoredWrite[]>;\n /** The room's compaction state as the relay last announced it; undefined before any notice. */\n readonly compaction: Signal<CompactionState | undefined>;\n /**\n * The seat pressed (`true`) or released Compact: it declares itself ready for a consensus cut\n * whenever it is connected and nothing it wrote is outstanding, re-declaring on every change. A\n * reconnect or a new generation releases it.\n */\n declareReady(pressed: boolean): void;\n /** Path-addressed write (`'a.b.c'` or segments), emitted immediately. */\n setAtPath(path: string | readonly (string | number)[], value: unknown): void;\n /**\n * The room's sequenced history as it arrives: `change` events carry another writer's ops\n * in strictly increasing seq order, so a listener may append them (narration, prompt\n * suffixes) without any diffing. A `resync` event voids that guarantee — everything\n * accumulated so far must be rebuilt from current state (take a fresh `stableSnapshot`).\n * Own writes never echo here.\n */\n changes(cb: (event: SeatEvent) => void): () => void;\n /**\n * An isolated branch for a reviewable proposal. The fork observes the room as it is now;\n * `commit()` emits its diff citing only those observed writes, so a room edit that lands\n * while the fork is open survives as a concurrent value for the merge policy to resolve\n * instead of being overwritten. `rebase()` re-observes the room; `discard()` drops the\n * staged edits and also re-observes the room, so a later commit on the same fork cites the\n * room as it is at the discard.\n */\n fork(\n opt?: ForkStoreOptions<T & Record<string, any>>,\n ): SyncedFork<T & Record<string, any>>;\n /**\n * Everything written through this seat is the room's: nothing is pending and no conflict is\n * held. It counts a write made in the same turn as the call. `false` until the seat has started\n * (a moment after it is created),\n * while a write waits for the room, while a conflict is held (until it is discarded or written\n * again), and for good once a write can no longer land: a write after an eject,\n * or a write the emit-side policy rejected. After an eject it is `true` exactly when nothing was\n * outstanding at the ejection and nothing was written since. A close freezes it: it keeps the\n * answer it had at the close, and a write after the close does not change it. After a storage\n * failure or `clearOutbox()` it is `false`. A write the relay refused is listed in `unstored`,\n * not here.\n */\n acked(): boolean;\n /**\n * Resolves once nothing written through this seat is outstanding (immediately if it already is;\n * before the seat has started it waits for the start). Rejects with the terminal reason if the\n * seat ends while writes are outstanding or a write can no longer land, and with `'cleared'`\n * after `clearOutbox()`. While a conflict is held it rejects at once with `conflict: <cause>`; a\n * terminal reason wins. A write the relay refused rejects the calls pending when it is answered\n * with `refused: <reason>`. The barrier to await before handing a result to something that must\n * contain every edit.\n */\n whenAcked(): Promise<void>;\n /**\n * Discard every write not yet in the room, every conflict and every `unstored` entry, and end the\n * seat: nothing more is sent, the status reads `'closed'`, and `whenAcked()` rejects with\n * `'cleared'`. Called before the seat has started, it clears once it has; when the start fails it\n * rejects with that reason, then and on every later call. After `close()` it rejects with\n * `'closed'`. After an eject or an outdated ending the seat's journal is already closed, as at\n * every ending, and a seat keeps nothing on storage: the call marks the seat cleared (`acked()`\n * reads `false`, `whenAcked()` rejects with `'cleared'`) and resolves at once.\n */\n clearOutbox(): Promise<void>;\n /** Publish this seat's ephemeral presence payload (e.g. `{ name, kind: 'agent' }`). */\n setPresence(data: unknown): void;\n /**\n * Send an ephemeral payload to one member, by origin. The relay routes it to that member only\n * and never persists it; with no connection, or `to` not in the room, it is lost.\n */\n send(to: string, data: unknown): void;\n /**\n * Listen for `direct` frames addressed to this seat; returns the unsubscribe. A frame that\n * arrives with no listener is lost.\n */\n direct(cb: (msg: MeshDirect) => void): () => void;\n /** Authority surface over this seat's op-sync; see {@link SeatSync}. */\n readonly sync: SeatSync<T>;\n /**\n * Leave the room and destroy the seat's op engine. The handle is frozen from then on: `doc`\n * still reads and writes locally, but nothing is sent, `acked()` and `whenAcked()` keep the\n * answer they had at close, and `stableSnapshot()` is null. Closed before the seat has started,\n * they answer once its journal has been read: with nothing written, `acked()` reads `true` and\n * `whenAcked()` resolves; until then `acked()` is `false` and `whenAcked()` waits.\n */\n close(): void;\n};\n\n/**\n * A headless mesh peer: the same replica and wire contract `meshSync` implements in the\n * browser, without Angular's injector or any browser API — for agents, server-side bridges,\n * and device writers joining a room as first-class, attributed participants. Each call is\n * one identity with its own replica; run several seats in one process for several\n * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as\n * to any human peer.\n */\nexport function agentSeat<T extends object>(\n initial: T,\n opt: AgentSeatOptions,\n): AgentSeat<T> {\n const context = opt.context ?? createStoreContext();\n const root = store(initial as T & Record<string, any>, context);\n const doc = root as unknown as WritableSignalStore<T & Record<string, any>>;\n const read = root as unknown as () => T;\n const policyVersion = opt.policyVersion ?? 0;\n\n const listeners = new Set<(event: SeatEvent) => void>();\n const directListeners = new Set<(msg: MeshDirect) => void>();\n const emit = (event: SeatEvent): void => {\n for (const cb of [...listeners]) guarded(() => cb(event));\n };\n const compaction = signal<CompactionState | undefined>(undefined);\n // what the session shows, read at each of its changes; undefined until it exists\n const view = signal<SessionView | undefined>(undefined);\n const unstored = computed(() => view()?.unstored ?? []);\n const hold = bootHold(read, opt.emit);\n let markBooted!: () => void;\n const booted = new Promise<void>((resolve) => (markBooted = resolve));\n let welcomed = false;\n // permanent states only: each makes the doc hold writes the room will never sequence\n let lostWrites = false;\n let rejectedFor: string | undefined;\n let closed = false;\n // the answer at close: from the session's view, or, closed before the start, from the read\n let frozenAcked: boolean | undefined;\n let closeCalled = false;\n // the view keeps what it showed at close\n let frozen = false;\n let bootFailure: string | undefined;\n let pendingPresence: { data: unknown } | undefined;\n type Owed = { resolve: () => void; reject: (e: Error) => void };\n let clearAtBoot: Owed[] = [];\n let liveClears: Owed[] = [];\n let clearing = false;\n // a clear after an ending resolved: what the seat wrote is discarded\n let wiped = false;\n // the session's ending, once the seat has one: the first ending stands\n let ended: { status: 'closed' | 'ejected'; reason?: string } | null = null;\n let boot: SessionBoot | undefined;\n\n let sync: OpSync<T> | undefined;\n let session: MeshSession | undefined;\n\n const refresh = (): void => {\n if (frozen || frozenAcked !== undefined || !session) return;\n view.set(sessionView(session, view()));\n };\n\n // The one way the seat's session ends, called first in the session's ending: marked ended, the\n // journal closed, the clears owed settled, and only then the application told.\n const end = (status: 'closed' | 'ejected', reason?: string): void => {\n if (ended) return;\n ended = { status, reason };\n if (session?.hasUnacked()) lostWrites = true; // no echo can arrive for them now\n boot?.end();\n const cleared = status === 'closed' && reason === 'cleared';\n for (const c of liveClears.splice(0))\n if (cleared) c.resolve();\n else c.reject(new Error(reason ?? 'closed'));\n if (status === 'ejected' || cleared)\n guarded(() => opt.onEject?.(reason ?? status));\n };\n\n const beginClear = (asked: Owed[]): void => {\n liveClears.push(...asked);\n if (clearing) return;\n clearing = true;\n void (session as MeshSession).clear().catch(() => undefined);\n };\n\n // a write the seat holds is sent only if this build can get it admitted (a memory journal\n // restores nothing, so this judges nothing; it keeps the boot the same as `meshSync`'s)\n const sendable = (env: OpEnvelope): boolean =>\n validateEnvelope(env) === null &&\n env.proto === OP_PROTO_VERSION &&\n env.writer === opt.writer &&\n env.policyVersion === policyVersion &&\n checkEnvelope(\n opt.policy,\n env,\n { ...opt.ctx, writer: opt.writer },\n opt.room,\n { seq: 0, empty: !!env.seed },\n ) === null;\n\n const start = async (): Promise<void> => {\n const b = sessionBoot(undefined);\n boot = b;\n let read: BootRead | undefined;\n let opened: BootOpen;\n // closed before the start: answered from the read, and nothing is written\n const answerClosed = (): void => {\n frozenAcked ??=\n !lostWrites &&\n read?.stored != null &&\n holdsNothingOutstanding(read.stored);\n markBooted();\n };\n try {\n read = await b.loaded;\n if (closed) return answerClosed();\n opened = b.open();\n await opened.born;\n } catch (e: unknown) {\n if (closed) return answerClosed();\n const why = e instanceof Error ? e.message : '';\n bootFailure = why === 'moved' || why === 'exhausted' ? why : 'storage';\n closed = true;\n b.end();\n hold.drop();\n for (const a of clearAtBoot.splice(0)) a.reject(new Error(bootFailure));\n markBooted();\n const reason = bootFailure;\n guarded(() => opt.onEject?.(reason));\n return;\n }\n if (closed) {\n frozenAcked =\n !lostWrites && holdsNothingOutstanding(opened.journal.state());\n b.end();\n markBooted();\n return;\n }\n const journal = opened.journal;\n const held = hold.take();\n const engine = opSync(root as never, {\n writer: opt.writer,\n origin: opened.origin,\n policies: opt.policies,\n policyVersion,\n driver: microtaskDriver(),\n emit: opt.emit,\n emissionFloor: (path) => floorAt(journal.state(), path),\n onReject: (_env, reason) => {\n console.warn(\n `[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`,\n );\n },\n }) as OpSync<T>;\n sync = engine;\n judgeIncompatible(journal, sendable);\n const observed = restoreEngine(engine, journal);\n const s = meshSession({\n room: opt.room,\n writer: opt.writer,\n transport: opt.transport,\n sync: engine,\n journal,\n policies: opt.policies,\n policy: opt.policy,\n ctx: opt.ctx,\n policyVersion,\n schemaVersion: opt.schemaVersion,\n reconnect: opt.reconnect,\n handshake: opt.handshake,\n // the recorded raw ops re-stamped against the current registers, as one new envelope\n reauthor: (intent) => engine.emitOps(intent.raws, { bump: intent.bump }),\n hooks: {\n onStatus: (st) => {\n if (st === 'live') welcomed = true;\n },\n // the session tells of an envelope only once the engine has taken it\n onRemote: (batch) => emit({ kind: 'change', ...batch }),\n onResync: (seq) => emit({ kind: 'resync', seq }),\n onDirect: (msg) => deliverGuarded(directListeners, msg),\n onCompaction: (state) => compaction.set(state),\n onChange: refresh,\n onLocalReject: (violation) => {\n rejectedFor = violation.reason; // the write stays in the replica but will never reach the room\n console.warn(\n '[@mmstack/mesh] agent seat write violates the room policy — not sent',\n violation,\n );\n },\n onTerminal: (state, reason) => end(state, reason),\n onCallbackError: reportThrown,\n },\n });\n session = s;\n refresh();\n mintHeld(engine, observed, held, s.recordTogether);\n markBooted();\n if (ended) return;\n if (clearAtBoot.length) {\n const asked = clearAtBoot;\n clearAtBoot = [];\n beginClear(asked);\n return;\n }\n if (pendingPresence) {\n s.setPresence(pendingPresence.data);\n pendingPresence = undefined;\n }\n s.connect();\n };\n hold.start();\n void start();\n\n const diverged = (): boolean =>\n lostWrites || rejectedFor !== undefined || closed;\n const flush = (): void => sync?.flush();\n\n // read from the session at each call: after an ending nothing notifies a change\n const acked = (): boolean => {\n if (!session && frozenAcked !== undefined) return frozenAcked;\n flush(); // a write made this tick counts as pending, not as unstamped\n return (\n !!session && !lostWrites && rejectedFor === undefined && session.acked()\n );\n };\n\n const whenAcked = (): Promise<void> => {\n flush();\n if (rejectedFor !== undefined)\n return Promise.reject(new Error(rejectedFor));\n if (wiped) return Promise.reject(new Error('cleared'));\n if (session) return session.whenAcked();\n if (bootFailure !== undefined)\n return Promise.reject(new Error(bootFailure));\n if (closed) {\n if (lostWrites) return Promise.reject(new Error('closed'));\n if (frozenAcked !== undefined)\n return frozenAcked\n ? Promise.resolve()\n : Promise.reject(new Error('closed'));\n }\n return booted.then(whenAcked);\n };\n\n return {\n doc,\n // from its ending the seat answers for itself: the session's own status and peers follow a moment later\n status: () =>\n ended?.status ??\n session?.status() ??\n (bootFailure !== undefined\n ? 'ejected'\n : closed\n ? 'closed'\n : 'connecting'),\n peers: () => (session && !ended ? [...session.peers().values()] : []),\n snapshot: () => read(),\n stableSnapshot: () => {\n if (!session) return null;\n flush(); // a write made this tick must count as pending, not linger unstamped\n // a held conflict is outstanding, yet retracted locally: the doc is still the room's fold\n const pending =\n session.unackedEnvs().length > 0 ||\n (session.hasUnacked() && session.conflicts().length === 0);\n if (!welcomed || diverged() || pending || session.snapshotOwed())\n return null;\n return { seq: session.lastSeq(), doc: read() };\n },\n write: (fn) => {\n fn();\n flush();\n },\n conflicts: () => view()?.conflicts ?? [],\n unstored,\n compaction: compaction.asReadonly(),\n declareReady: (pressed) => session?.declareReady(pressed),\n setAtPath: (path, value) => {\n setAtPath(doc, path, value);\n flush();\n },\n changes: (cb) => {\n listeners.add(cb);\n return () => listeners.delete(cb);\n },\n fork: (forkOpt) => {\n const f = forkStore(doc, forkOpt);\n let frontier: DotFrontier = sync ? sync.captureFrontier() : { seq: 0 };\n const recapture = (): void => {\n frontier = sync ? sync.captureFrontier() : { seq: 0 };\n };\n return {\n store: f.store,\n ops: f.ops,\n commit: () => {\n if (!sync) {\n f.commit(); // before the start nothing has been observed: a plain held write\n return;\n }\n sync.commitScope(frontier, () => f.commit());\n sync.flush();\n },\n discard: () => {\n f.discard();\n recapture();\n },\n rebase: recapture,\n };\n },\n acked,\n whenAcked,\n clearOutbox: () => {\n if (closed) return Promise.reject(new Error(bootFailure ?? 'closed'));\n if (ended && session) {\n // nothing of the seat is on storage: after an eject the session is cleared where it stands\n void session.clear().catch(() => undefined);\n wiped = true;\n // an ended session tells no change: the view is read again here\n refresh();\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n if (session) beginClear([{ resolve, reject }]);\n else clearAtBoot.push({ resolve, reject });\n });\n },\n setPresence: (data) => {\n if (session) session.setPresence(data);\n else pendingPresence = { data };\n },\n send: (to, data) => session?.sendDirect(to, data),\n direct: (cb) => {\n directListeners.add(cb);\n return () => directListeners.delete(cb);\n },\n sync: {\n override: (fn) => (sync ? sync.override(fn) : hold.override(fn)),\n captureFrontier: () => (sync ? sync.captureFrontier() : { seq: 0 }),\n commitScope: (frontier, fn) =>\n sync ? sync.commitScope(frontier, fn) : fn(),\n liveUnder: (path) => (sync ? sync.liveUnder(path) : []),\n liveAt: (path) => (sync ? sync.liveAt(path) : []),\n appliedFrontier: () => (sync ? sync.appliedFrontier() : {}),\n },\n close: () => {\n if (closeCalled) return;\n closeCalled = true;\n flush(); // a write made this tick is part of what the seat wrote\n if (bootFailure !== undefined) frozenAcked = acked();\n else if (!session) {\n if (hold.written()) {\n frozenAcked = false;\n lostWrites = true; // the held writes were never recorded\n }\n hold.drop();\n for (const a of clearAtBoot.splice(0)) a.reject(new Error('closed'));\n boot?.end();\n }\n frozen = true;\n closed = true; // sync is destroyed below: later writes are unwatched, so no more proofs\n session?.close();\n sync?.destroy();\n },\n };\n}\n\ntype PathSegment = string | number;\n\nconst parsePath = (\n path: string | readonly PathSegment[],\n): readonly PathSegment[] =>\n typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;\n\n// resolve a string segment against an array ('0' → 0) so dot-paths address list items\nconst resolveKey = (current: unknown, seg: PathSegment): PathSegment =>\n Array.isArray(current) && typeof seg === 'string' && /^\\d+$/.test(seg)\n ? Number(seg)\n : seg;\n\nfunction withPathSet(\n current: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): unknown {\n if (path.length === 0) return value;\n const [head, ...rest] = path;\n if (Array.isArray(current)) {\n const idx = typeof head === 'number' ? head : Number(head);\n const copy = [...current];\n copy[idx] = withPathSet(current[idx], rest, value);\n return copy;\n }\n const base =\n current !== null && typeof current === 'object'\n ? (current as Record<PathSegment, unknown>)\n : {};\n return { ...base, [head]: withPathSet(base[head], rest, value) };\n}\n\n/**\n * Applies `value` at a path on a signal-store node — the write shape a tool-calling model\n * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as\n * the path exists in the current value and finishes with one immutable set on the deepest\n * real node, which also covers paths that do not exist yet (a fresh record key creates it).\n * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer\n * `seat.setAtPath`, which also emits immediately.\n */\nexport function setAtPath(\n node: unknown,\n path: string | readonly PathSegment[],\n value: unknown,\n): void {\n const segs = parsePath(path);\n let cursor = node as Record<PathSegment, unknown> & {\n (): unknown;\n set(v: unknown): void;\n };\n let walked = 0;\n for (const seg of segs) {\n const current = cursor();\n if (current === null || typeof current !== 'object') break;\n const key = resolveKey(current, seg);\n // a key the node answers itself has no child node; the rest of the path is set on this value\n if (!Object.hasOwn(current, key) || isStoreReservedKey(key)) break;\n const child = cursor[key];\n if (typeof child !== 'function') break;\n cursor = child as typeof cursor;\n walked++;\n }\n const rest = segs.slice(walked);\n if (rest.length === 0) {\n cursor.set(value);\n return;\n }\n cursor.set(withPathSet(cursor(), rest, value));\n}\n\nconst MAX_VALUE_CHARS = 120;\n\nconst printable = (value: unknown): string => {\n const json = JSON.stringify(value);\n if (json === undefined) return String(value);\n return json.length > MAX_VALUE_CHARS\n ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`\n : json;\n};\n\n/**\n * One store op as a plain-English line (\"mira set plan.endDate to \\\"2026-10-11\\\"\"), for\n * activity feeds and model context. Values render as truncated JSON. Pair with a seat's\n * `changes` stream: narrating each batch's ops yields an append-only account of the room.\n */\nexport function describeOp(op: StoreOp, writer: string): string {\n const at = op.path.length === 0 ? 'the document root' : op.path.join('.');\n switch (op.kind) {\n case 'set':\n return `${writer} set ${at} to ${printable(op.next)}`;\n case 'delete':\n return `${writer} removed ${at}`;\n case 'clear':\n return `${writer} cleared ${at}`;\n }\n}\n","import { isDevMode } from '@angular/core';\nimport type {\n ClientMsg,\n PrincipalCtx,\n Relay,\n ServerMsg,\n} from '@mmstack/mesh-protocol';\n\n/**\n * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport\n * represents a single connection and never reconnects itself.\n */\nexport type MeshTransport = {\n send(msg: ClientMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n /** `code` and `reason` are the close frame's (1006 for a dropped connection, 1000 for a normal close). */\n onClose(cb: (code: number, reason: string) => void): () => void;\n close(): void;\n};\n\nexport type MeshTransportFactory = () => MeshTransport;\n\n/**\n * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and\n * flushed on open; malformed inbound frames are dropped.\n */\nexport function webSocketTransport(\n url: string,\n protocols?: string | string[],\n): MeshTransportFactory {\n return () => {\n const ws = new WebSocket(url, protocols);\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<(code: number, reason: string) => void>();\n const pending: string[] = [];\n\n ws.onopen = () => {\n for (const frame of pending.splice(0)) ws.send(frame);\n };\n ws.onmessage = (event) => {\n let msg: ServerMsg;\n try {\n msg = JSON.parse(String(event.data)) as ServerMsg;\n } catch {\n if (isDevMode()) {\n console.warn(\n '[@mmstack/mesh] dropped unparseable frame (expected JSON text)',\n );\n }\n return;\n }\n for (const cb of [...messageCbs]) cb(msg);\n };\n ws.onclose = (event) => {\n for (const cb of [...closeCbs]) cb(event.code, event.reason);\n };\n\n return {\n send: (msg) => {\n const frame = JSON.stringify(msg);\n if (ws.readyState === WebSocket.OPEN) ws.send(frame);\n else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => ws.close(),\n };\n };\n}\n\n/** A message as it reads after a JSON hop: keys holding `undefined` gone, such array slots `null`. */\nconst asJson = <T>(msg: T): T => JSON.parse(JSON.stringify(msg)) as T;\n\nexport type DirectTransportOptions = {\n /**\n * Hand the relay's messages to this peer BY REFERENCE instead of through a JSON hop. A snapshot\n * welcome then costs the peer no copy of the room's registers: its stores hold the relay's own\n * sibling objects, the same ones every other such peer holds. The peer must therefore treat\n * everything it receives as the relay's memory and never mutate it — a write in place would\n * corrupt the room for everyone. The peer's own messages still cross as JSON, so what it writes\n * reaches the relay exactly as a socket peer's would. Off by default; opt in only for a process\n * whose readers are known not to mutate what a seat materializes.\n */\n readonly byReference?: boolean;\n};\n\n/**\n * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop\n * tests, and handy for single-process demos or an SSR-side room.\n *\n * Messages cross as JSON in both directions, as they would over a socket, so a direct peer holds\n * exactly what a socket peer would. Handed over by reference, an `undefined` an emitter wrote\n * would reach relay memory where a socket peer's would have been dropped. The relay's own\n * messages may skip the hop ({@link DirectTransportOptions.byReference}): they never hold an\n * `undefined` (every value in a room arrived as JSON), so the two peers read the same state and\n * differ only in who owns the objects.\n */\nexport function directTransport(\n relay: Relay,\n ctx: PrincipalCtx,\n options: DirectTransportOptions = {},\n): MeshTransportFactory {\n const inbound = options.byReference ? <T>(msg: T): T => msg : asJson;\n return () => {\n const messageCbs = new Set<(msg: ServerMsg) => void>();\n const closeCbs = new Set<(code: number, reason: string) => void>();\n let open = true;\n\n const connection = relay.connect(\n {\n send: (msg) => {\n if (!open) return;\n const wired = inbound(msg);\n for (const cb of [...messageCbs]) cb(wired);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb(1000, '');\n },\n },\n ctx,\n );\n\n return {\n send: (msg) => {\n if (open) connection.receive(asJson(msg));\n },\n onMessage: (cb) => {\n messageCbs.add(cb);\n return () => messageCbs.delete(cb);\n },\n onClose: (cb) => {\n closeCbs.add(cb);\n return () => closeCbs.delete(cb);\n },\n close: () => {\n if (!open) return;\n open = false;\n connection.disconnect();\n for (const cb of [...closeCbs]) cb(1000, '');\n },\n };\n };\n}\n","/**\n * The per-origin lifecycle of peer links as a pure reducer. `peerLinks` feeds it every\n * membership and link event and executes the effects it returns, in order; nothing else\n * decides when a link is built, dropped or rebuilt.\n *\n * While the links are open, every listed origin is in exactly one state: `linking` (a peer, an\n * open timeout armed), `open` (a peer, every channel open, no timer) or `waiting` (no peer, a\n * rebuild timer armed). An unlisted origin has no state. After `close` nothing happens again.\n */\nexport type LinkState = 'linking' | 'open' | 'waiting';\n\nexport type LifecycleEvent =\n /** A member joined, or a waiting member's announce arrived: build now. */\n | { readonly t: 'listed'; readonly origin: string }\n | { readonly t: 'welcome'; readonly members: readonly string[] }\n | { readonly t: 'gone'; readonly origin: string }\n | { readonly t: 'opened'; readonly origin: string }\n /** A channel closed, the connector reported the link gone, or the open timeout fired. */\n | { readonly t: 'lost'; readonly origin: string }\n /** The rebuild timer fired. */\n | { readonly t: 'due'; readonly origin: string }\n | { readonly t: 'close' };\n\nexport type LifecycleEffect =\n | { readonly t: 'build'; readonly origin: string }\n | { readonly t: 'drop'; readonly origin: string }\n | { readonly t: 'armOpen'; readonly origin: string }\n | {\n readonly t: 'armRetry';\n readonly origin: string;\n readonly attempt: number;\n }\n | { readonly t: 'disarm'; readonly origin: string };\n\nexport type LinkEntry = {\n readonly state: LinkState;\n /** Losses since the link last opened. */\n readonly attempt: number;\n /** Lost at least once since it last opened. */\n readonly stalled: boolean;\n};\n\nexport type Lifecycle = ReadonlyMap<string, LinkEntry>;\n\nexport type LifecycleStep = {\n readonly next: Lifecycle;\n readonly effects: readonly LifecycleEffect[];\n};\n\n/** The starting value: nothing listed. */\nexport const emptyLifecycle: Lifecycle = new Map();\n\n/** The value after `close`; `step` recognises it by identity and ignores every later event. */\nexport const closedLifecycle: Lifecycle = new Map();\n\nconst hasPeer = (e: LinkEntry | undefined): boolean =>\n e?.state === 'linking' || e?.state === 'open';\n\nconst hasTimer = (e: LinkEntry | undefined): boolean =>\n e?.state === 'linking' || e?.state === 'waiting';\n\n/**\n * Builds now for a listed origin with no peer; keeps an existing one. The open timeout is\n * armed before the build so a link that opens while it is being built cancels it.\n */\nconst listOne = (\n s: Map<string, LinkEntry>,\n origin: string,\n effects: LifecycleEffect[],\n): void => {\n const cur = s.get(origin);\n if (hasPeer(cur)) return;\n if (cur) effects.push({ t: 'disarm', origin });\n effects.push({ t: 'armOpen', origin }, { t: 'build', origin });\n s.set(origin, {\n state: 'linking',\n attempt: cur?.attempt ?? 0,\n stalled: cur?.stalled ?? false,\n });\n};\n\nconst unlistOne = (\n s: Map<string, LinkEntry>,\n origin: string,\n effects: LifecycleEffect[],\n): void => {\n const cur = s.get(origin);\n if (!cur) return;\n if (hasPeer(cur)) effects.push({ t: 'drop', origin });\n effects.push({ t: 'disarm', origin });\n s.delete(origin);\n};\n\nconst none = (s: Lifecycle): LifecycleStep => ({ next: s, effects: [] });\n\n/** One transition. Pure and total: an event that does not apply returns `s` and no effects. */\nexport function step(s: Lifecycle, e: LifecycleEvent): LifecycleStep {\n if (s === closedLifecycle) return none(s);\n const effects: LifecycleEffect[] = [];\n const next = new Map(s);\n switch (e.t) {\n case 'listed':\n if (hasPeer(s.get(e.origin))) return none(s);\n listOne(next, e.origin, effects);\n break;\n case 'welcome': {\n const listed = new Set(e.members);\n for (const origin of s.keys())\n if (!listed.has(origin)) unlistOne(next, origin, effects);\n for (const origin of listed) listOne(next, origin, effects);\n break;\n }\n case 'gone':\n if (!s.has(e.origin)) return none(s);\n unlistOne(next, e.origin, effects);\n break;\n case 'opened': {\n const cur = s.get(e.origin);\n if (cur?.state !== 'linking') return none(s);\n next.set(e.origin, { state: 'open', attempt: 0, stalled: false });\n effects.push({ t: 'disarm', origin: e.origin });\n break;\n }\n case 'lost': {\n const cur = s.get(e.origin);\n if (!cur || !hasPeer(cur)) return none(s);\n next.set(e.origin, {\n state: 'waiting',\n attempt: cur.attempt + 1,\n stalled: true,\n });\n effects.push(\n { t: 'drop', origin: e.origin },\n { t: 'armRetry', origin: e.origin, attempt: cur.attempt },\n );\n break;\n }\n case 'due': {\n const cur = s.get(e.origin);\n if (cur?.state !== 'waiting') return none(s);\n next.set(e.origin, { ...cur, state: 'linking' });\n effects.push(\n { t: 'armOpen', origin: e.origin },\n { t: 'build', origin: e.origin },\n );\n break;\n }\n case 'close':\n for (const [origin, cur] of s) {\n if (hasPeer(cur)) effects.push({ t: 'drop', origin });\n if (hasTimer(cur)) effects.push({ t: 'disarm', origin });\n }\n return { next: closedLifecycle, effects };\n }\n return { next, effects };\n}\n\n/**\n * The wait before rebuild number `attempt` (0-based): equal jitter over a capped exponential,\n * so every delay lies in `[base / 2, base)` with `base = min(minMs * 2^attempt, maxMs)`.\n */\nexport function retryDelay(\n attempt: number,\n bounds: { readonly minMs: number; readonly maxMs: number },\n random: () => number,\n): number {\n const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);\n return base / 2 + random() * (base / 2);\n}\n","import {\n computed,\n DestroyRef,\n inject,\n Injector,\n isDevMode,\n signal,\n untracked,\n type Signal,\n} from '@angular/core';\nimport {\n MESH_PROTO_VERSION,\n type ClientSignalMsg,\n type IceServer,\n type ServerMsg,\n} from '@mmstack/mesh-protocol';\nimport {\n emptyLifecycle,\n retryDelay,\n step,\n type LifecycleEffect,\n type LifecycleEvent,\n} from './peer-lifecycle';\nimport type { MeshTransport, MeshTransportFactory } from './transport';\n\n/**\n * A data channel as the P2P engine needs it; it opens later. Peer links send only on an open\n * channel, so the contract asks for no buffering, but the channels of {@link rtcPeerConnector}\n * buffer sends made before open and flush them when the channel opens.\n */\nexport type DataChannelLike = {\n send(frame: string): void;\n onMessage(cb: (frame: string) => void): () => void;\n onOpen(cb: () => void): () => void;\n onClose(cb: () => void): () => void;\n close(): void;\n};\n\n/** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */\nexport type PeerChannelSpec = {\n readonly label: string;\n readonly ordered?: boolean;\n readonly maxRetransmits?: number;\n};\n\n/** How many signals are held for replay while a connection waits for its welcome. */\nconst HELD_SIGNALS = 256;\n\n/** The single reliable channel every link carries when no channels are asked for. */\nexport const defaultPeerChannels: readonly PeerChannelSpec[] = [\n { label: 'mmstack-mesh' },\n];\n\n/**\n * Creates one peer link. `polite` assigns the perfect-negotiation role (derived\n * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads\n * through the relay; `signal` delivers the remote side's payloads. Object payloads gain a\n * `link` field on the way out (the sending link's instance id) and, once the remote instance\n * is known, a `to` field; both are stripped before `signal` sees the payload.\n *\n * `channels` lists the labelled channels the link carries; `channel` is the first of them and\n * `channels` (by label) all of them. A connector that returns only `channel` supports a single\n * channel. Signal payloads carry no channel field: one link per remote carries every channel,\n * so nothing needs routing. The field name `ch` is kept free for a future where it does.\n *\n * `onClose`, when the connector has it, reports the link as a whole finished even if no channel\n * said so; the links then rebuild it.\n */\nexport type PeerConnector = (opt: {\n readonly remote: string;\n readonly polite: boolean;\n readonly sendSignal: (data: unknown) => void;\n readonly channels: readonly PeerChannelSpec[];\n /** ICE servers the relay issued in the last welcome, if any. */\n readonly iceServers?: readonly IceServer[];\n}) => {\n readonly channel: DataChannelLike;\n readonly channels?: Readonly<Record<string, DataChannelLike>>;\n signal(data: unknown): void;\n /** Fires once when the link as a whole is gone, whether or not its channels reported it. */\n onClose?(cb: () => void): () => void;\n close(): void;\n};\n\n/**\n * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.\n *\n * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.\n * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form\n * on one network segment. When ICE fails, or stays `disconnected` longer than\n * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before\n * the link connects again, a closed connection, or a negotiation step the browser rejects\n * reports the link gone through `onClose`.\n */\nexport function rtcPeerConnector(\n config?: RTCConfiguration,\n opt?: { readonly disconnectGraceMs?: number },\n): PeerConnector {\n const graceMs = opt?.disconnectGraceMs ?? 5000;\n return ({\n polite,\n sendSignal,\n // oxlint-disable-next-line typescript/no-useless-default-assignment -- guards untyped callers of a public connector\n channels = defaultPeerChannels,\n iceServers,\n }) => {\n const pc = new RTCPeerConnection(\n iceServers\n ? {\n ...config,\n iceServers: iceServers.map((server) => ({\n ...server,\n urls:\n typeof server.urls === 'string'\n ? server.urls\n : [...server.urls],\n })),\n }\n : config,\n );\n let makingOffer = false;\n let ignoreOffer = false;\n const goneCbs = new Set<() => void>();\n let finished = false;\n let restartTried = false;\n let grace: ReturnType<typeof setTimeout> | undefined;\n const clearGrace = (): void => {\n if (grace !== undefined) clearTimeout(grace);\n grace = undefined;\n };\n const reportGone = (): void => {\n if (finished) return;\n finished = true;\n clearGrace();\n for (const cb of [...goneCbs]) cb();\n };\n // one ICE restart per connected period; a second failure is the end of the link\n const failed = (): void => {\n if (finished) return;\n if (restartTried) return reportGone();\n restartTried = true;\n pc.restartIce();\n };\n const rejected = (step: string, err: unknown): void => {\n if (finished || pc.signalingState === 'closed') return;\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`,\n err,\n );\n }\n reportGone();\n };\n pc.oniceconnectionstatechange = () => {\n const state = pc.iceConnectionState;\n if (state === 'connected' || state === 'completed') {\n clearGrace();\n restartTried = false;\n } else if (state === 'failed') {\n clearGrace();\n failed();\n } else if (state === 'disconnected' && grace === undefined) {\n grace = setTimeout(() => {\n grace = undefined;\n if (pc.iceConnectionState === 'disconnected') failed();\n }, graceMs);\n }\n };\n pc.onconnectionstatechange = () => {\n if (pc.connectionState === 'closed') reportGone();\n };\n\n const makeChannel = () => {\n const messageCbs = new Set<(frame: string) => void>();\n const openCbs = new Set<() => void>();\n const closeCbs = new Set<() => void>();\n const pending: string[] = [];\n let dc: RTCDataChannel | null = null;\n const attach = (channel: RTCDataChannel): void => {\n dc = channel;\n channel.onmessage = (e) => {\n for (const cb of [...messageCbs]) cb(String(e.data));\n };\n channel.onopen = () => {\n for (const frame of pending.splice(0)) channel.send(frame);\n for (const cb of [...openCbs]) cb();\n };\n channel.onclose = () => {\n for (const cb of [...closeCbs]) cb();\n };\n };\n const like: DataChannelLike = {\n send: (frame) => {\n if (dc && dc.readyState === 'open') dc.send(frame);\n else pending.push(frame);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n close: () => dc?.close(),\n };\n return { attach, like };\n };\n\n const made = new Map(channels.map((c) => [c.label, makeChannel()]));\n\n // the impolite side opens every channel; the polite side adopts them by label\n if (!polite) {\n for (const spec of channels) {\n const init: RTCDataChannelInit = {};\n if (spec.ordered !== undefined) init.ordered = spec.ordered;\n if (spec.maxRetransmits !== undefined)\n init.maxRetransmits = spec.maxRetransmits;\n made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));\n }\n } else {\n pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);\n }\n\n pc.onicecandidate = (e) => {\n if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });\n };\n pc.onnegotiationneeded = async () => {\n try {\n makingOffer = true;\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n } catch (err) {\n rejected('make an offer', err);\n } finally {\n makingOffer = false;\n }\n };\n\n const byLabel: Record<string, DataChannelLike> = {};\n for (const [label, ch] of made) byLabel[label] = ch.like;\n\n return {\n channel: byLabel[channels[0].label],\n channels: byLabel,\n signal: async (data) => {\n if (pc.signalingState === 'closed') return;\n const { description, ice } = (data ?? {}) as {\n description?: RTCSessionDescriptionInit;\n ice?: RTCIceCandidateInit;\n };\n if (description) {\n const collision =\n description.type === 'offer' &&\n (makingOffer || pc.signalingState !== 'stable');\n ignoreOffer = !polite && collision;\n if (ignoreOffer) return;\n try {\n await pc.setRemoteDescription(description);\n if (description.type === 'offer') {\n await pc.setLocalDescription();\n sendSignal({ description: pc.localDescription });\n }\n } catch (err) {\n rejected('apply the remote description', err);\n }\n } else if (ice) {\n try {\n await pc.addIceCandidate(ice);\n } catch (err) {\n if (!ignoreOffer) throw err;\n }\n }\n },\n onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),\n close: () => {\n finished = true;\n clearGrace();\n for (const ch of made.values()) ch.like.close();\n pc.close();\n },\n };\n };\n}\n\n/**\n * A relay connection someone else owns (a live session, say). Peer links ride on it without\n * saying hello, so the links share that connection's origin and room membership.\n */\nexport type SignalingPort = {\n /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */\n members(): readonly string[] | undefined;\n /** ICE servers from the owner's last welcome, if it keeps them. Read after subscribing. */\n iceServers?(): readonly IceServer[] | undefined;\n send(msg: ClientSignalMsg): void;\n onMessage(cb: (msg: ServerMsg) => void): () => void;\n};\n\nexport type PeerLinksOptions = {\n readonly room: string;\n /** This side's origin; also decides the perfect-negotiation role against each remote. */\n readonly origin: string;\n /**\n * A transport factory means the links own their relay connection (hello, reconnect); a\n * {@link SignalingPort} means they ride on one that is already joined.\n */\n readonly signaling: MeshTransportFactory | SignalingPort;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n /**\n * The channels every link carries, first one the default for `send` and `broadcast`.\n * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.\n */\n readonly channels?: readonly PeerChannelSpec[];\n /** Sent in the hello when the links own their connection. */\n readonly policyVersion?: number;\n /**\n * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe\n * before the first link opens. Defaults to `true`.\n */\n readonly autoConnect?: boolean;\n /** How long a link may take to open every channel before it counts as lost. Default 15000. */\n readonly openTimeoutMs?: number;\n /** Backoff bounds for rebuilding a lost link. Defaults 1000 and 30000. */\n readonly retry?: { readonly minMs?: number; readonly maxMs?: number };\n /** Random source for the backoff jitter; tests pass a seeded one. Default Math.random. */\n readonly random?: () => number;\n readonly injector?: Injector;\n};\n\nexport type PeerLinks = {\n /**\n * `live` once the relay has welcomed this side (or, over a port, once it has seen a\n * welcome); back to `connecting` while an owned relay connection is being re-established.\n * Peer links outlive that: they are retired only by their own close or a relay `gone`. Over\n * a port the same holds across the session's socket drops; when the session itself ends, the\n * port reports `gone` for every member and the links are retired with it.\n */\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins whose link has every channel open. */\n readonly peers: Signal<readonly string[]>;\n /** Members whose link was lost at least once since it last opened: waiting to rebuild, or rebuilding. */\n readonly stalled: Signal<readonly string[]>;\n /**\n * Other origins in the room as the relay reports them (welcome, then join and leave). The\n * relay is the authority on who is present; a link can outlive a dead socket for a while.\n */\n readonly members: Signal<readonly string[]>;\n /** Replays current membership synchronously, then reports every change without coalescing. */\n onMembers(cb: (members: readonly string[]) => void): () => void;\n /** The labels every link carries, in the order they were asked for. */\n readonly channels: readonly string[];\n /** Fires when one channel of a link opens; replays channels that are already open. */\n onOpen(cb: (origin: string, channel: string) => void): () => void;\n onMessage(\n cb: (origin: string, frame: string, channel: string) => void,\n ): () => void;\n /**\n * Fires when a link goes away: a channel closed, the connector reported it gone, it did not\n * open in time, or the relay reported the origin gone. A lost link is rebuilt while the relay\n * lists its origin.\n */\n onClose(cb: (origin: string) => void): () => void;\n /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */\n onEnd(cb: () => void): () => void;\n /** Sends on one open channel; a frame for a channel that is not open is dropped. */\n send(origin: string, frame: string, channel?: string): void;\n /** Sends on the channel of every link where it is open. */\n broadcast(frame: string, channel?: string): void;\n /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */\n connect(): void;\n close(): void;\n};\n\ntype Peer = {\n /** This side's instance id for the link, carried in every signal payload it sends. */\n readonly id: string;\n /** The remote side's instance id, bound by the first signal that carries one. */\n remote?: string;\n link: ReturnType<PeerConnector>;\n channels: Map<string, { channel: DataChannelLike; open: boolean }>;\n unsubs: (() => void)[];\n};\n\n/**\n * A signal payload split into its addressing and the connector's part: `link` is the sending\n * instance, `to` the receiving instance it was bound to when it sent (absent until it is).\n */\nconst unwrapSignal = (\n data: unknown,\n): { link?: string; to?: string; payload?: unknown } => {\n if (typeof data !== 'object' || data === null) return { payload: data };\n const { link, to, ...rest } = data as { link?: unknown; to?: unknown };\n if (typeof link !== 'string') return { payload: data };\n return {\n link,\n to: typeof to === 'string' ? to : undefined,\n payload: Object.keys(rest).length ? rest : undefined,\n };\n};\n\n/**\n * The link layer under peer-to-peer consumers: one peer connection per remote origin in the\n * room, set up from relay membership and negotiated over relay `signal` frames. Each link\n * carries the same labelled channels; frames are opaque strings, what they mean is the\n * consumer's business.\n *\n * An origin is one seat: the relay hands a second connection with the same origin the seat\n * and reports it to the room as a plain join. Links tell seats apart by instance, not by\n * order: every link announces a random instance id in its signals and, once it knows the\n * instance across, addresses its signals to it. A signal addressed to an instance this side\n * no longer has is dropped. An unaddressed signal from an instance other than the one linked\n * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed\n * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt\n * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin\n * still take the seat from each other on every reconnect; give each tab its own origin.\n *\n * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is\n * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for\n * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may\n * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild\n * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.\n *\n * No link is built before the welcome of the connection it signals over: joins before it are\n * superseded by the welcome's roster and signals are held and replayed after it, so every link\n * is built with that welcome's ICE servers and never an earlier connection's.\n */\nexport function peerLinks(opt: PeerLinksOptions): PeerLinks {\n const injector = opt.injector ?? inject(Injector);\n const connector = opt.connector ?? rtcPeerConnector();\n const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;\n const labels = specs.map((c) => c.label);\n const primary = labels[0];\n const status = signal<'connecting' | 'live'>('connecting');\n const openPeers = signal<ReadonlySet<string>>(new Set());\n const members = signal<ReadonlySet<string>>(new Set());\n const peers = new Map<string, Peer>();\n const lifecycle = signal(emptyLifecycle);\n // one timer slot per origin: the open timeout or the rebuild timer, never both\n const timers = new Map<string, ReturnType<typeof setTimeout>>();\n const openTimeoutMs = opt.openTimeoutMs ?? 15_000;\n const bounds = {\n minMs: opt.retry?.minMs ?? 1000,\n maxMs: opt.retry?.maxMs ?? 30_000,\n };\n const random = opt.random ?? Math.random;\n // the relay's ICE servers from the last welcome; undefined leaves the connector's own\n let iceServers: readonly IceServer[] | undefined;\n const openCbs = new Set<(origin: string, channel: string) => void>();\n const messageCbs = new Set<\n (origin: string, frame: string, channel: string) => void\n >();\n const closeCbs = new Set<(origin: string) => void>();\n const endCbs = new Set<() => void>();\n const memberCbs = new Set<(members: readonly string[]) => void>();\n let signalingUnsubs: (() => void)[] = [];\n let transport: MeshTransport | null = null;\n let reconnectTimer: ReturnType<typeof setTimeout> | undefined;\n let connected = false;\n let closed = false;\n // no link is built before the welcome of the connection it signals over, so every link\n // carries that welcome's ICE servers: joins are ignored and signals held until then\n let welcomed = false;\n // the last request id this side issued; ids only grow, also across connections\n let helloId = 0;\n let held: Extract<ServerMsg, { t: 'signal' }>[] = [];\n let heldWarned = false;\n // links are told apart by instance, never by order: a random tag plus a counter\n const tag = Math.random().toString(36).slice(2, 10);\n let linkSeq = 0;\n let feeding = 0;\n const failedBuilds: string[] = [];\n\n const port: SignalingPort | null =\n typeof opt.signaling === 'function' ? null : opt.signaling;\n const sendSignal = (msg: ClientSignalMsg): void => {\n if (port) port.send(msg);\n else transport?.send(msg);\n };\n\n const dropPeer = (origin: string): void => {\n const peer = peers.get(origin);\n if (!peer) return;\n peers.delete(origin);\n for (const unsub of peer.unsubs) unsub();\n peer.link.close();\n openPeers.update((set) => {\n const next = new Set(set);\n next.delete(origin);\n return next;\n });\n for (const cb of [...closeCbs]) cb(origin);\n };\n\n /**\n * Builds the link to `origin`; `remote` is the instance on the other side when the link is\n * built in answer to one of its signals, so everything this side sends is addressed to it.\n */\n const ensurePeer = (origin: string, remote?: string): Peer => {\n const existing = peers.get(origin);\n if (existing) return existing;\n const id = `${tag}.${++linkSeq}`;\n // signals the connector sends while it is still being built wait until the peer is\n // registered, so the remote's synchronous answer finds it instead of building another\n let building: unknown[] | null = [];\n let retired = false;\n const signal = (data: unknown): void => {\n if (retired) return;\n if (building) {\n building.push(data);\n return;\n }\n const stamped =\n typeof data === 'object' && data !== null\n ? {\n ...data,\n link: id,\n ...(p.remote === undefined ? {} : { to: p.remote }),\n }\n : data;\n sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });\n };\n const link = connector({\n remote: origin,\n polite: opt.origin > origin,\n sendSignal: signal,\n channels: specs,\n ...(iceServers ? { iceServers } : {}),\n });\n const p: Peer = {\n id,\n remote,\n link,\n channels: new Map(),\n unsubs: [() => (retired = true)],\n };\n peers.set(origin, p);\n const lost = (): void => {\n if (peers.get(origin) === p) feed({ t: 'lost', origin });\n };\n if (link.onClose) p.unsubs.push(link.onClose(lost));\n const early = building;\n building = null;\n // announce the instance, so a side that still holds a link to an earlier seat of this\n // origin (a takeover the relay reports as a plain join) replaces it\n signal({});\n for (const data of early) signal(data);\n for (const label of labels) {\n const channel =\n link.channels?.[label] ??\n (label === primary ? link.channel : undefined);\n if (!channel) {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`,\n );\n }\n continue;\n }\n const state = { channel, open: false };\n p.channels.set(label, state);\n p.unsubs.push(\n channel.onOpen(() => {\n state.open = true;\n if (\n peers.get(origin) === p &&\n labels.every((l) => p.channels.get(l)?.open)\n ) {\n openPeers.update((set) => new Set(set).add(origin));\n feed({ t: 'opened', origin });\n // a link rebuilt by a takeover opens while its origin is already open to the\n // lifecycle, which then ignores the report: its open timeout ends here all the same\n if (untracked(lifecycle).get(origin)?.state === 'open')\n disarm(origin);\n }\n for (const cb of [...openCbs]) cb(origin, label);\n }),\n channel.onMessage((frame) => {\n for (const cb of [...messageCbs]) cb(origin, frame, label);\n }),\n channel.onClose(lost),\n );\n }\n return p;\n };\n\n const disarm = (origin: string): void => {\n const timer = timers.get(origin);\n if (timer !== undefined) clearTimeout(timer);\n timers.delete(origin);\n };\n\n const arm = (origin: string, ms: number, fire: LifecycleEvent): void => {\n disarm(origin);\n const timer = setTimeout(() => {\n if (timers.get(origin) !== timer) return;\n timers.delete(origin);\n feed(fire);\n }, ms);\n timers.set(origin, timer);\n };\n\n const execute = (f: LifecycleEffect, remote?: string): void => {\n switch (f.t) {\n case 'drop':\n return dropPeer(f.origin);\n case 'disarm':\n return disarm(f.origin);\n }\n if (closed) return;\n switch (f.t) {\n case 'build':\n try {\n ensurePeer(f.origin, remote);\n } catch (err) {\n buildFailed(f.origin, err);\n }\n return;\n case 'armOpen':\n return arm(f.origin, openTimeoutMs, { t: 'lost', origin: f.origin });\n case 'armRetry':\n return arm(f.origin, retryDelay(f.attempt, bounds, random), {\n t: 'due',\n origin: f.origin,\n });\n }\n };\n\n /**\n * Steps the lifecycle and runs its effects in order. The new state is stored first, so an\n * event an effect causes on the spot (a link that opens while it is built) steps from it.\n * `remote` addresses the build of a link made in answer to a signal.\n */\n function feed(e: LifecycleEvent, remote?: string): void {\n feeding++;\n try {\n const { next, effects } = step(untracked(lifecycle), e);\n if (next !== untracked(lifecycle)) lifecycle.set(next);\n for (const f of effects) execute(f, remote);\n } finally {\n feeding--;\n }\n if (feeding === 0) drainFailed();\n }\n\n /**\n * A connector that throws while a link is built is a failure of that origin's link: it is\n * reported `lost` once the effect list in progress has finished, so the origin waits out the\n * backoff with no peer and the rest of that list still runs.\n */\n function buildFailed(origin: string, err: unknown): void {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] the peer connector threw while linking '${origin}'`,\n err,\n );\n }\n failedBuilds.push(origin);\n if (feeding === 0) drainFailed();\n }\n\n function drainFailed(): void {\n for (\n let o = failedBuilds.shift();\n o !== undefined;\n o = failedBuilds.shift()\n )\n feed({ t: 'lost', origin: o });\n }\n\n const setMembers = (origins: readonly string[]): void => {\n const next = new Set(origins);\n members.set(next);\n for (const cb of [...memberCbs]) cb([...next]);\n };\n\n const welcomeMembers = (\n origins: readonly string[],\n ice: readonly IceServer[] | undefined,\n ): void => {\n setMembers(origins);\n iceServers = ice;\n welcomed = true;\n status.set('live');\n feed({ t: 'welcome', members: origins });\n const replay = held;\n held = [];\n for (const msg of replay) {\n if (closed) return;\n handleSignaling(msg);\n }\n };\n\n const handleSignaling = (msg: ServerMsg): void => {\n if (closed || msg.room !== opt.room) return;\n if (!welcomed && msg.t !== 'welcome' && msg.t !== 'reject') {\n // the welcome's roster supersedes joins before it; a leave, or a join that hands the\n // origin's seat to a new connection, discards what the origin sent before it\n if (msg.t === 'signal') {\n if (held.length < HELD_SIGNALS) held.push(msg);\n else if (isDevMode() && !heldWarned) {\n heldWarned = true;\n console.warn(\n `[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`,\n );\n }\n } else if (msg.t === 'member') {\n held = held.filter((h) => h.from !== msg.origin);\n }\n return;\n }\n switch (msg.t) {\n case 'welcome':\n welcomeMembers(msg.members, msg.ice);\n return;\n case 'member':\n setMembers(\n msg.gone\n ? [...members()].filter((origin) => origin !== msg.origin)\n : [...new Set([...members(), msg.origin])],\n );\n feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });\n return;\n case 'signal': {\n if (!members().has(msg.from)) {\n // the relay routes signals among members only and reports a join before the\n // joiner's first signal; anything else must not become a link that retries forever\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`,\n );\n }\n return;\n }\n const { link, to, payload } = unwrapSignal(msg.data);\n let peer = peers.get(msg.from);\n if (link === undefined || (!peer && to === undefined)) {\n // no link to this member (lost and waiting to rebuild): its announce is the reason\n // to build now, addressed to its instance if stamped\n if (!peer) feed({ t: 'listed', origin: msg.from }, link);\n peer = peers.get(msg.from);\n if (!peer) return;\n } else if (!peer || (to !== undefined && to !== peer.id)) {\n // addressed to an instance this side no longer has: a retired link's leftovers\n return;\n } else if (peer.remote === undefined) {\n peer.remote = link;\n } else if (peer.remote !== link) {\n if (to === undefined) {\n // a new instance over there that does not know this side yet: a new seat or a\n // restarted link, so this side rebuilds, addressing it, which is what makes the\n // rebuild final: the other side never rebuilds in answer to an addressed signal.\n // It replaces the instance, not a lost link: the lifecycle state stays and only\n // the open timeout moves to the new instance.\n dropPeer(msg.from);\n arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });\n try {\n peer = ensurePeer(msg.from, link);\n } catch (err) {\n buildFailed(msg.from, err);\n return;\n }\n } else {\n // built for this very instance, so it is the newer end of this link: adopt it\n peer.remote = link;\n }\n }\n if (payload !== undefined) {\n const from = msg.from;\n // a connector may apply signals asynchronously; a rejection there must not escape\n void Promise.resolve(peer.link.signal(payload)).catch(\n (err: unknown) => {\n if (isDevMode()) {\n console.warn(\n `[@mmstack/mesh] a peer link could not apply a signal from '${from}'`,\n err,\n );\n }\n },\n );\n }\n return;\n }\n case 'reject':\n // a later hello of this origin took the seat: an own connection is reset and opened again;\n // over a borrowed port the session that owns the connection does that\n if (msg.reason === 'displaced') {\n resetSignaling();\n return;\n }\n close();\n return;\n }\n };\n\n const resetSignaling = (): void => {\n const t = transport;\n if (!t || closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport = null;\n welcomed = false;\n held = [];\n status.set('connecting');\n t.close();\n reconnectTimer = setTimeout(connectSignaling, 1000);\n };\n\n const connectSignaling = (): void => {\n if (closed) return;\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n if (port) {\n const unsub = port.onMessage(handleSignaling);\n if (closed) {\n unsub();\n return;\n }\n signalingUnsubs = [unsub];\n const current = port.members();\n if (current !== undefined) welcomeMembers(current, port.iceServers?.());\n return;\n }\n const t = (opt.signaling as MeshTransportFactory)();\n transport = t;\n signalingUnsubs = [\n t.onMessage(handleSignaling),\n t.onClose(() => {\n if (closed || transport !== t) return;\n transport = null;\n welcomed = false;\n held = [];\n status.set('connecting');\n reconnectTimer = setTimeout(connectSignaling, 1000);\n }),\n ];\n // one hello per connection: its request id is recorded before the send\n const rid = ++helloId;\n t.send({\n t: 'hello',\n room: opt.room,\n origin: opt.origin,\n proto: MESH_PROTO_VERSION,\n policyVersion: opt.policyVersion ?? 0,\n rid,\n });\n };\n\n const connect = (): void => {\n if (connected || closed) return;\n connected = true;\n connectSignaling();\n };\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n held = [];\n if (reconnectTimer !== undefined) clearTimeout(reconnectTimer);\n feed({ t: 'close' });\n // a takeover's open timeout on a link the lifecycle already counts open\n for (const origin of [...timers.keys()]) disarm(origin);\n for (const origin of [...peers.keys()]) dropPeer(origin);\n for (const unsub of signalingUnsubs.splice(0)) unsub();\n transport?.close();\n transport = null;\n setMembers([]);\n memberCbs.clear();\n status.set('connecting');\n for (const cb of [...endCbs]) cb();\n endCbs.clear();\n };\n\n const openChannel = (origin: string, label: string) => {\n const state = peers.get(origin)?.channels.get(label);\n return state?.open ? state.channel : null;\n };\n\n injector.get(DestroyRef).onDestroy(close);\n if (opt.autoConnect !== false) connect();\n\n return {\n status: status.asReadonly(),\n peers: computed(() => [...openPeers()]),\n stalled: computed(() =>\n [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin),\n ),\n members: computed(() => [...members()]),\n onMembers: (cb) => {\n if (!closed) memberCbs.add(cb);\n cb([...members()]);\n return () => memberCbs.delete(cb);\n },\n channels: labels,\n onOpen: (cb) => {\n openCbs.add(cb);\n for (const [origin, peer] of peers) {\n for (const [label, state] of peer.channels) {\n if (state.open) cb(origin, label);\n }\n }\n return () => openCbs.delete(cb);\n },\n onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),\n onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),\n onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),\n send: (origin, frame, channel = primary) => {\n openChannel(origin, channel)?.send(frame);\n },\n broadcast: (frame, channel = primary) => {\n for (const origin of peers.keys())\n openChannel(origin, channel)?.send(frame);\n },\n connect,\n close,\n };\n}\n","import {\n inject,\n Injector,\n type Signal,\n type WritableSignal,\n} from '@angular/core';\nimport {\n opSync,\n type DiffOpsOptions,\n type MergePolicyEntry,\n type OpEnvelope,\n type OpSyncCheckpoint,\n} from '@mmstack/primitives/core';\nimport {\n defaultPeerChannels,\n peerLinks,\n type PeerChannelSpec,\n type PeerConnector,\n type PeerLinks,\n} from './peer-links';\nimport type { MeshTransportFactory } from './transport';\n\nexport {\n rtcPeerConnector,\n type DataChannelLike,\n type PeerConnector,\n} from './peer-links';\n\ntype P2PMsg =\n | { t: 'hello'; wm: Record<string, number> }\n // the full checkpoint (root + register state + watermark), NOT a bare value: the covered\n // side must inherit supersession state or already-superseded stragglers would resurrect\n | { t: 'state'; state: OpSyncCheckpoint<object> }\n | { t: 'uptodate' }\n | { t: 'env'; env: OpEnvelope };\n\nexport type WebRtcMeshOptions = {\n readonly room: string;\n readonly writer: string;\n /**\n * This replica's origin, its identity in the room; defaults to a random id per instance.\n * One origin is one seat, so never share one between two live instances.\n */\n readonly origin?: string;\n /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */\n readonly signaling: MeshTransportFactory;\n /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */\n readonly connector?: PeerConnector;\n /**\n * Further channels every link carries beside the mesh's own reliable one, for consumers\n * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.\n */\n readonly channels?: readonly PeerChannelSpec[];\n readonly policies?: readonly MergePolicyEntry[];\n readonly policyVersion?: number;\n readonly injector?: Injector;\n /** How local writes are diffed into ops (forwarded to `opSync`; see `DiffOpsOptions`). Absent: as before. */\n readonly emit?: DiffOpsOptions;\n};\n\nexport type WebRtcMeshRef = {\n /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */\n readonly origin: string;\n readonly status: Signal<'connecting' | 'live'>;\n /** Origins with an OPEN data channel. */\n readonly peers: Signal<readonly string[]>;\n /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */\n readonly links: PeerLinks;\n close(): void;\n};\n\n/**\n * Peer-to-peer mesh sync: the relay only signals\n * and tracks membership; envelopes flow over WebRTC data channels and converge via the\n * per-path register map. Catch-up is pairwise: on channel open both sides exchange\n * watermarks; a side whose state is covered (the other holds every envelope it holds)\n * hydrates from the other's FULL checkpoint (root + per-path register state + watermark), so supersession and precedence\n * carry over intact: a late joiner is indistinguishable from a peer that saw every\n * envelope. Two peers that each hold envelopes the other lacks keep their convergent\n * go-forward guarantees but do not exchange the missed envelopes retroactively.\n *\n * There is no relay admission here: no sequence, no generation, no refusals. Beside a\n * relay-backed session over the same document a peer channel may hand on only envelopes the\n * relay has sequenced, never a peer's own unacknowledged writes.\n */\nexport function webRtcMesh<T extends object>(\n source: WritableSignal<T>,\n opt: WebRtcMeshOptions,\n): WebRtcMeshRef {\n const injector = opt.injector ?? inject(Injector);\n const meshChannel = defaultPeerChannels[0];\n let closed = false;\n\n const sync = opSync(source, {\n writer: opt.writer,\n origin: opt.origin,\n policies: opt.policies,\n policyVersion: opt.policyVersion,\n injector,\n emit: opt.emit,\n });\n\n // subscribe before signaling starts: a link can open, and its first frame arrive, while\n // the hello is still being answered\n const links = peerLinks({\n room: opt.room,\n origin: sync.origin,\n signaling: opt.signaling,\n connector: opt.connector,\n channels: [\n meshChannel,\n ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),\n ],\n policyVersion: opt.policyVersion,\n autoConnect: false,\n injector,\n });\n\n const covered = (\n mine: Record<string, number>,\n theirs: Record<string, number>,\n ): boolean => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);\n\n const sendTo = (origin: string, msg: P2PMsg): void => {\n links.send(origin, JSON.stringify(msg));\n };\n\n const handlePeerMsg = (origin: string, msg: P2PMsg): void => {\n switch (msg.t) {\n case 'hello': {\n const snap = sync.snapshot();\n if (covered(snap.wm, msg.wm)) sendTo(origin, { t: 'uptodate' });\n else sendTo(origin, { t: 'state', state: snap });\n return;\n }\n case 'state': {\n if (covered(sync.watermark(), msg.state.wm)) {\n sync.hydrate(msg.state as OpSyncCheckpoint<T>);\n }\n return;\n }\n case 'uptodate':\n return;\n case 'env':\n sync.receive(msg.env);\n return;\n }\n };\n\n links.onOpen((origin, channel) => {\n if (channel === meshChannel.label)\n sendTo(origin, { t: 'hello', wm: sync.watermark() });\n });\n links.onMessage((origin, frame, channel) => {\n if (channel !== meshChannel.label) return;\n let msg: P2PMsg;\n try {\n msg = JSON.parse(frame) as P2PMsg;\n } catch {\n return;\n }\n handlePeerMsg(origin, msg);\n });\n\n const unsubLocal = sync.subscribe((env) =>\n links.broadcast(JSON.stringify({ t: 'env', env } satisfies P2PMsg)),\n );\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n unsubLocal();\n links.close();\n sync.destroy();\n };\n\n // a relay reject ends the links; the mesh ends with them\n links.onEnd(close);\n links.connect();\n\n return {\n origin: sync.origin,\n status: links.status,\n peers: links.peers,\n links,\n close,\n };\n}\n","import {\n computed,\n DestroyRef,\n effect,\n inject,\n Injector,\n signal,\n untracked,\n type Signal,\n} from '@angular/core';\nimport { throttled } from '@mmstack/primitives/core';\nimport type { PeerChannelSpec, PeerLinks } from './peer-links';\n\n/**\n * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that\n * waits for a retransmit is already stale, and ordering would hold newer frames behind it.\n * Put it in the `channels` of the {@link PeerLinks} the presence rides on.\n */\nexport const presenceChannel: PeerChannelSpec = {\n label: 'mmstack-presence',\n ordered: false,\n maxRetransmits: 0,\n};\n\n/**\n * What goes over the wire. `seq` counts frames sent on one channel of one links object, in\n * send order, and is shared by every sender created on those links; it never restarts while\n * the links live. It orders frames of one link only, and is never compared across links.\n */\nexport type PresenceFrame<T> = {\n readonly seq: number;\n readonly value: T;\n};\n\nexport type RtcPresenceOptions = {\n /** The channel label on the links; defaults to {@link presenceChannel}'s. */\n readonly channel?: string;\n /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */\n readonly throttleMs?: number;\n /**\n * Who is in the room, from the relay. A value is held only for an origin in it: a peer link\n * can outlive the relay membership on a dead socket, so the link is not proof of presence.\n * Subscribe synchronously with the current roster, then report every transition, including\n * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.\n * A sampled signal or an effect cannot preserve these transitions.\n */\n readonly roster: (cb: (members: readonly string[]) => void) => () => void;\n readonly injector?: Injector;\n};\n\nexport type RtcPresenceRef<T> = {\n /** Publishes this side's value; throttled, and the last value of a burst always goes out. */\n set(value: T): void;\n /** The latest value per origin, only for origins in the roster. */\n readonly peers: Signal<ReadonlyMap<string, T>>;\n /** Stops publishing and forgets every held value. The links stay open. */\n close(): void;\n};\n\nconst none = Symbol('none');\n\n// one send counter per links object and channel, shared by every sender created on them\nconst counters = new WeakMap<PeerLinks, Map<string, { seq: number }>>();\nconst counterOf = (links: PeerLinks, label: string): { seq: number } => {\n let byLabel = counters.get(links);\n if (!byLabel) counters.set(links, (byLabel = new Map()));\n let counter = byLabel.get(label);\n if (!counter) byLabel.set(label, (counter = { seq: 0 }));\n return counter;\n};\n\nconst isNum = (x: unknown): x is number =>\n typeof x === 'number' && Number.isFinite(x);\n\n/**\n * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no\n * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the\n * sender's next `set`.\n *\n * Order comes from causality the receiver observes, never from clocks or from numbers chosen\n * by different senders. A value is held only for an origin in the roster, and it is removed\n * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or\n * below it is dropped: one counter stamps every frame sent on that link in send order, so a\n * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a\n * frame of an old link cannot arrive on a new one. An origin that leaves and comes back\n * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives\n * and nobody reads `peers` between leave and rejoin.\n *\n * The counter belongs to the links and the channel, not to this sender, so a sender closed\n * and recreated on the same links carries on where the last one stopped and is heard at\n * once. A new tab or device is a new link, which every receiver already treats as fresh.\n *\n * Nothing is minted while no link carries the channel: a sender alone costs no frames, no\n * numbers and no timers. The gate is the set of links whose presence channel is open, the very\n * set `broadcast` delivers to, so no frame that anyone could receive is withheld.\n *\n * Values travel as JSON.\n */\nexport function rtcPresence<T>(\n links: PeerLinks,\n opt: RtcPresenceOptions,\n): RtcPresenceRef<T> {\n const injector = opt.injector ?? inject(Injector);\n const label = opt.channel ?? presenceChannel.label;\n if (!links.channels.includes(label)) {\n throw new Error(\n `[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`,\n );\n }\n\n const held = new Map<string, { seq: number; value: T }>();\n const version = signal(0);\n const counter = counterOf(links, label);\n let closed = false;\n let roster: ReadonlySet<string> = new Set();\n // origins whose link has this channel open: who a broadcast would reach\n const open = new Set<string>();\n\n const forget = (origin: string): void => {\n if (held.delete(origin)) version.update((v) => v + 1);\n };\n\n const receive = (origin: string, frame: string): void => {\n if (closed) return;\n let msg: PresenceFrame<T>;\n try {\n msg = JSON.parse(frame) as PresenceFrame<T>;\n } catch {\n return;\n }\n if (\n typeof msg !== 'object' ||\n msg === null ||\n !isNum(msg.seq) ||\n !('value' in msg)\n ) {\n return;\n }\n if (!roster.has(origin)) return;\n const prev = held.get(origin);\n if (prev && msg.seq <= prev.seq) return;\n held.set(origin, { seq: msg.seq, value: msg.value });\n version.update((v) => v + 1);\n };\n\n const unsubs = [\n opt.roster((members) => {\n roster = new Set(members);\n for (const origin of held.keys()) if (!roster.has(origin)) forget(origin);\n }),\n links.onMessage((origin, frame, channel) => {\n if (channel === label) receive(origin, frame);\n }),\n // the link is the epoch: a new or lost link starts the origin fresh\n links.onOpen((origin, channel) => {\n if (channel !== label) return;\n forget(origin);\n open.add(origin);\n }),\n links.onClose((origin) => {\n open.delete(origin);\n forget(origin);\n }),\n links.onEnd(() => close()),\n ];\n\n const peers = computed<ReadonlyMap<string, T>>(() => {\n version();\n if (closed) return new Map();\n const out = new Map<string, T>();\n for (const [origin, entry] of held) {\n if (roster.has(origin)) out.set(origin, entry.value);\n }\n return out;\n });\n\n const destroyRef = injector.get(DestroyRef);\n const outgoing = throttled<T | typeof none>(none, {\n ms: opt.throttleMs ?? 33,\n leading: true,\n trailing: true,\n destroyRef,\n });\n const publisher = effect(\n () => {\n const value = outgoing();\n // a link closed since the set: nothing to reach, so nothing is minted\n if (value === none || closed || open.size === 0) return;\n untracked(() =>\n links.broadcast(\n JSON.stringify({\n seq: counter.seq++,\n value,\n } satisfies PresenceFrame<T>),\n label,\n ),\n );\n },\n { injector },\n );\n\n const close = (): void => {\n if (closed) return;\n closed = true;\n publisher.destroy();\n for (const unsub of unsubs.splice(0)) unsub();\n held.clear();\n open.clear();\n version.update((v) => v + 1);\n };\n\n destroyRef.onDestroy(close);\n\n return {\n set: (value) => {\n if (!closed && open.size > 0) outgoing.set(value);\n },\n peers,\n close,\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["step","none"],"mappings":";;;;;AA2DO,MAAM,cAAc,GAAG,OAAwB;IACpD,MAAM,EA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