statewire 0.19.4 → 0.21.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.
- package/README.md +15 -1
- package/dist/client/connection.d.ts.map +1 -1
- package/dist/client/connection.js +18 -4
- package/dist/client/connection.js.map +1 -1
- package/dist/client/session.d.ts +10 -1
- package/dist/client/session.d.ts.map +1 -1
- package/dist/client/session.js +92 -27
- package/dist/client/session.js.map +1 -1
- package/dist/client/sessionStore.d.ts +2 -0
- package/dist/client/sessionStore.d.ts.map +1 -1
- package/dist/client/sessionStore.js.map +1 -1
- package/dist/host/host.d.ts +2 -1
- package/dist/host/host.d.ts.map +1 -1
- package/dist/host/host.js +20 -12
- package/dist/host/host.js.map +1 -1
- package/dist/host/http.d.ts.map +1 -1
- package/dist/host/http.js +14 -9
- package/dist/host/http.js.map +1 -1
- package/dist/host/socket.d.ts +14 -3
- package/dist/host/socket.d.ts.map +1 -1
- package/dist/host/socket.js +162 -20
- package/dist/host/socket.js.map +1 -1
- package/dist/host-internal.d.ts +5 -2
- package/dist/host-internal.d.ts.map +1 -1
- package/dist/host.d.ts +6 -0
- package/dist/host.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/statewire.d.ts +3 -0
- package/dist/statewire.d.ts.map +1 -1
- package/dist/statewire.js +23 -5
- package/dist/statewire.js.map +1 -1
- package/dist/transports/remote.d.ts.map +1 -1
- package/dist/transports/remote.js +3 -2
- package/dist/transports/remote.js.map +1 -1
- package/dist/transports/sse.d.ts +5 -0
- package/dist/transports/sse.d.ts.map +1 -1
- package/dist/transports/sse.js +12 -0
- package/dist/transports/sse.js.map +1 -1
- package/dist/transports/testing.d.ts +2 -0
- package/dist/transports/testing.d.ts.map +1 -1
- package/dist/transports/testing.js +11 -4
- package/dist/transports/testing.js.map +1 -1
- package/dist/types.d.ts +4 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/wire/context.d.ts +14 -0
- package/dist/wire/context.d.ts.map +1 -0
- package/dist/wire/context.js +31 -0
- package/dist/wire/context.js.map +1 -0
- package/dist/wire/limits.d.ts +2 -1
- package/dist/wire/limits.d.ts.map +1 -1
- package/dist/wire/limits.js +2 -1
- package/dist/wire/limits.js.map +1 -1
- package/dist/wire/protocol.d.ts +1 -1
- package/dist/wire/protocol.js +4 -4
- package/dist/wire/protocol.js.map +1 -1
- package/package.json +1 -1
- package/src/client/connection.ts +16 -4
- package/src/client/session.ts +128 -19
- package/src/client/sessionStore.ts +5 -1
- package/src/host/host.ts +18 -3
- package/src/host/http.ts +37 -5
- package/src/host/socket.ts +232 -13
- package/src/host-internal.ts +4 -0
- package/src/host.ts +5 -0
- package/src/statewire.ts +34 -3
- package/src/transports/remote.ts +3 -0
- package/src/transports/sse.ts +19 -0
- package/src/transports/testing.ts +14 -3
- package/src/types.ts +12 -0
- package/src/wire/context.ts +40 -0
- package/src/wire/limits.ts +2 -0
- package/src/wire/protocol.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.js","names":["wrapStorageError","DEFAULT_PROTOCOL","WIRE_VERSION","protocolOffers","inRange","StatewireProtocol","applyDocumentOps","mainDocument","findDocument","resolveDocumentKey","StatewireDocuments","useContext","useEffect","useState","StatewirePath","MAX_COMMANDS_PER_FRAME","TERMINAL","StatewireCmd","StatewireSyn","encodeParams","reviveResponse","reviveValue","bindCommandsHost","CommandsInvocation","CommandsListener","Statewire","StatewireClient","DocumentStorageContext","SessionStorageContext","createMemorySessionStore","backoff","retryHint","createMethodProxy","randomId","newClientId","StatewireSendError","RemoteLink","StatewireFrame","StatewireRemoteProps","WireCommand","protocol","produced","NonNullable","SessionCommand","method","params","meta","Pending","seq","command","inv","attempted","posted","applied","resolve","payload","reject","error","protocolError","message","Error","rejectedSend","failure","SendFailure","Promise","result","catch","AttachState","StatewireSessionOptions","Options","sessionStore","SessionStorage","onSessionLost","OnSessionLost","onDone","Shared","txq","parked","verdict","SessionVerdict","unsubscribe","Session","options","selection","Selection","record","SessionRecord","ctx","recordPersisted","hydrated","ready","storageError","persistedRecord","store","documentStore","Storage","shared","ephemeral","deactivated","sessionKnown","durableSeq","Record","ephemeralSeqs","resumeAt","idle","lanesOnAttach","attachEntries","ReadonlySet","frameFailures","pending","failedList","FailedCommand","failedParts","canonical","documentListeners","Set","documents","State","lastPublished","changed","source","StateSource","attach","attachEpoch","running","pumping","transport","waiters","lifecycle","notify","commands","EMPTY_LANE","SessionLane","nextSeq","laneOf","Object","hasOwn","lanes","withLane","lane","isEphemeral","s","protocols","some","p","name","durableSeqOf","laneEntries","filter","publish","wake","waiter","waitForWake","r","push","sleepUntilWake","delayMs","clearTimeout","timer","setTimeout","w","storageFailed","cause","entry","setRecord","save","toStored","_protocol","backlog","map","mergeBacklog","own","known","foreign","c","has","sort","a","b","durableLanes","keys","MAX_PARKED_VERDICTS","syncBacklogInner","splice","parkedHere","v","parkedSeqs","verdicts","length","slice","unchanged","every","i","undefined","syncBacklog","transactBackground","transact","fn","run","then","lock","stored","load","clientId","adoptReset","persistence","flush","done","setIdle","level","cover","onApplied","onCovered","failedCommands","parts","values","flatMap","failed","same","part","flat","retainFailedInner","ts","retainFailed","settleEntry","outcome","ok","onSettle","type","rides","settleAll","detach","const","batch","detachFailure","predecessorLost","fate","settleLost","entries","requeue","survivors","old","enqueueInner","rebaseRecord","adopt","held","previous","current","pump","resetRecord","connection","reconnect","ephemeralDetach","detachEphemeralLanes","includes","rejectedFailure","cmd","code","outcomeOf","String","settleVerdict","TERMINAL_CMD_TYPES","parkVerdict","handleCmd","dur","watermark","Math","max","find","consumeVerdicts","consumed","add","size","handleCmds","cmds","ingestOps","ops","next","get","value","applicationProtocols","fromEntries","id","d","key","JSON","stringify","changedPaths","cacheDocuments","document","keyPrefixes","version","namespace","publishIngested","listener","sessionLostInner","seqWm","selectionOf","syn","handleHello","mode","Map","attached","reconcile","adoptStored","handleOps","handleRefusal","retry","Date","now","gaps","first","handleDetach","handleFinish","reason","isFinished","Lanes","frame","buildLanes","cmdGate","last","stopped","gated","_produced","takeAttachLanes","wanted","persistBeforeSend","status","resumeDelay","epoch","send","onPosted","start","subscribe","stop","setTransport","onStart","enqueue","offered","offers","offer","adopted","sendCommand","negotiated","encoded","wire","wireVersion","findFailed","f","unknownFailed","takeFailed","found","discardFailed","retryFailed","documentSource","Source","prefix","mounted","absolute","cached","list","delete","invokeProtocol","storedCommandCompatible","validateLanes","Array","isArray","loadSessionRecord","compatible","migrate","useStatewireSession","defaultStore","session","beforeAttach","onHello","args","onOps","onCmds","onRefusal","onIdle","onDetach","onFinish","snapshot","takeChanged","setOnChange","setListener"],"sources":["../../src/client/session.ts"],"sourcesContent":["import { wrapStorageError } from \"./storageError\";\nimport {\n DEFAULT_PROTOCOL,\n WIRE_VERSION,\n protocolOffers,\n inRange,\n} from \"../wire/protocol\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport {\n applyDocumentOps,\n mainDocument,\n findDocument,\n resolveDocumentKey,\n} from \"../wire/documents\";\nimport type { StatewireDocuments } from \"../wire/documents\";\nimport { useContext, useEffect, useState } from \"react\";\n\nimport type { StatewirePath } from \"../wire/ops\";\nimport { MAX_COMMANDS_PER_FRAME } from \"../wire/limits\";\nimport { TERMINAL } from \"./connection\";\nimport type { StatewireCmd, StatewireSyn } from \"./connection\";\nimport { encodeParams, reviveResponse, reviveValue } from \"../wire/meta\";\nimport { bindCommandsHost } from \"../host/host\";\nimport type { CommandsInvocation, CommandsListener } from \"../host/host\";\nimport type { Statewire } from \"../types\";\nimport type { StatewireClient } from \"../statewire\";\nimport {\n DocumentStorageContext,\n SessionStorageContext,\n createMemorySessionStore,\n} from \"./sessionStore\";\nimport { backoff, retryHint } from \"./timing\";\nimport { createMethodProxy } from \"../util/methodProxy\";\nimport { randomId as newClientId } from \"../util/randomId\";\nimport { StatewireSendError } from \"../types\";\nimport type {\n RemoteLink,\n StatewireFrame,\n StatewireRemoteProps,\n} from \"../transports/sse\";\n\ntype WireCommand = {\n protocol: string;\n produced?: NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n method: string;\n params: unknown[];\n meta?: unknown;\n};\n\ntype Pending = {\n readonly seq: number;\n readonly command: WireCommand;\n readonly inv: CommandsInvocation;\n /** A send carrying this statement may have reached the server. */\n attempted: boolean;\n /** In the resend queue when false. */\n posted: boolean;\n /** The server acknowledged admission; the terminal verdict is still due. */\n applied: boolean;\n resolve: (payload: unknown) => void;\n reject: (error: unknown) => void;\n};\n\nconst protocolError = (message: string): never => {\n throw new Error(`statewire: protocol error: ${message}`);\n};\n\nconst rejectedSend = (\n failure: StatewireClient.SendFailure,\n): Promise<unknown> => {\n const result = Promise.reject<unknown>(new StatewireSendError(failure));\n result.catch(() => {});\n return result;\n};\n\ntype AttachState = \"detached\" | \"attached\" | \"finished\";\n\nexport type StatewireSessionOptions = StatewireProtocol.Options & {\n sessionStore?: StatewireClient.SessionStorage | undefined;\n onSessionLost?: StatewireClient.OnSessionLost | undefined;\n onDone?: (() => void) | undefined;\n};\n\ntype Shared = {\n txq: Promise<void>;\n parked: { protocol: string; verdict: StatewireClient.SessionVerdict }[];\n unsubscribe: (() => void) | null;\n};\n\ntype Session = {\n options: StatewireSessionOptions;\n selection: StatewireProtocol.Selection | undefined;\n record: StatewireClient.SessionRecord;\n ctx: StatewireRemoteProps;\n recordPersisted: boolean;\n hydrated: boolean;\n ready: Promise<void> | undefined;\n storageError: unknown;\n persistedRecord: StatewireClient.SessionRecord | null;\n store: StatewireClient.SessionStorage;\n documentStore: StatewireDocuments.Storage | undefined;\n shared: Shared | false;\n /** Every selected lane is ephemeral: the record dies with the attach. */\n ephemeral: boolean;\n /** An ephemeral record died with its attach: the storage is off for good. */\n deactivated: boolean;\n sessionKnown: boolean;\n durableSeq: Record<string, number>;\n /** Ephemeral lane clocks: restart at 1 on every attach. */\n ephemeralSeqs: Record<string, number>;\n resumeAt: number;\n idle: boolean;\n onSessionLost: StatewireClient.OnSessionLost | undefined;\n onDone: (() => void) | undefined;\n lanesOnAttach: boolean;\n attachEntries: ReadonlySet<Pending>;\n frameFailures: number;\n pending: Pending[];\n failedList: readonly StatewireClient.FailedCommand[];\n failedParts: readonly (readonly StatewireClient.FailedCommand[])[];\n canonical: unknown;\n documentListeners: Set<() => void>;\n documents: StatewireDocuments.State;\n lastPublished: unknown;\n changed: StatewirePath[];\n source: Statewire.StateSource;\n attach: AttachState;\n attachEpoch: number;\n running: boolean;\n pumping: boolean;\n transport: RemoteLink | null;\n waiters: (() => void)[];\n lifecycle: CommandsListener | null;\n notify: () => void;\n commands: Record<string, (...params: unknown[]) => Promise<unknown>>;\n};\n\nconst EMPTY_LANE: StatewireClient.SessionLane = { nextSeq: 1, commands: [] };\n\nconst laneOf = (\n record: StatewireClient.SessionRecord,\n protocol: string,\n): StatewireClient.SessionLane =>\n Object.hasOwn(record.lanes, protocol) ? record.lanes[protocol]! : EMPTY_LANE;\n\nconst withLane = (\n record: StatewireClient.SessionRecord,\n protocol: string,\n lane: StatewireClient.SessionLane,\n): StatewireClient.SessionRecord => ({\n ...record,\n lanes: { ...record.lanes, [protocol]: lane },\n});\n\nconst isEphemeral = (s: Session, protocol: string) =>\n s.selection?.protocols.some(\n (p) => p.name === protocol && p.record === \"ephemeral\",\n ) ?? false;\n\nconst durableSeqOf = (s: Session, protocol: string) =>\n Object.hasOwn(s.durableSeq, protocol) ? s.durableSeq[protocol]! : 0;\n\nconst laneEntries = (s: Session, protocol: string) =>\n s.pending.filter((p) => p.command.protocol === protocol);\n\nconst publish = (s: Session) => {\n if (s.canonical === s.lastPublished) return;\n s.lastPublished = s.canonical;\n s.notify();\n};\n\nconst wake = (s: Session) => {\n const waiters = s.waiters;\n s.waiters = [];\n for (const waiter of waiters) waiter();\n};\n\nconst waitForWake = (s: Session) => new Promise<void>((r) => s.waiters.push(r));\n\nconst sleepUntilWake = (s: Session, delayMs: number) =>\n new Promise<void>((resolve) => {\n const waiter = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n s.waiters = s.waiters.filter((w) => w !== waiter);\n resolve();\n }, delayMs);\n s.waiters.push(waiter);\n });\n\nconst storageFailed = (s: Session, cause: unknown) => {\n const error = wrapStorageError(cause);\n s.storageError = error;\n for (const entry of s.pending) entry.reject(error);\n s.transport?.storageFailed(error);\n};\n\nconst setRecord = (s: Session, record: StatewireClient.SessionRecord) => {\n s.record = record;\n if (!s.deactivated) {\n try {\n s.store.save(record);\n } catch (cause) {\n storageFailed(s, cause);\n throw s.storageError;\n }\n }\n};\n\nconst toStored = (p: Pending): StatewireClient.SessionCommand => {\n const { protocol: _protocol, ...command } = p.command;\n return { seq: p.seq, ...command };\n};\n\nconst backlog = (\n s: Session,\n protocol: string,\n): StatewireClient.SessionCommand[] =>\n laneEntries(s, protocol)\n .filter((p) => p.seq > durableSeqOf(s, protocol))\n .map(toStored);\n\nconst mergeBacklog = (\n s: Session,\n protocol: string,\n): StatewireClient.SessionCommand[] => {\n const own = backlog(s, protocol);\n if (!s.shared) return own;\n const known = new Set(laneEntries(s, protocol).map((p) => p.seq));\n const foreign = laneOf(s.record, protocol).commands.filter(\n (c) => !known.has(c.seq) && c.seq > durableSeqOf(s, protocol),\n );\n return [...foreign, ...own].sort((a, b) => a.seq - b.seq);\n};\n\nconst durableLanes = (s: Session): string[] => [\n ...new Set([\n ...Object.keys(s.record.lanes),\n ...s.pending\n .map((p) => p.command.protocol)\n .filter((protocol) => !isEphemeral(s, protocol)),\n ]),\n];\n\nconst MAX_PARKED_VERDICTS = 64;\n\n// Storage holds what a reload must resend: a command leaves at its dur, at a\n// server verdict, or at a record reset — never at a local channel death.\nconst syncBacklogInner = (s: Session) => {\n const parked = s.shared ? s.shared.parked.splice(0) : [];\n let lanes = s.record.lanes;\n for (const protocol of durableLanes(s)) {\n const lane = laneOf(s.record, protocol);\n const parkedHere = parked\n .filter((v) => v.protocol === protocol)\n .map((v) => v.verdict);\n const parkedSeqs = new Set(parkedHere.map((v) => v.seq));\n const commands = mergeBacklog(s, protocol).filter(\n (c) => !parkedSeqs.has(c.seq),\n );\n const verdicts =\n parkedHere.length > 0\n ? [...(lane.verdicts ?? []), ...parkedHere].slice(-MAX_PARKED_VERDICTS)\n : lane.verdicts;\n const unchanged =\n verdicts === lane.verdicts &&\n commands.length === lane.commands.length &&\n commands.every((c, i) => c.seq === lane.commands[i]!.seq);\n if (unchanged) continue;\n lanes = {\n ...lanes,\n [protocol]: {\n ...lane,\n commands,\n ...(verdicts !== undefined && { verdicts }),\n },\n };\n }\n if (lanes !== s.record.lanes) setRecord(s, { ...s.record, lanes });\n};\n\nconst syncBacklog = (s: Session) => {\n if (!s.shared) return syncBacklogInner(s);\n transactBackground(s, () => syncBacklogInner(s));\n};\n\n// Every record mutation over shared storage is a locked read-modify-write.\nconst transact = (s: Session, fn: () => void): Promise<void> => {\n if (!s.shared || s.deactivated) {\n fn();\n return Promise.resolve();\n }\n const shared = s.shared;\n const run = shared.txq.then(() =>\n s.store.lock!(async () => {\n const stored = s.store.load();\n if (stored !== null && stored.clientId !== s.record.clientId) {\n adoptReset(s, stored);\n } else if (stored !== null) {\n s.record = stored;\n }\n fn();\n const persistence = s.store.flush?.();\n if (persistence) await persistence;\n }),\n );\n const result = run.catch((cause: unknown) => {\n storageFailed(s, cause);\n throw s.storageError;\n });\n shared.txq = result.then(\n () => {},\n () => {},\n );\n return result;\n};\n\nconst transactBackground = (s: Session, fn: () => void, done?: () => void) => {\n void transact(s, fn).then(done, () => {});\n};\n\nconst setIdle = (s: Session, level: boolean) => {\n if (level === s.idle) return;\n s.idle = level;\n s.notify();\n if (level) s.onDone?.();\n};\n\nconst cover = (s: Session, entry: Pending) => {\n if (entry.applied) return;\n entry.applied = true;\n s.lifecycle?.onApplied(entry.inv);\n s.lifecycle?.onCovered?.(entry.inv);\n};\n\nexport const failedCommands = (\n s: Session,\n): readonly StatewireClient.FailedCommand[] => {\n const parts = Object.values(s.record.lanes).flatMap((lane) =>\n lane.failed === undefined ? [] : [lane.failed],\n );\n const same =\n parts.length === s.failedParts.length &&\n parts.every((part, i) => part === s.failedParts[i]);\n if (!same) {\n s.failedParts = parts;\n s.failedList = parts.flat();\n }\n return s.failedList;\n};\n\nconst retainFailedInner = (\n s: Session,\n entry: Pending,\n failure: StatewireClient.SendFailure,\n) => {\n const lane = laneOf(s.record, entry.command.protocol);\n setRecord(\n s,\n withLane(s.record, entry.command.protocol, {\n ...lane,\n failed: [\n ...(lane.failed ?? []),\n {\n protocol: entry.command.protocol,\n ...(entry.command.produced !== undefined && {\n produced: entry.command.produced,\n }),\n command: entry.command.method,\n params: entry.command.params,\n ...(entry.command.meta !== undefined && { meta: entry.command.meta }),\n failure,\n ts: entry.inv.ts,\n seq: entry.seq,\n },\n ],\n }),\n );\n s.notify();\n};\n\nconst retainFailed = (\n s: Session,\n entry: Pending,\n failure: StatewireClient.SendFailure,\n) => {\n if (!s.shared) {\n retainFailedInner(s, entry, failure);\n return;\n }\n transactBackground(s, () => retainFailedInner(s, entry, failure));\n};\n\nconst settleEntry = (\n s: Session,\n entry: Pending,\n outcome:\n | { ok: true; payload: unknown }\n | { ok: false; failure: StatewireClient.SendFailure },\n) => {\n s.pending = s.pending.filter((p) => p !== entry);\n if (outcome.ok) {\n entry.resolve(outcome.payload);\n s.lifecycle?.onSettle(entry.inv, {\n type: \"accepted\",\n payload: outcome.payload,\n });\n } else {\n // A statement the record still carries resends on the next attach; only\n // invocations the record no longer owns become failed history.\n const rides =\n (outcome.failure.cause === \"unmount\" ||\n outcome.failure.cause === \"stream-gone\") &&\n entry.seq > durableSeqOf(s, entry.command.protocol);\n if (!rides && !isEphemeral(s, entry.command.protocol))\n retainFailed(s, entry, outcome.failure);\n entry.reject(new StatewireSendError(outcome.failure));\n s.lifecycle?.onSettle(entry.inv, {\n type: \"rejected\",\n error: new StatewireSendError(outcome.failure),\n });\n }\n};\n\nconst settleAll = (s: Session, detach: \"unmount\" | \"gone\") => {\n const cause =\n detach === \"unmount\" ? (\"unmount\" as const) : (\"stream-gone\" as const);\n const batch = s.pending;\n const detachFailure = (entry: Pending): StatewireClient.SendFailure => {\n if (!entry.attempted) {\n const predecessorLost = batch.some(\n (p) =>\n p.command.protocol === entry.command.protocol &&\n p.seq < entry.seq &&\n p.attempted,\n );\n return predecessorLost\n ? { fate: \"aborted\", cause, predecessorLost }\n : { fate: \"aborted\", cause };\n }\n return { fate: \"lost\", cause };\n };\n for (const entry of [...batch]) {\n s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, { ok: false, failure: detachFailure(entry) });\n }\n};\n\nconst settleLost = (s: Session, entries: Pending[]) => {\n for (const entry of entries) {\n s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, {\n ok: false,\n failure: { fate: \"lost\", cause: \"session-lost\" },\n });\n }\n};\n\nconst requeue = (s: Session, survivors: Pending[]) => {\n for (const old of survivors) {\n s.lifecycle?.onCovered?.(old.inv);\n enqueueInner(s, old.command, old.inv.params, old.resolve, old.reject);\n }\n};\n\n// The server-side record's dedup memory is gone: history that may have\n// reached a server settles lost — the new hello's snapshot is the only\n// truth about what survived — and never-attempted statements re-stamp\n// on the adopted lane clocks.\nconst rebaseRecord = (s: Session, adopt: () => void) => {\n const held = [...s.pending];\n const survivors = held.filter((p) => !p.attempted && !p.applied);\n settleLost(\n s,\n held.filter((p) => p.attempted || p.applied),\n );\n s.pending = [];\n s.durableSeq = {};\n // Failed entries are user-owned history: they ride through every record replacement.\n const previous = s.record.lanes;\n adopt();\n let lanes = s.record.lanes;\n for (const [protocol, lane] of Object.entries(previous)) {\n const failed = lane.failed;\n if (failed === undefined || laneOf(s.record, protocol).failed === failed)\n continue;\n const current = laneOf(s.record, protocol);\n lanes = {\n ...lanes,\n [protocol]: {\n ...current,\n failed: [...(current.failed ?? []), ...failed],\n },\n };\n }\n if (lanes !== s.record.lanes) setRecord(s, { ...s.record, lanes });\n requeue(s, survivors);\n publish(s);\n wake(s);\n void pump(s);\n};\n\nconst resetRecord = (s: Session, clientId: string) =>\n rebaseRecord(s, () => setRecord(s, { clientId, lanes: {} }));\n\n// Another sharer replaced the record's identity: their reset settles our\n// attempted history and our survivors re-stamp on the stored clocks.\nconst adoptReset = (s: Session, stored: StatewireClient.SessionRecord) => {\n rebaseRecord(s, () => {\n s.record = stored;\n });\n // The host attributes frames by lease, and the lease is bound to the id\n // this attach was opened with.\n if (s.attach === \"attached\") s.transport?.connection.reconnect();\n};\n\n// The record died with the attach: mint a fresh id for the next one.\nconst ephemeralDetach = (s: Session) => {\n s.ephemeral = false;\n s.sessionKnown = false;\n resetRecord(s, newClientId());\n};\n\n// An ephemeral lane dies with its attach: attempted statements can never be\n// answered, the rest re-stamp from 1 for the next attach.\nconst detachEphemeralLanes = (s: Session) => {\n const held = s.pending.filter((p) => isEphemeral(s, p.command.protocol));\n if (held.length === 0) return;\n s.pending = s.pending.filter((p) => !held.includes(p));\n settleLost(\n s,\n held.filter((p) => p.attempted),\n );\n requeue(\n s,\n held.filter((p) => !p.attempted),\n );\n publish(s);\n};\n\nconst rejectedFailure = (cmd: StatewireCmd): StatewireClient.SendFailure => {\n return {\n fate: \"rejected\",\n cause: \"server\",\n ...(cmd.code !== undefined && { code: cmd.code }),\n ...(cmd.message !== undefined && { message: cmd.message }),\n ...(cmd.payload !== undefined && { payload: cmd.payload }),\n };\n};\n\nconst outcomeOf = (\n cmd: StatewireCmd,\n):\n | { ok: true; payload: unknown }\n | { ok: false; failure: StatewireClient.SendFailure } => {\n switch (cmd.type) {\n case \"result\":\n return { ok: true, payload: reviveResponse(cmd).payload };\n case \"rejected\":\n return { ok: false, failure: rejectedFailure(reviveResponse(cmd)) };\n case \"failed\":\n return {\n ok: false,\n failure: {\n fate: \"failed\",\n cause: \"server\",\n ...(cmd.message !== undefined && { message: cmd.message }),\n },\n };\n case \"crashed\":\n return { ok: false, failure: { fate: \"crashed\", cause: \"server\" } };\n case \"expired\":\n return { ok: false, failure: { fate: \"expired\", cause: \"server\" } };\n default:\n return protocolError(`unknown cmd type: ${String(cmd.type)}`);\n }\n};\n\n// Only a result verdict carries applied effects; the rest drop the overlay unapplied.\nconst settleVerdict = (s: Session, entry: Pending, cmd: StatewireCmd) => {\n const outcome = outcomeOf(cmd);\n if (outcome.ok) cover(s, entry);\n else s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, outcome);\n};\n\nconst TERMINAL_CMD_TYPES: ReadonlySet<string> = new Set(TERMINAL);\n\nconst parkVerdict = (s: Session, cmd: StatewireCmd) => {\n if (!s.shared || !TERMINAL_CMD_TYPES.has(cmd.type!)) return;\n if (isEphemeral(s, cmd.protocol)) return;\n s.shared.parked.push({\n protocol: cmd.protocol,\n verdict: {\n seq: cmd.seq,\n type: cmd.type as StatewireClient.SessionVerdict[\"type\"],\n ...(cmd.code !== undefined && { code: cmd.code }),\n ...(cmd.message !== undefined && { message: cmd.message }),\n ...(cmd.payload !== undefined && { payload: cmd.payload }),\n ...(cmd.meta !== undefined && { meta: cmd.meta }),\n },\n });\n};\n\nconst handleCmd = (s: Session, cmd: StatewireCmd) => {\n if (cmd.dur === true && !isEphemeral(s, cmd.protocol)) {\n const watermark = Math.max(durableSeqOf(s, cmd.protocol), cmd.seq);\n s.durableSeq[cmd.protocol] = watermark;\n for (const entry of laneEntries(s, cmd.protocol)) {\n if (entry.seq <= watermark) entry.posted = true;\n }\n }\n if (cmd.type === undefined) return;\n const entry = s.pending.find(\n (p) => p.command.protocol === cmd.protocol && p.seq === cmd.seq,\n );\n if (cmd.type === \"applied\") {\n if (entry) cover(s, entry);\n return;\n }\n if (!entry) return;\n parkVerdict(s, cmd);\n settleVerdict(s, entry, cmd);\n};\n\nconst consumeVerdicts = (s: Session) => {\n let lanes = s.record.lanes;\n for (const [protocol, lane] of Object.entries(s.record.lanes)) {\n const verdicts = lane.verdicts ?? [];\n const consumed = new Set<number>();\n for (const verdict of verdicts) {\n const entry = laneEntries(s, protocol).find((p) => p.seq === verdict.seq);\n if (!entry) continue;\n consumed.add(verdict.seq);\n settleVerdict(s, entry, { ...verdict, protocol });\n }\n if (consumed.size === 0) continue;\n lanes = {\n ...lanes,\n [protocol]: {\n ...lane,\n commands: lane.commands.filter((c) => !consumed.has(c.seq)),\n verdicts: verdicts.filter((v) => !consumed.has(v.seq)),\n },\n };\n }\n if (lanes === s.record.lanes) return;\n setRecord(s, { ...s.record, lanes });\n publish(s);\n wake(s);\n};\n\nconst handleCmds = (s: Session, cmds: StatewireCmd[]) => {\n for (const cmd of cmds) handleCmd(s, cmd);\n syncBacklog(s);\n wake(s);\n};\n\nconst ingestOps = (s: Session, ops: unknown[]) => {\n const applied = applyDocumentOps(s.documents, ops, s.selection?.protocols);\n s.documents = applied;\n const next =\n s.selection === undefined\n ? applied.documents.get(0)?.value\n : s.options.applicationProtocols === \"*\"\n ? Object.fromEntries(\n [...applied.documents].map(([id, d]) => [\n `${d.protocol}:${d.key === null ? id : JSON.stringify(d.key)}`,\n d.value,\n ]),\n )\n : mainDocument(applied, s.options.protocol ?? DEFAULT_PROTOCOL)?.value;\n if (next !== s.canonical)\n s.changed.push(\n ...(applied.changedPaths.length ? applied.changedPaths : [[]]),\n );\n s.canonical = next;\n};\n\nconst cacheDocuments = (s: Session) => {\n if (s.documentStore && s.selection) {\n for (const document of s.documents.documents.values()) {\n if (!document.protocol || !document.key) continue;\n const key = resolveDocumentKey(\n document.key,\n s.options.keyPrefixes?.[document.protocol],\n );\n const version = s.selection.protocols.find(\n (p) => p.name === document.protocol,\n )?.version;\n if (key !== undefined && version !== undefined)\n s.documentStore.save(\n [s.documentStore.namespace ?? \"\", document.protocol, ...key],\n { version, value: document.value },\n );\n }\n }\n};\n\nconst publishIngested = (s: Session) => {\n publish(s);\n cacheDocuments(s);\n for (const listener of s.documentListeners) listener();\n wake(s);\n};\n\n// The refusal's watermark is exact: every held statement above it was never\n// admitted by the live record, and the first unposted seq being beyond\n// watermark+1 proves the record that admitted the missing prefix is gone —\n// its history settles lost and the lane clock restarts at the watermark.\nconst sessionLostInner = (s: Session, protocol: string, seqWm: number) => {\n const held = laneEntries(s, protocol);\n settleLost(s, held);\n s.durableSeq[protocol] = seqWm;\n const failed = laneOf(s.record, protocol).failed;\n setRecord(\n s,\n withLane(s.record, protocol, {\n nextSeq: seqWm + 1,\n commands: [],\n ...(failed !== undefined && { failed }),\n }),\n );\n if (\n held.length > 0 &&\n s.onSessionLost?.(held.map((p) => p.inv)) === \"requeue\"\n ) {\n for (const old of held) {\n enqueueInner(\n s,\n old.command,\n old.inv.params,\n () => {},\n () => {},\n );\n }\n }\n publish(s);\n wake(s);\n};\n\nconst selectionOf = (\n syn: StatewireSyn,\n): StatewireProtocol.Selection | undefined => {\n if (syn.version === undefined || syn.protocols === undefined)\n return undefined;\n return {\n version: syn.version,\n protocols: syn.protocols.map(({ name, version, record }) => {\n if (version === undefined)\n return protocolError(`hello lane ${name} has no version`);\n return { name, version, ...(record !== undefined && { record }) };\n }),\n };\n};\n\nconst handleHello = (\n s: Session,\n { ops, syn }: { ops: unknown[]; syn: StatewireSyn },\n) => {\n s.selection = selectionOf(syn);\n s.documents = { mode: null, documents: new Map() };\n ingestOps(s, ops);\n s.attach = \"attached\";\n s.attachEpoch += 1;\n s.frameFailures = 0;\n s.resumeAt = 0;\n const lanes = syn.protocols ?? [];\n s.ephemeral =\n lanes.length > 0 && lanes.every((lane) => lane.record === \"ephemeral\");\n if (s.ephemeral) s.deactivated = true;\n const attached = s.attachEntries;\n s.attachEntries = new Set();\n const reconcile = () => {\n if (s.shared) adoptStored(s);\n // Resending unsettled statements is exactly-once-safe: absorbed replays\n // re-emit their stored verdicts (applied while still in flight).\n for (const lane of lanes) {\n if (lane.record === \"ephemeral\") {\n s.ephemeralSeqs[lane.name] = Math.max(\n Object.hasOwn(s.ephemeralSeqs, lane.name)\n ? s.ephemeralSeqs[lane.name]!\n : 0,\n ...laneEntries(s, lane.name).map((p) => p.seq),\n );\n } else s.durableSeq[lane.name] = lane.seq ?? 0;\n }\n for (const entry of s.pending) entry.posted = attached.has(entry);\n syncBacklogInner(s);\n s.sessionKnown = true;\n };\n if (!s.shared || s.deactivated) {\n reconcile();\n publishIngested(s);\n void pump(s);\n return;\n }\n transactBackground(s, reconcile, () => {\n publishIngested(s);\n void pump(s);\n });\n};\n\nconst handleOps = (\n s: Session,\n { ops, cmds }: { ops: unknown[]; cmds: StatewireCmd[] },\n) => {\n ingestOps(s, ops);\n for (const cmd of cmds) handleCmd(s, cmd);\n syncBacklog(s);\n publishIngested(s);\n};\n\n// A retry-less {syn} refusal is the one session-loss verdict: a gap against\n// a durable lane's exact watermark settles that lane's history lost; a\n// pushback (retry present) or a gapless refusal only reconciles the resend queues.\nconst handleRefusal = (s: Session, syn: StatewireSyn) => {\n const lanes = (syn.protocols ?? []).filter(\n (lane): lane is { name: string; seq: number } => lane.seq !== undefined,\n );\n for (const { name, seq } of lanes) {\n const watermark = isEphemeral(s, name)\n ? seq\n : Math.max(seq, durableSeqOf(s, name));\n for (const entry of laneEntries(s, name))\n entry.posted = entry.seq <= watermark;\n }\n if (typeof syn.retry === \"number\") {\n s.resumeAt = Date.now() + retryHint(syn.retry);\n wake(s);\n void pump(s);\n return;\n }\n const gaps = lanes.filter(({ name, seq }) => {\n const first = laneEntries(s, name).find((p) => !p.posted);\n return (\n first !== undefined &&\n first.seq > Math.max(seq, durableSeqOf(s, name)) + 1\n );\n });\n for (const { name, seq } of gaps) {\n if (isEphemeral(s, name))\n protocolError(`gap on ephemeral lane ${name} after watermark ${seq}`);\n }\n if (gaps.length > 0) {\n transactBackground(\n s,\n () => {\n for (const { name, seq } of gaps) sessionLostInner(s, name, seq);\n },\n () => {\n wake(s);\n void pump(s);\n },\n );\n return;\n }\n wake(s);\n void pump(s);\n};\n\nconst handleDetach = (s: Session) => {\n if (s.attach === \"attached\") s.attach = \"detached\";\n s.ephemeralSeqs = {};\n if (s.ephemeral) ephemeralDetach(s);\n else detachEphemeralLanes(s);\n wake(s);\n};\n\nconst handleFinish = (s: Session, { reason }: { reason: string }) => {\n if (reason === \"reconnect\" || reason === \"error\") return;\n s.attach = \"finished\";\n settleAll(s, \"gone\");\n publish(s);\n wake(s);\n};\n\nconst isFinished = (s: Session) => s.attach === \"finished\";\n\ntype Lanes = {\n frame: StatewireFrame;\n entries: Pending[];\n};\n\n// A lane must be strictly consecutive within a frame: the first unposted run\n// per lane rides now, later runs ride follow-up frames. Ephemeral lanes ignore\n// the gate: they live on the attach and never wait for persistence.\nconst buildLanes = (\n s: Session,\n cmdGate: \"persisted\" | \"all\" | \"none\" = \"all\",\n): Lanes | null => {\n const entries: Pending[] = [];\n const last: Record<string, number> = {};\n const stopped = new Set<string>();\n for (const entry of s.pending) {\n if (entries.length >= MAX_COMMANDS_PER_FRAME) break;\n const protocol = entry.command.protocol;\n if (entry.posted || stopped.has(protocol)) continue;\n const gated =\n !isEphemeral(s, protocol) &&\n (cmdGate === \"none\" ||\n (cmdGate === \"persisted\" &&\n (s.persistedRecord?.clientId !== s.record.clientId ||\n entry.seq >= laneOf(s.persistedRecord, protocol).nextSeq)));\n if (\n gated ||\n (Object.hasOwn(last, protocol) && entry.seq !== last[protocol]! + 1)\n ) {\n stopped.add(protocol);\n continue;\n }\n last[protocol] = entry.seq;\n entries.push(entry);\n }\n if (entries.length === 0) return null;\n return {\n frame: {\n cmd: entries.map((p) => {\n const { produced: _produced, ...command } = p.command;\n return { ...command, seq: p.seq };\n }),\n },\n entries,\n };\n};\n\nconst takeAttachLanes = (s: Session): StatewireFrame | null => {\n s.attachEntries = new Set();\n const wanted = s.lanesOnAttach;\n s.lanesOnAttach = false;\n const lanes = buildLanes(s, wanted && s.sessionKnown ? \"persisted\" : \"none\");\n if (!lanes) return null;\n s.attachEntries = new Set(lanes.entries);\n for (const entry of lanes.entries) entry.attempted = true;\n return lanes.frame;\n};\n\nconst persistBeforeSend = (s: Session): void | Promise<void> => {\n if (s.storageError !== undefined) throw s.storageError;\n if (!s.hydrated) return s.ready!.then(() => persistBeforeSend(s));\n const record = s.record;\n try {\n const pending = s.store.flush?.();\n if (pending)\n return pending.then(\n () => {\n s.persistedRecord = record;\n },\n (cause: unknown) => {\n throw wrapStorageError(cause);\n },\n );\n s.persistedRecord = record;\n } catch (cause) {\n throw wrapStorageError(cause);\n }\n};\n\nconst pump = async (s: Session) => {\n if (s.pumping) return;\n s.pumping = true;\n try {\n while (s.running && !isFinished(s)) {\n if (!s.hydrated) await s.ready;\n const transport = s.transport;\n if (buildLanes(s) === null) return;\n if (s.attach !== \"attached\" || !transport) {\n if (\n (transport?.connection.status === \"standby\" &&\n transport.connection.reason === \"idle\") ||\n (transport?.parked && s.pending.length > 0)\n ) {\n transport.connection.reconnect();\n }\n await waitForWake(s);\n continue;\n }\n const resumeDelay = s.resumeAt - Date.now();\n if (resumeDelay > 0) {\n await sleepUntilWake(s, resumeDelay);\n continue;\n }\n const lanes = buildLanes(s);\n if (!lanes) continue;\n const epoch = s.attachEpoch;\n const persistence = persistBeforeSend(s);\n if (persistence) await persistence;\n if (!s.running || isFinished(s)) return;\n if (epoch !== s.attachEpoch || s.attach !== \"attached\") continue;\n for (const entry of lanes.entries) entry.attempted = true;\n let result;\n try {\n // Shared storage: the lock across the send keeps per-lane arrival\n // ordered across sharers during attach handover.\n const send = () => transport.send(lanes.frame);\n result = await (s.shared && !s.deactivated\n ? s.store.lock!(send)\n : send());\n } catch {\n if (!s.running || isFinished(s)) return;\n s.frameFailures += 1;\n await sleepUntilWake(s, backoff(s.frameFailures));\n continue;\n }\n if (!s.running) return;\n s.frameFailures = 0;\n if (result.type === \"ok\") {\n if (epoch === s.attachEpoch) {\n for (const entry of lanes.entries) {\n if (s.pending.includes(entry)) {\n entry.posted = true;\n s.lifecycle?.onPosted?.(entry.inv);\n }\n }\n }\n } else if (result.type === \"refusal\") {\n if (epoch === s.attachEpoch) handleRefusal(s, result.syn);\n } else if (result.type === \"stale-lease\") {\n // A POST outlived its attach: reattach first, the hello arbitrates.\n if (epoch === s.attachEpoch) {\n transport.connection.reconnect();\n await waitForWake(s);\n }\n } else if (result.type === \"no-lease\") {\n // No out-of-band write channel: the frame rides a fresh attach.\n if (epoch === s.attachEpoch) {\n s.lanesOnAttach = true;\n transport.connection.reconnect();\n while (s.running && !isFinished(s) && epoch === s.attachEpoch) {\n await waitForWake(s);\n }\n }\n }\n }\n } catch (error) {\n storageFailed(s, error);\n } finally {\n s.pumping = false;\n }\n};\n\nconst start = (s: Session) => {\n s.running = true;\n if (!s.hydrated) {\n void s.ready!.then(\n () => {\n if (s.running) start(s);\n },\n () => {},\n );\n return;\n }\n if (s.shared) {\n s.shared.unsubscribe = s.store.subscribe!(() => {\n transactBackground(s, () => consumeVerdicts(s));\n });\n s.running = true;\n transactBackground(\n s,\n () => {\n if (s.store.load() === null) s.store.save(s.record);\n s.recordPersisted = true;\n adoptStored(s);\n consumeVerdicts(s);\n },\n () => void pump(s),\n );\n return;\n }\n if (!s.recordPersisted) {\n s.recordPersisted = true;\n s.store.save(s.record);\n }\n adoptStored(s);\n s.running = true;\n void pump(s);\n};\n\nconst stop = (s: Session) => {\n s.running = false;\n if (s.shared) {\n s.shared.unsubscribe?.();\n s.shared.unsubscribe = null;\n }\n wake(s);\n settleAll(s, \"unmount\");\n};\n\nconst setTransport = (s: Session, transport: RemoteLink) => {\n if (s.transport === transport) return;\n s.transport = transport;\n wake(s);\n};\n\nconst enqueueInner = (\n s: Session,\n command: WireCommand,\n params: readonly unknown[],\n resolve: (payload: unknown) => void,\n reject: (error: unknown) => void,\n) => {\n const protocol = command.protocol;\n const ephemeral = isEphemeral(s, protocol);\n const seq = ephemeral\n ? (Object.hasOwn(s.ephemeralSeqs, protocol)\n ? s.ephemeralSeqs[protocol]!\n : 0) + 1\n : Math.max(\n laneOf(s.record, protocol).nextSeq,\n durableSeqOf(s, protocol) + 1,\n );\n const entry: Pending = {\n seq,\n command,\n inv: {\n protocol,\n method: command.method,\n params,\n ts: Date.now(),\n seq,\n clientId: s.record.clientId,\n },\n attempted: false,\n posted: false,\n applied: false,\n resolve,\n reject,\n };\n s.pending.push(entry);\n if (ephemeral) s.ephemeralSeqs[protocol] = seq;\n else\n setRecord(\n s,\n withLane(s.record, protocol, {\n ...laneOf(s.record, protocol),\n nextSeq: seq + 1,\n commands: mergeBacklog(s, protocol),\n }),\n );\n s.lifecycle?.onStart(entry.inv);\n};\n\nconst enqueue = (\n s: Session,\n command: WireCommand,\n params: readonly unknown[],\n resolve: (payload: unknown) => void,\n reject: (error: unknown) => void,\n) => {\n if (!s.shared) {\n enqueueInner(s, command, params, resolve, reject);\n wake(s);\n void pump(s);\n return;\n }\n void transact(s, () => {\n // A send queued behind the lock before this tab unmounted still lands in\n // the shared journal: another sharer adopts and replays it.\n if (isFinished(s)) {\n reject(new StatewireSendError({ fate: \"aborted\", cause: \"stream-gone\" }));\n return;\n }\n enqueueInner(s, command, params, resolve, reject);\n }).then(() => {\n wake(s);\n void pump(s);\n }, reject);\n};\n\nconst offered = (s: Session, protocol: string) => {\n const offers = protocolOffers(s.options);\n return offers === \"*\" || offers.some((offer) => offer.name === protocol);\n};\n\n// A stored command may have reached a server: attempted settles it lost,\n// never aborted, when a channel death ends the session.\nconst adoptStored = (s: Session) => {\n let adopted = false;\n for (const [protocol, lane] of Object.entries(s.record.lanes)) {\n if (!offered(s, protocol)) continue;\n const known = new Set(laneEntries(s, protocol).map((p) => p.seq));\n for (const { seq, ...command } of lane.commands) {\n if (known.has(seq)) continue;\n const params =\n command.meta === undefined\n ? command.params\n : (reviveValue([...command.params], command.meta) as unknown[]);\n const entry: Pending = {\n seq,\n command: { protocol, ...command },\n inv: {\n protocol,\n method: command.method,\n params,\n ts: Date.now(),\n seq,\n clientId: s.record.clientId,\n },\n attempted: true,\n posted: false,\n applied: false,\n resolve: () => {},\n reject: () => {},\n };\n s.pending.push(entry);\n s.lifecycle?.onStart(entry.inv);\n adopted = true;\n }\n }\n if (adopted) s.pending.sort((a, b) => a.seq - b.seq);\n};\n\nconst sendCommand = (\n s: Session,\n method: string,\n params: readonly unknown[],\n protocol = s.options.protocol ?? DEFAULT_PROTOCOL,\n): Promise<unknown> => {\n const negotiated = s.selection\n ? s.selection.protocols.some((p) => p.name === protocol)\n : offered(s, protocol);\n if (!negotiated)\n throw new Error(`statewire: protocol \"${protocol}\" is not negotiated`);\n if (!s.hydrated) {\n const result = s.ready!.then(() =>\n sendCommand(s, method, params, protocol),\n );\n result.catch(() => {});\n return result;\n }\n if (s.storageError !== undefined) {\n const result = Promise.reject(s.storageError);\n result.catch(() => {});\n return result;\n }\n if (!s.running) {\n return rejectedSend({ fate: \"aborted\", cause: \"unmount\" });\n }\n if (isFinished(s)) {\n return rejectedSend({ fate: \"aborted\", cause: \"stream-gone\" });\n }\n const result = new Promise<unknown>((resolve, reject) => {\n const { params: encoded, meta } = encodeParams(params);\n enqueue(\n s,\n {\n protocol,\n produced: {\n wire: s.options.wireVersion ?? { version: WIRE_VERSION },\n protocols:\n protocolOffers(s.options) === \"*\" && s.selection\n ? s.selection.protocols\n : protocolOffers(s.options),\n },\n method,\n params: encoded,\n ...(meta !== undefined && { meta }),\n },\n params,\n resolve,\n reject,\n );\n });\n result.catch(() => {});\n return result;\n};\n\nconst findFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): StatewireClient.FailedCommand | undefined =>\n (laneOf(s.record, entry.protocol).failed ?? []).find(\n (f) =>\n f.seq === entry.seq && f.ts === entry.ts && f.command === entry.command,\n );\n\nconst unknownFailed = (entry: StatewireClient.FailedCommand) =>\n new Error(`statewire: unknown failed command \"${entry.command}\"`);\n\nconst takeFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): StatewireClient.FailedCommand => {\n const lane = laneOf(s.record, entry.protocol);\n const found = findFailed(s, entry);\n if (found === undefined) throw unknownFailed(entry);\n setRecord(\n s,\n withLane(s.record, entry.protocol, {\n ...lane,\n failed: (lane.failed ?? []).filter((f) => f !== found),\n }),\n );\n s.notify();\n return found;\n};\n\nexport const discardFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): void => {\n if (!s.shared) {\n takeFailed(s, entry);\n return;\n }\n if (findFailed(s, entry) === undefined) throw unknownFailed(entry);\n transactBackground(s, () => {\n if (findFailed(s, entry) !== undefined) takeFailed(s, entry);\n });\n};\n\nexport const retryFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): Promise<unknown> => {\n if (!s.running) {\n return rejectedSend({ fate: \"aborted\", cause: \"unmount\" });\n }\n if (isFinished(s)) {\n return rejectedSend({ fate: \"aborted\", cause: \"stream-gone\" });\n }\n const found = findFailed(s, entry);\n if (found === undefined) throw unknownFailed(entry);\n const params =\n found.meta === undefined\n ? found.params\n : (reviveValue([...found.params], found.meta) as unknown[]);\n const result = new Promise<unknown>((resolve, reject) => {\n const retry = () => {\n if (!s.running) {\n reject(new StatewireSendError({ fate: \"aborted\", cause: \"unmount\" }));\n return;\n }\n if (isFinished(s)) {\n reject(\n new StatewireSendError({ fate: \"aborted\", cause: \"stream-gone\" }),\n );\n return;\n }\n const current = findFailed(s, entry);\n if (current === undefined) {\n reject(unknownFailed(entry));\n return;\n }\n takeFailed(s, current);\n enqueueInner(\n s,\n {\n protocol: current.protocol,\n ...(current.produced !== undefined && { produced: current.produced }),\n method: current.command,\n params: [...current.params],\n ...(current.meta !== undefined && { meta: current.meta }),\n },\n params,\n resolve,\n reject,\n );\n };\n if (!s.shared) {\n retry();\n wake(s);\n void pump(s);\n return;\n }\n void transact(s, retry).then(() => {\n wake(s);\n void pump(s);\n }, reject);\n });\n result.catch(() => {});\n return result;\n};\n\nexport const documentSource = (s: Session): StatewireDocuments.Source => ({\n get: (protocol, key, prefix = s.options.keyPrefixes?.[protocol]) => {\n const mounted = findDocument(s.documents, protocol, key, prefix);\n if (mounted !== undefined) return mounted.value;\n if (!s.documentStore || key === undefined) return undefined;\n const absolute = resolveDocumentKey(key, prefix);\n if (absolute === undefined) return undefined;\n const cached = s.documentStore.load([\n s.documentStore.namespace ?? \"\",\n protocol,\n ...absolute,\n ]);\n if (cached === undefined) return undefined;\n const offers = protocolOffers(s.options);\n const offer =\n offers === \"*\"\n ? s.selection?.protocols.find((p) => p.name === protocol)\n : offers.find((p) => p.name === protocol);\n return offer !== undefined && inRange(cached.version, offer)\n ? cached.value\n : undefined;\n },\n list: () => s.documents.documents,\n subscribe: (listener) => {\n s.documentListeners.add(listener);\n return () => {\n s.documentListeners.delete(listener);\n };\n },\n});\n\nexport const invokeProtocol = (\n s: Session,\n protocol: string,\n method: string,\n params: readonly unknown[],\n) => sendCommand(s, method, params, protocol);\n\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: NonNullable<StatewireClient.SessionCommand[\"produced\"]>,\n) => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n const previous = command.produced.protocols;\n if (current.protocols === \"*\") return true;\n if (previous === \"*\") return false;\n const produced = previous.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\nconst validateLanes = (record: StatewireClient.SessionRecord) => {\n if (\n typeof record.lanes !== \"object\" ||\n record.lanes === null ||\n Object.values(record.lanes).some((lane) => !Array.isArray(lane.commands))\n )\n throw new Error(\n \"statewire: session storage loaded a record without command lanes\",\n );\n};\n\nconst loadSessionRecord = (\n store: StatewireClient.SessionStorage,\n options: StatewireSessionOptions,\n) => {\n let stored = store.load();\n if (stored !== null) validateLanes(stored);\n const current = {\n wire: options.wireVersion ?? { version: WIRE_VERSION },\n protocols: protocolOffers(options),\n };\n const compatible = (record: StatewireClient.SessionRecord) =>\n Object.entries(record.lanes).every(([protocol, lane]) =>\n lane.commands.every((command) =>\n storedCommandCompatible(protocol, command, current),\n ),\n );\n if (stored !== null && !compatible(stored)) {\n if (!store.migrate)\n throw new Error(\"statewire: stored commands require a storage migration\");\n stored = store.migrate(stored, current);\n if (stored !== null) {\n validateLanes(stored);\n if (!compatible(stored))\n throw new Error(\"statewire: migrated commands are incompatible\");\n store.save(stored);\n }\n }\n const record = stored ?? { clientId: newClientId(), lanes: {} };\n if (stored === null) store.save(record);\n return record;\n};\n\nexport const useStatewireSession = (\n options: StatewireSessionOptions,\n): Session => {\n const [defaultStore] = useState(createMemorySessionStore);\n const mounted = useContext(SessionStorageContext);\n const documentStore = useContext(DocumentStorageContext);\n if (options.sessionStore !== undefined && mounted !== undefined) {\n throw new Error(\n \"statewire: session storage is set twice — drop the transport's sessionStore or the client's storage.session\",\n );\n }\n const store = options.sessionStore ?? mounted ?? defaultStore;\n if ((store.lock === undefined) !== (store.subscribe === undefined)) {\n throw new Error(\n \"statewire: session storage must provide lock and subscribe together\",\n );\n }\n const [s] = useState((): Session => {\n const record =\n store.ready === undefined\n ? loadSessionRecord(store, options)\n : { clientId: newClientId(), lanes: {} };\n const session: Session = {\n options,\n selection: undefined,\n record,\n ctx: {\n beforeAttach: () => persistBeforeSend(session),\n get clientId() {\n return session.record.clientId;\n },\n takeAttachLanes: () => takeAttachLanes(session),\n onHello: (args) => handleHello(session, args),\n onOps: (args) => handleOps(session, args),\n onCmds: (cmds) => handleCmds(session, cmds),\n onRefusal: (syn) => handleRefusal(session, syn),\n onIdle: (level) => setIdle(session, level),\n onDetach: () => handleDetach(session),\n onFinish: (args) => handleFinish(session, args),\n },\n recordPersisted: store.ready === undefined,\n hydrated: store.ready === undefined,\n ready: undefined,\n storageError: undefined,\n persistedRecord: store.ready === undefined ? record : null,\n store,\n documentStore,\n shared:\n store.lock !== undefined\n ? { txq: Promise.resolve(), parked: [], unsubscribe: null }\n : false,\n ephemeral: false,\n deactivated: false,\n sessionKnown: false,\n durableSeq: {},\n ephemeralSeqs: {},\n resumeAt: 0,\n idle: false,\n onSessionLost: undefined,\n onDone: undefined,\n lanesOnAttach: false,\n attachEntries: new Set(),\n frameFailures: 0,\n pending: [],\n failedList: [],\n failedParts: [],\n canonical: undefined,\n documentListeners: new Set(),\n documents: { mode: null, documents: new Map() },\n lastPublished: undefined,\n changed: [],\n source: {\n snapshot: () => session.canonical,\n takeChanged: () => {\n const changed = session.changed;\n session.changed = [];\n return changed;\n },\n setOnChange: (listener) => {\n session.notify = listener ?? (() => {});\n },\n },\n attach: \"detached\",\n attachEpoch: 0,\n running: false,\n pumping: false,\n transport: null,\n waiters: [],\n lifecycle: null,\n notify: () => {},\n commands: createMethodProxy((method, params) =>\n sendCommand(session, method, params),\n ),\n };\n if (store.ready !== undefined) {\n session.ready = store.ready.then(() => {\n session.record = loadSessionRecord(store, session.options);\n session.recordPersisted = true;\n session.hydrated = true;\n if (session.running) session.notify();\n });\n session.ready = session.ready.catch((cause: unknown) => {\n const error = wrapStorageError(cause);\n session.storageError = error;\n session.transport?.storageFailed(error);\n throw error;\n });\n session.ready.catch(() => {});\n }\n bindCommandsHost(session.commands, {\n setListener: (listener) => {\n session.lifecycle = listener;\n },\n });\n return session;\n });\n if ((store.lock !== undefined) !== (s.shared !== false)) {\n throw new Error(\n \"statewire: session storage changed sharedness across renders — lock/subscribe must be present from the first render or never\",\n );\n }\n s.options = options;\n s.store = store;\n s.documentStore = documentStore;\n s.onSessionLost = options.onSessionLost;\n s.onDone = options.onDone;\n const keyPrefixes = JSON.stringify(options.keyPrefixes);\n useEffect(() => {\n cacheDocuments(s);\n }, [s, documentStore, keyPrefixes]);\n useEffect(\n () =>\n documentStore?.subscribe?.(() => {\n for (const listener of s.documentListeners) listener();\n }),\n [s, documentStore],\n );\n useEffect(() => {\n start(s);\n return () => stop(s);\n }, [s]);\n return s;\n};\n\nexport { setTransport };\n"],"mappings":";;;;;;;;;;;;;;;AA+DA,MAAM0D,iBAAiBC,YAA2B;CAChD,MAAM,IAAIC,MAAM,8BAA8BD,SAAS;AACzD;AAEA,MAAME,gBACJC,YACqB;CACrB,MAAMG,SAASD,QAAQR,OAAgB,IAAIrB,mBAAmB2B,OAAO,CAAC;CACtEG,OAAOC,YAAY,CAAC,CAAC;CACrB,OAAOD;AACT;AAgEA,MAAMkE,aAA0C;CAAEE,SAAS;CAAGH,UAAU,CAAA;AAAG;AAE3E,MAAMI,UACJjD,QACA7C,aAEA+F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
|
|
1
|
+
{"version":3,"file":"session.js","names":["encodeContext","wrapStorageError","DEFAULT_PROTOCOL","WIRE_VERSION","protocolOffers","inRange","StatewireProtocol","applyDocumentOps","mainDocument","findDocument","resolveDocumentKey","StatewireDocuments","useContext","useEffect","useState","StatewirePath","MAX_COMMANDS_PER_FRAME","TERMINAL","StatewireCmd","StatewireSyn","encodeParams","reviveResponse","reviveValue","bindCommandsHost","CommandsInvocation","CommandsListener","Statewire","StatewireClient","DocumentStorageContext","SessionStorageContext","createMemorySessionStore","backoff","retryHint","createMethodProxy","randomId","newClientId","StatewireSendError","RemoteLink","StatewireFrame","StatewireRemoteProps","WireCommand","protocol","produced","NonNullable","SessionCommand","method","params","meta","Pending","seq","command","inv","attempted","posted","applied","resolve","payload","reject","error","protocolError","message","Error","rejectedSend","failure","SendFailure","Promise","result","catch","AttachState","StatewireSessionOptions","Options","context","Readonly","Record","Context","sessionStore","SessionStorage","onSessionLost","OnSessionLost","onDone","Shared","txq","syncQueued","parked","verdict","SessionVerdict","unsubscribe","Session","options","configuredContext","contexts","Map","ReturnType","dirtyContexts","Set","attachContexts","selection","Selection","record","SessionRecord","ctx","recordPersisted","hydrated","ready","storageError","persistedRecord","store","documentStore","Storage","shared","ephemeral","deactivated","sessionKnown","durableSeq","ephemeralSeqs","resumeAt","idle","lanesOnAttach","attachEntries","ReadonlySet","frameFailures","pending","failedList","FailedCommand","failedParts","canonical","documentListeners","documents","State","lastPublished","changed","source","StateSource","attach","attachEpoch","running","pumping","transport","waiters","lifecycle","notify","commands","EMPTY_LANE","SessionLane","nextSeq","laneOf","Object","hasOwn","lanes","withLane","lane","isEphemeral","s","protocols","some","p","name","durableSeqOf","laneEntries","filter","publish","wake","waiter","waitForWake","r","push","sleepUntilWake","delayMs","clearTimeout","timer","setTimeout","w","storageFailed","cause","entry","setRecord","save","toStored","_protocol","backlog","map","mergeBacklog","own","known","foreign","c","has","sort","a","b","durableLanes","keys","MAX_PARKED_VERDICTS","syncBacklogInner","splice","parkedHere","v","parkedSeqs","verdicts","length","slice","unchanged","every","i","undefined","syncBacklog","transact","fn","run","then","lock","stored","load","clientId","adoptReset","boundRecord","persistence","flush","transactBackground","done","setIdle","level","cover","onApplied","onCovered","failedCommands","parts","values","flatMap","failed","same","part","flat","MAX_FAILED_RETAINED","boundFailed","ts","entries","retainFailedInner","retainFailed","settleEntry","outcome","ok","onSettle","type","rides","settleAll","detach","const","batch","detachFailure","predecessorLost","fate","settleLost","requeue","survivors","old","enqueueInner","rebaseRecord","adopt","held","previous","current","pump","resetRecord","connection","reconnect","ephemeralDetach","detachEphemeralLanes","includes","rejectedFailure","cmd","code","outcomeOf","String","settleVerdict","TERMINAL_CMD_TYPES","parkVerdict","handleCmd","dur","watermark","Math","max","find","consumeVerdicts","consumed","add","size","handleCmds","cmds","ingestOps","ops","next","get","value","applicationProtocols","fromEntries","id","d","key","JSON","stringify","changedPaths","cacheDocuments","document","keyPrefixes","version","namespace","publishIngested","listener","sessionLostInner","seqWm","selectionOf","syn","handleHello","delete","clear","mode","attached","reconcile","adoptStored","handleOps","handleRefusal","retry","Date","now","gaps","first","handleDetach","handleFinish","reason","isFinished","Lanes","frame","buildLanes","cmdGate","last","stopped","gated","_produced","takeAttachLanes","wanted","persistBeforeSend","status","resumeDelay","epoch","send","onPosted","start","subscribe","stop","setTransport","onStart","enqueue","offered","offers","offer","adopted","structuredClone","sendCommand","negotiated","encoded","wire","wireVersion","findFailed","f","unknownFailed","takeFailed","found","discardFailed","retryFailed","documentSource","Source","prefix","mounted","absolute","cached","list","invokeProtocol","storedCommandCompatible","validateLanes","Array","isArray","loadSessionRecord","compatible","migrate","setContext","set","useStatewireSession","defaultStore","session","beforeAttach","onHello","args","onOps","onCmds","onRefusal","onIdle","onDetach","onFinish","snapshot","takeChanged","setOnChange","setListener"],"sources":["../../src/client/session.ts"],"sourcesContent":["import { encodeContext } from \"../wire/context\";\nimport { wrapStorageError } from \"./storageError\";\nimport {\n DEFAULT_PROTOCOL,\n WIRE_VERSION,\n protocolOffers,\n inRange,\n} from \"../wire/protocol\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport {\n applyDocumentOps,\n mainDocument,\n findDocument,\n resolveDocumentKey,\n} from \"../wire/documents\";\nimport type { StatewireDocuments } from \"../wire/documents\";\nimport { useContext, useEffect, useState } from \"react\";\n\nimport type { StatewirePath } from \"../wire/ops\";\nimport { MAX_COMMANDS_PER_FRAME } from \"../wire/limits\";\nimport { TERMINAL } from \"./connection\";\nimport type { StatewireCmd, StatewireSyn } from \"./connection\";\nimport { encodeParams, reviveResponse, reviveValue } from \"../wire/meta\";\nimport { bindCommandsHost } from \"../host/host\";\nimport type { CommandsInvocation, CommandsListener } from \"../host/host\";\nimport type { Statewire } from \"../types\";\nimport type { StatewireClient } from \"../statewire\";\nimport {\n DocumentStorageContext,\n SessionStorageContext,\n createMemorySessionStore,\n} from \"./sessionStore\";\nimport { backoff, retryHint } from \"./timing\";\nimport { createMethodProxy } from \"../util/methodProxy\";\nimport { randomId as newClientId } from \"../util/randomId\";\nimport { StatewireSendError } from \"../types\";\nimport type {\n RemoteLink,\n StatewireFrame,\n StatewireRemoteProps,\n} from \"../transports/sse\";\n\ntype WireCommand = {\n protocol: string;\n produced?: NonNullable<StatewireClient.SessionCommand[\"produced\"]>;\n method: string;\n params: unknown[];\n meta?: unknown;\n};\n\ntype Pending = {\n readonly seq: number;\n readonly command: WireCommand;\n readonly inv: CommandsInvocation;\n /** A send carrying this statement may have reached the server. */\n attempted: boolean;\n /** In the resend queue when false. */\n posted: boolean;\n /** The server acknowledged admission; the terminal verdict is still due. */\n applied: boolean;\n resolve: (payload: unknown) => void;\n reject: (error: unknown) => void;\n};\n\nconst protocolError = (message: string): never => {\n throw new Error(`statewire: protocol error: ${message}`);\n};\n\nconst rejectedSend = (\n failure: StatewireClient.SendFailure,\n): Promise<unknown> => {\n const result = Promise.reject<unknown>(new StatewireSendError(failure));\n result.catch(() => {});\n return result;\n};\n\ntype AttachState = \"detached\" | \"attached\" | \"finished\";\n\nexport type StatewireSessionOptions = StatewireProtocol.Options & {\n context?: Readonly<Record<string, Statewire.Context>>;\n sessionStore?: StatewireClient.SessionStorage | undefined;\n onSessionLost?: StatewireClient.OnSessionLost | undefined;\n onDone?: (() => void) | undefined;\n};\n\ntype Shared = {\n txq: Promise<void>;\n syncQueued: boolean;\n parked: { protocol: string; verdict: StatewireClient.SessionVerdict }[];\n unsubscribe: (() => void) | null;\n};\n\ntype Session = {\n options: StatewireSessionOptions;\n configuredContext: StatewireSessionOptions[\"context\"];\n contexts: Map<string, ReturnType<typeof encodeContext>>;\n dirtyContexts: Set<string>;\n attachContexts: Map<string, ReturnType<typeof encodeContext>>;\n selection: StatewireProtocol.Selection | undefined;\n record: StatewireClient.SessionRecord;\n ctx: StatewireRemoteProps;\n recordPersisted: boolean;\n hydrated: boolean;\n ready: Promise<void> | undefined;\n storageError: unknown;\n persistedRecord: StatewireClient.SessionRecord | null;\n store: StatewireClient.SessionStorage;\n documentStore: StatewireDocuments.Storage | undefined;\n shared: Shared | false;\n /** Every selected lane is ephemeral: the record dies with the attach. */\n ephemeral: boolean;\n /** An ephemeral record died with its attach: the storage is off for good. */\n deactivated: boolean;\n sessionKnown: boolean;\n durableSeq: Record<string, number>;\n /** Ephemeral lane clocks: restart at 1 on every attach. */\n ephemeralSeqs: Record<string, number>;\n resumeAt: number;\n idle: boolean;\n onSessionLost: StatewireClient.OnSessionLost | undefined;\n onDone: (() => void) | undefined;\n lanesOnAttach: boolean;\n attachEntries: ReadonlySet<Pending>;\n frameFailures: number;\n pending: Pending[];\n failedList: readonly StatewireClient.FailedCommand[];\n failedParts: readonly (readonly StatewireClient.FailedCommand[])[];\n canonical: unknown;\n documentListeners: Set<() => void>;\n documents: StatewireDocuments.State;\n lastPublished: unknown;\n changed: StatewirePath[];\n source: Statewire.StateSource;\n attach: AttachState;\n attachEpoch: number;\n running: boolean;\n pumping: boolean;\n transport: RemoteLink | null;\n waiters: (() => void)[];\n lifecycle: CommandsListener | null;\n notify: () => void;\n commands: Record<string, (...params: unknown[]) => Promise<unknown>>;\n};\n\nconst EMPTY_LANE: StatewireClient.SessionLane = { nextSeq: 1, commands: [] };\n\nconst laneOf = (\n record: StatewireClient.SessionRecord,\n protocol: string,\n): StatewireClient.SessionLane =>\n Object.hasOwn(record.lanes, protocol) ? record.lanes[protocol]! : EMPTY_LANE;\n\nconst withLane = (\n record: StatewireClient.SessionRecord,\n protocol: string,\n lane: StatewireClient.SessionLane,\n): StatewireClient.SessionRecord => ({\n ...record,\n lanes: { ...record.lanes, [protocol]: lane },\n});\n\nconst isEphemeral = (s: Session, protocol: string) =>\n s.selection?.protocols.some(\n (p) => p.name === protocol && p.record === \"ephemeral\",\n ) ?? false;\n\nconst durableSeqOf = (s: Session, protocol: string) =>\n Object.hasOwn(s.durableSeq, protocol) ? s.durableSeq[protocol]! : 0;\n\nconst laneEntries = (s: Session, protocol: string) =>\n s.pending.filter((p) => p.command.protocol === protocol);\n\nconst publish = (s: Session) => {\n if (s.canonical === s.lastPublished) return;\n s.lastPublished = s.canonical;\n s.notify();\n};\n\nconst wake = (s: Session) => {\n const waiters = s.waiters;\n s.waiters = [];\n for (const waiter of waiters) waiter();\n};\n\nconst waitForWake = (s: Session) => new Promise<void>((r) => s.waiters.push(r));\n\nconst sleepUntilWake = (s: Session, delayMs: number) =>\n new Promise<void>((resolve) => {\n const waiter = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n s.waiters = s.waiters.filter((w) => w !== waiter);\n resolve();\n }, delayMs);\n s.waiters.push(waiter);\n });\n\nconst storageFailed = (s: Session, cause: unknown) => {\n const error = wrapStorageError(cause);\n s.storageError = error;\n for (const entry of s.pending) entry.reject(error);\n s.transport?.storageFailed(error);\n};\n\nconst setRecord = (s: Session, record: StatewireClient.SessionRecord) => {\n if (!s.deactivated) {\n try {\n s.store.save(record);\n } catch (cause) {\n storageFailed(s, cause);\n throw s.storageError;\n }\n }\n s.record = record;\n};\n\nconst toStored = (p: Pending): StatewireClient.SessionCommand => {\n const { protocol: _protocol, ...command } = p.command;\n return { seq: p.seq, ...command };\n};\n\nconst backlog = (\n s: Session,\n protocol: string,\n): StatewireClient.SessionCommand[] =>\n laneEntries(s, protocol)\n .filter((p) => p.seq > durableSeqOf(s, protocol))\n .map(toStored);\n\nconst mergeBacklog = (\n s: Session,\n protocol: string,\n): StatewireClient.SessionCommand[] => {\n const own = backlog(s, protocol);\n if (!s.shared) return own;\n const known = new Set(laneEntries(s, protocol).map((p) => p.seq));\n const foreign = laneOf(s.record, protocol).commands.filter(\n (c) => !known.has(c.seq) && c.seq > durableSeqOf(s, protocol),\n );\n return [...foreign, ...own].sort((a, b) => a.seq - b.seq);\n};\n\nconst durableLanes = (s: Session): string[] => [\n ...new Set([\n ...Object.keys(s.record.lanes),\n ...s.pending\n .map((p) => p.command.protocol)\n .filter((protocol) => !isEphemeral(s, protocol)),\n ]),\n];\n\nconst MAX_PARKED_VERDICTS = 64;\n\n// Storage holds what a reload must resend: a command leaves at its dur, at a\n// server verdict, or at a record reset — never at a local channel death.\nconst syncBacklogInner = (s: Session) => {\n const parked = s.shared ? s.shared.parked.splice(0) : [];\n let lanes = s.record.lanes;\n for (const protocol of durableLanes(s)) {\n const lane = laneOf(s.record, protocol);\n const parkedHere = parked\n .filter((v) => v.protocol === protocol)\n .map((v) => v.verdict);\n const parkedSeqs = new Set(parkedHere.map((v) => v.seq));\n const commands = mergeBacklog(s, protocol).filter(\n (c) => !parkedSeqs.has(c.seq),\n );\n const verdicts =\n parkedHere.length > 0\n ? [...(lane.verdicts ?? []), ...parkedHere].slice(-MAX_PARKED_VERDICTS)\n : lane.verdicts;\n const unchanged =\n verdicts === lane.verdicts &&\n commands.length === lane.commands.length &&\n commands.every((c, i) => c.seq === lane.commands[i]!.seq);\n if (unchanged) continue;\n lanes = {\n ...lanes,\n [protocol]: {\n ...lane,\n commands,\n ...(verdicts !== undefined && { verdicts }),\n },\n };\n }\n if (lanes !== s.record.lanes) setRecord(s, { ...s.record, lanes });\n};\n\nconst syncBacklog = (s: Session) => {\n const shared = s.shared;\n if (!shared) return syncBacklogInner(s);\n if (shared.syncQueued) return;\n shared.syncQueued = true;\n void transact(s, () => {\n shared.syncQueued = false;\n syncBacklogInner(s);\n }).catch(() => {\n shared.syncQueued = false;\n });\n};\n\n// Every record mutation over shared storage is a locked read-modify-write.\nconst transact = (s: Session, fn: () => void): Promise<void> => {\n if (!s.shared || s.deactivated) {\n fn();\n return Promise.resolve();\n }\n const shared = s.shared;\n const run = shared.txq.then(() =>\n s.store.lock!(async () => {\n const stored = s.store.load();\n if (stored !== null && stored.clientId !== s.record.clientId) {\n adoptReset(s, stored);\n } else if (stored !== null) {\n s.record = boundRecord(stored);\n }\n fn();\n const persistence = s.store.flush?.();\n if (persistence) await persistence;\n }),\n );\n const result = run.catch((cause: unknown) => {\n storageFailed(s, cause);\n throw s.storageError;\n });\n shared.txq = result.then(\n () => {},\n () => {},\n );\n return result;\n};\n\nconst transactBackground = (s: Session, fn: () => void, done?: () => void) => {\n void transact(s, fn).then(done, () => {});\n};\n\nconst setIdle = (s: Session, level: boolean) => {\n if (level === s.idle) return;\n s.idle = level;\n s.notify();\n if (level) s.onDone?.();\n};\n\nconst cover = (s: Session, entry: Pending) => {\n if (entry.applied) return;\n entry.applied = true;\n s.lifecycle?.onApplied(entry.inv);\n s.lifecycle?.onCovered?.(entry.inv);\n};\n\nexport const failedCommands = (\n s: Session,\n): readonly StatewireClient.FailedCommand[] => {\n const parts = Object.values(s.record.lanes).flatMap((lane) =>\n lane.failed === undefined ? [] : [lane.failed],\n );\n const same =\n parts.length === s.failedParts.length &&\n parts.every((part, i) => part === s.failedParts[i]);\n if (!same) {\n s.failedParts = parts;\n s.failedList = parts.flat();\n }\n return s.failedList;\n};\n\nexport const MAX_FAILED_RETAINED = 256;\n\nconst boundFailed = (failed: readonly StatewireClient.FailedCommand[]) =>\n failed.length > MAX_FAILED_RETAINED\n ? [...failed].sort((a, b) => a.ts - b.ts).slice(-MAX_FAILED_RETAINED)\n : failed;\n\nconst boundRecord = (record: StatewireClient.SessionRecord) => {\n let lanes = record.lanes;\n for (const [protocol, lane] of Object.entries(lanes)) {\n if (lane.failed !== undefined && lane.failed.length > MAX_FAILED_RETAINED)\n lanes = {\n ...lanes,\n [protocol]: { ...lane, failed: boundFailed(lane.failed) },\n };\n }\n return lanes === record.lanes ? record : { ...record, lanes };\n};\n\nconst retainFailedInner = (\n s: Session,\n entry: Pending,\n failure: StatewireClient.SendFailure,\n) => {\n const lane = laneOf(s.record, entry.command.protocol);\n setRecord(\n s,\n withLane(s.record, entry.command.protocol, {\n ...lane,\n failed: boundFailed([\n ...(lane.failed ?? []),\n {\n protocol: entry.command.protocol,\n ...(entry.command.produced !== undefined && {\n produced: entry.command.produced,\n }),\n command: entry.command.method,\n params: entry.command.params,\n ...(entry.command.meta !== undefined && { meta: entry.command.meta }),\n failure,\n ts: entry.inv.ts,\n seq: entry.seq,\n },\n ]),\n }),\n );\n s.notify();\n};\n\nconst retainFailed = (\n s: Session,\n entry: Pending,\n failure: StatewireClient.SendFailure,\n) => {\n if (!s.shared) {\n retainFailedInner(s, entry, failure);\n return;\n }\n transactBackground(s, () => retainFailedInner(s, entry, failure));\n};\n\nconst settleEntry = (\n s: Session,\n entry: Pending,\n outcome:\n | { ok: true; payload: unknown }\n | { ok: false; failure: StatewireClient.SendFailure },\n) => {\n s.pending = s.pending.filter((p) => p !== entry);\n if (outcome.ok) {\n entry.resolve(outcome.payload);\n s.lifecycle?.onSettle(entry.inv, {\n type: \"accepted\",\n payload: outcome.payload,\n });\n } else {\n // A statement the record still carries resends on the next attach; only\n // invocations the record no longer owns become failed history.\n const rides =\n (outcome.failure.cause === \"unmount\" ||\n outcome.failure.cause === \"stream-gone\") &&\n entry.seq > durableSeqOf(s, entry.command.protocol);\n if (!rides && !isEphemeral(s, entry.command.protocol))\n retainFailed(s, entry, outcome.failure);\n entry.reject(new StatewireSendError(outcome.failure));\n s.lifecycle?.onSettle(entry.inv, {\n type: \"rejected\",\n error: new StatewireSendError(outcome.failure),\n });\n }\n};\n\nconst settleAll = (s: Session, detach: \"unmount\" | \"gone\") => {\n const cause =\n detach === \"unmount\" ? (\"unmount\" as const) : (\"stream-gone\" as const);\n const batch = s.pending;\n const detachFailure = (entry: Pending): StatewireClient.SendFailure => {\n if (!entry.attempted) {\n const predecessorLost = batch.some(\n (p) =>\n p.command.protocol === entry.command.protocol &&\n p.seq < entry.seq &&\n p.attempted,\n );\n return predecessorLost\n ? { fate: \"aborted\", cause, predecessorLost }\n : { fate: \"aborted\", cause };\n }\n return { fate: \"lost\", cause };\n };\n for (const entry of [...batch]) {\n s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, { ok: false, failure: detachFailure(entry) });\n }\n};\n\nconst settleLost = (s: Session, entries: Pending[]) => {\n for (const entry of entries) {\n s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, {\n ok: false,\n failure: { fate: \"lost\", cause: \"session-lost\" },\n });\n }\n};\n\nconst requeue = (s: Session, survivors: Pending[]) => {\n for (const old of survivors) {\n s.lifecycle?.onCovered?.(old.inv);\n enqueueInner(s, old.command, old.inv.params, old.resolve, old.reject);\n }\n};\n\n// The server-side record's dedup memory is gone: history that may have\n// reached a server settles lost — the new hello's snapshot is the only\n// truth about what survived — and never-attempted statements re-stamp\n// on the adopted lane clocks.\nconst rebaseRecord = (s: Session, adopt: () => void) => {\n const held = [...s.pending];\n const survivors = held.filter((p) => !p.attempted && !p.applied);\n settleLost(\n s,\n held.filter((p) => p.attempted || p.applied),\n );\n s.pending = [];\n s.durableSeq = {};\n // Failed entries are user-owned history: they ride through every record replacement.\n const previous = s.record.lanes;\n adopt();\n let lanes = s.record.lanes;\n for (const [protocol, lane] of Object.entries(previous)) {\n const failed = lane.failed;\n if (failed === undefined || laneOf(s.record, protocol).failed === failed)\n continue;\n const current = laneOf(s.record, protocol);\n lanes = {\n ...lanes,\n [protocol]: {\n ...current,\n failed: boundFailed([...(current.failed ?? []), ...failed]),\n },\n };\n }\n if (lanes !== s.record.lanes) setRecord(s, { ...s.record, lanes });\n requeue(s, survivors);\n publish(s);\n wake(s);\n void pump(s);\n};\n\nconst resetRecord = (s: Session, clientId: string) =>\n rebaseRecord(s, () => setRecord(s, { clientId, lanes: {} }));\n\n// Another sharer replaced the record's identity: their reset settles our\n// attempted history and our survivors re-stamp on the stored clocks.\nconst adoptReset = (s: Session, stored: StatewireClient.SessionRecord) => {\n rebaseRecord(s, () => {\n s.record = boundRecord(stored);\n });\n // The host attributes frames by lease, and the lease is bound to the id\n // this attach was opened with.\n if (s.attach === \"attached\") s.transport?.connection.reconnect();\n};\n\n// The record died with the attach: mint a fresh id for the next one.\nconst ephemeralDetach = (s: Session) => {\n s.ephemeral = false;\n s.sessionKnown = false;\n resetRecord(s, newClientId());\n};\n\n// An ephemeral lane dies with its attach: attempted statements can never be\n// answered, the rest re-stamp from 1 for the next attach.\nconst detachEphemeralLanes = (s: Session) => {\n const held = s.pending.filter((p) => isEphemeral(s, p.command.protocol));\n if (held.length === 0) return;\n s.pending = s.pending.filter((p) => !held.includes(p));\n settleLost(\n s,\n held.filter((p) => p.attempted),\n );\n requeue(\n s,\n held.filter((p) => !p.attempted),\n );\n publish(s);\n};\n\nconst rejectedFailure = (cmd: StatewireCmd): StatewireClient.SendFailure => {\n return {\n fate: \"rejected\",\n cause: \"server\",\n ...(cmd.code !== undefined && { code: cmd.code }),\n ...(cmd.message !== undefined && { message: cmd.message }),\n ...(cmd.payload !== undefined && { payload: cmd.payload }),\n };\n};\n\nconst outcomeOf = (\n cmd: StatewireCmd,\n):\n | { ok: true; payload: unknown }\n | { ok: false; failure: StatewireClient.SendFailure } => {\n switch (cmd.type) {\n case \"result\":\n return { ok: true, payload: reviveResponse(cmd).payload };\n case \"rejected\":\n return { ok: false, failure: rejectedFailure(reviveResponse(cmd)) };\n case \"failed\":\n return {\n ok: false,\n failure: {\n fate: \"failed\",\n cause: \"server\",\n ...(cmd.message !== undefined && { message: cmd.message }),\n },\n };\n case \"crashed\":\n return { ok: false, failure: { fate: \"crashed\", cause: \"server\" } };\n case \"expired\":\n return { ok: false, failure: { fate: \"expired\", cause: \"server\" } };\n default:\n return protocolError(`unknown cmd type: ${String(cmd.type)}`);\n }\n};\n\n// Only a result verdict carries applied effects; the rest drop the overlay unapplied.\nconst settleVerdict = (s: Session, entry: Pending, cmd: StatewireCmd) => {\n const outcome = outcomeOf(cmd);\n if (outcome.ok) cover(s, entry);\n else s.lifecycle?.onCovered?.(entry.inv);\n settleEntry(s, entry, outcome);\n};\n\nconst TERMINAL_CMD_TYPES: ReadonlySet<string> = new Set(TERMINAL);\n\nconst parkVerdict = (s: Session, cmd: StatewireCmd) => {\n if (!s.shared || !TERMINAL_CMD_TYPES.has(cmd.type!)) return;\n if (isEphemeral(s, cmd.protocol)) return;\n s.shared.parked.push({\n protocol: cmd.protocol,\n verdict: {\n seq: cmd.seq,\n type: cmd.type as StatewireClient.SessionVerdict[\"type\"],\n ...(cmd.code !== undefined && { code: cmd.code }),\n ...(cmd.message !== undefined && { message: cmd.message }),\n ...(cmd.payload !== undefined && { payload: cmd.payload }),\n ...(cmd.meta !== undefined && { meta: cmd.meta }),\n },\n });\n};\n\nconst handleCmd = (s: Session, cmd: StatewireCmd) => {\n if (cmd.dur === true && !isEphemeral(s, cmd.protocol)) {\n const watermark = Math.max(durableSeqOf(s, cmd.protocol), cmd.seq);\n s.durableSeq[cmd.protocol] = watermark;\n for (const entry of laneEntries(s, cmd.protocol)) {\n if (entry.seq <= watermark) entry.posted = true;\n }\n }\n if (cmd.type === undefined) return;\n const entry = s.pending.find(\n (p) => p.command.protocol === cmd.protocol && p.seq === cmd.seq,\n );\n if (cmd.type === \"applied\") {\n if (entry) cover(s, entry);\n return;\n }\n if (!entry) return;\n parkVerdict(s, cmd);\n settleVerdict(s, entry, cmd);\n};\n\nconst consumeVerdicts = (s: Session) => {\n let lanes = s.record.lanes;\n for (const [protocol, lane] of Object.entries(s.record.lanes)) {\n const verdicts = lane.verdicts ?? [];\n const consumed = new Set<number>();\n for (const verdict of verdicts) {\n const entry = laneEntries(s, protocol).find((p) => p.seq === verdict.seq);\n if (!entry) continue;\n consumed.add(verdict.seq);\n settleVerdict(s, entry, { ...verdict, protocol });\n }\n if (consumed.size === 0) continue;\n lanes = {\n ...lanes,\n [protocol]: {\n ...lane,\n commands: lane.commands.filter((c) => !consumed.has(c.seq)),\n verdicts: verdicts.filter((v) => !consumed.has(v.seq)),\n },\n };\n }\n if (lanes === s.record.lanes) return;\n setRecord(s, { ...s.record, lanes });\n publish(s);\n wake(s);\n};\n\nconst handleCmds = (s: Session, cmds: StatewireCmd[]) => {\n for (const cmd of cmds) handleCmd(s, cmd);\n syncBacklog(s);\n wake(s);\n};\n\nconst ingestOps = (s: Session, ops: unknown[]) => {\n const applied = applyDocumentOps(s.documents, ops, s.selection?.protocols);\n s.documents = applied;\n const next =\n s.selection === undefined\n ? applied.documents.get(0)?.value\n : s.options.applicationProtocols === \"*\"\n ? Object.fromEntries(\n [...applied.documents].map(([id, d]) => [\n `${d.protocol}:${d.key === null ? id : JSON.stringify(d.key)}`,\n d.value,\n ]),\n )\n : mainDocument(applied, s.options.protocol ?? DEFAULT_PROTOCOL)?.value;\n if (next !== s.canonical)\n s.changed.push(\n ...(applied.changedPaths.length ? applied.changedPaths : [[]]),\n );\n s.canonical = next;\n};\n\nconst cacheDocuments = (s: Session) => {\n if (s.documentStore && s.selection) {\n for (const document of s.documents.documents.values()) {\n if (!document.protocol || !document.key) continue;\n const key = resolveDocumentKey(\n document.key,\n s.options.keyPrefixes?.[document.protocol],\n );\n const version = s.selection.protocols.find(\n (p) => p.name === document.protocol,\n )?.version;\n if (key !== undefined && version !== undefined)\n s.documentStore.save(\n [s.documentStore.namespace ?? \"\", document.protocol, ...key],\n { version, value: document.value },\n );\n }\n }\n};\n\nconst publishIngested = (s: Session) => {\n publish(s);\n cacheDocuments(s);\n for (const listener of s.documentListeners) listener();\n wake(s);\n};\n\n// The refusal's watermark is exact: every held statement above it was never\n// admitted by the live record, and the first unposted seq being beyond\n// watermark+1 proves the record that admitted the missing prefix is gone —\n// its history settles lost and the lane clock restarts at the watermark.\nconst sessionLostInner = (s: Session, protocol: string, seqWm: number) => {\n const held = laneEntries(s, protocol);\n settleLost(s, held);\n s.durableSeq[protocol] = seqWm;\n const failed = laneOf(s.record, protocol).failed;\n setRecord(\n s,\n withLane(s.record, protocol, {\n nextSeq: seqWm + 1,\n commands: [],\n ...(failed !== undefined && { failed }),\n }),\n );\n if (\n held.length > 0 &&\n s.onSessionLost?.(held.map((p) => p.inv)) === \"requeue\"\n ) {\n for (const old of held) {\n enqueueInner(\n s,\n old.command,\n old.inv.params,\n () => {},\n () => {},\n );\n }\n }\n publish(s);\n wake(s);\n};\n\nconst selectionOf = (\n syn: StatewireSyn,\n): StatewireProtocol.Selection | undefined => {\n if (syn.version === undefined || syn.protocols === undefined)\n return undefined;\n return {\n version: syn.version,\n protocols: syn.protocols.map(({ name, version, record }) => {\n if (version === undefined)\n return protocolError(`hello lane ${name} has no version`);\n return { name, version, ...(record !== undefined && { record }) };\n }),\n };\n};\n\nconst handleHello = (\n s: Session,\n { ops, syn }: { ops: unknown[]; syn: StatewireSyn },\n) => {\n if (s.attach === \"attached\") {\n s.ephemeralSeqs = {};\n detachEphemeralLanes(s);\n }\n for (const [protocol, value] of s.contexts) {\n if (s.attachContexts.get(protocol) === value)\n s.dirtyContexts.delete(protocol);\n else s.dirtyContexts.add(protocol);\n }\n s.attachContexts.clear();\n s.selection = selectionOf(syn);\n s.documents = { mode: null, documents: new Map() };\n ingestOps(s, ops);\n s.attach = \"attached\";\n s.attachEpoch += 1;\n s.frameFailures = 0;\n s.resumeAt = 0;\n const lanes = syn.protocols ?? [];\n s.ephemeral =\n lanes.length > 0 && lanes.every((lane) => lane.record === \"ephemeral\");\n if (s.ephemeral) s.deactivated = true;\n const attached = s.attachEntries;\n s.attachEntries = new Set();\n const reconcile = () => {\n if (s.shared) adoptStored(s);\n // Resending unsettled statements is exactly-once-safe: absorbed replays\n // re-emit their stored verdicts (applied while still in flight).\n for (const lane of lanes) {\n if (lane.record === \"ephemeral\") {\n s.ephemeralSeqs[lane.name] = Math.max(\n Object.hasOwn(s.ephemeralSeqs, lane.name)\n ? s.ephemeralSeqs[lane.name]!\n : 0,\n ...laneEntries(s, lane.name).map((p) => p.seq),\n );\n } else s.durableSeq[lane.name] = lane.seq ?? 0;\n }\n for (const entry of s.pending) entry.posted = attached.has(entry);\n syncBacklogInner(s);\n s.sessionKnown = true;\n };\n if (!s.shared || s.deactivated) {\n reconcile();\n publishIngested(s);\n void pump(s);\n return;\n }\n transactBackground(s, reconcile, () => {\n publishIngested(s);\n void pump(s);\n });\n};\n\nconst handleOps = (\n s: Session,\n { ops, cmds }: { ops: unknown[]; cmds: StatewireCmd[] },\n) => {\n ingestOps(s, ops);\n for (const cmd of cmds) handleCmd(s, cmd);\n if (cmds.length > 0) syncBacklog(s);\n publishIngested(s);\n};\n\n// A retry-less {syn} refusal is the one session-loss verdict: a gap against\n// a durable lane's exact watermark settles that lane's history lost; a\n// pushback (retry present) or a gapless refusal only reconciles the resend queues.\nconst handleRefusal = (s: Session, syn: StatewireSyn) => {\n const lanes = (syn.protocols ?? []).filter(\n (lane): lane is { name: string; seq: number } => lane.seq !== undefined,\n );\n for (const { name, seq } of lanes) {\n const watermark = isEphemeral(s, name)\n ? seq\n : Math.max(seq, durableSeqOf(s, name));\n for (const entry of laneEntries(s, name))\n entry.posted = entry.seq <= watermark;\n }\n if (typeof syn.retry === \"number\") {\n s.resumeAt = Date.now() + retryHint(syn.retry);\n wake(s);\n void pump(s);\n return;\n }\n const gaps = lanes.filter(({ name, seq }) => {\n const first = laneEntries(s, name).find((p) => !p.posted);\n return (\n first !== undefined &&\n first.seq > Math.max(seq, durableSeqOf(s, name)) + 1\n );\n });\n for (const { name, seq } of gaps) {\n if (isEphemeral(s, name))\n protocolError(`gap on ephemeral lane ${name} after watermark ${seq}`);\n }\n if (gaps.length > 0) {\n transactBackground(\n s,\n () => {\n for (const { name, seq } of gaps) sessionLostInner(s, name, seq);\n },\n () => {\n wake(s);\n void pump(s);\n },\n );\n return;\n }\n wake(s);\n void pump(s);\n};\n\nconst handleDetach = (s: Session) => {\n if (s.attach === \"attached\") s.attach = \"detached\";\n s.ephemeralSeqs = {};\n if (s.ephemeral) ephemeralDetach(s);\n else detachEphemeralLanes(s);\n wake(s);\n};\n\nconst handleFinish = (s: Session, { reason }: { reason: string }) => {\n if (reason === \"reconnect\" || reason === \"error\") return;\n s.attach = \"finished\";\n settleAll(s, \"gone\");\n publish(s);\n wake(s);\n};\n\nconst isFinished = (s: Session) => s.attach === \"finished\";\n\ntype Lanes = {\n frame: StatewireFrame;\n entries: Pending[];\n};\n\n// A lane must be strictly consecutive within a frame: the first unposted run\n// per lane rides now, later runs ride follow-up frames. Ephemeral lanes ignore\n// the gate: they live on the attach and never wait for persistence.\nconst buildLanes = (\n s: Session,\n cmdGate: \"persisted\" | \"all\" | \"none\" = \"all\",\n): Lanes | null => {\n const entries: Pending[] = [];\n const last: Record<string, number> = {};\n const stopped = new Set<string>();\n for (const entry of s.pending) {\n if (entries.length >= MAX_COMMANDS_PER_FRAME) break;\n const protocol = entry.command.protocol;\n if (entry.posted || stopped.has(protocol)) continue;\n const gated =\n !isEphemeral(s, protocol) &&\n (cmdGate === \"none\" ||\n (cmdGate === \"persisted\" &&\n (s.persistedRecord?.clientId !== s.record.clientId ||\n entry.seq >= laneOf(s.persistedRecord, protocol).nextSeq)));\n if (\n gated ||\n (Object.hasOwn(last, protocol) && entry.seq !== last[protocol]! + 1)\n ) {\n stopped.add(protocol);\n continue;\n }\n last[protocol] = entry.seq;\n entries.push(entry);\n }\n const ctx = [...s.dirtyContexts].map((protocol) => s.contexts.get(protocol)!);\n if (entries.length === 0 && ctx.length === 0) return null;\n return {\n frame: {\n ...(ctx.length > 0 && { ctx }),\n ...(entries.length > 0 && {\n cmd: entries.map((p) => {\n const { produced: _produced, ...command } = p.command;\n return { ...command, seq: p.seq };\n }),\n }),\n },\n entries,\n };\n};\n\nconst takeAttachLanes = (s: Session): StatewireFrame | null => {\n s.attachEntries = new Set();\n const wanted = s.lanesOnAttach;\n s.lanesOnAttach = false;\n for (const protocol of s.contexts.keys()) s.dirtyContexts.add(protocol);\n s.attachContexts = new Map(s.contexts);\n const lanes = buildLanes(s, wanted && s.sessionKnown ? \"persisted\" : \"none\");\n if (!lanes) return null;\n s.attachEntries = new Set(lanes.entries);\n for (const entry of lanes.entries) entry.attempted = true;\n return lanes.frame;\n};\n\nconst persistBeforeSend = (s: Session): void | Promise<void> => {\n if (s.storageError !== undefined) throw s.storageError;\n if (!s.hydrated) return s.ready!.then(() => persistBeforeSend(s));\n const record = s.record;\n try {\n const pending = s.store.flush?.();\n if (pending)\n return pending.then(\n () => {\n s.persistedRecord = record;\n },\n (cause: unknown) => {\n throw wrapStorageError(cause);\n },\n );\n s.persistedRecord = record;\n } catch (cause) {\n throw wrapStorageError(cause);\n }\n};\n\nconst pump = async (s: Session) => {\n if (s.pumping) return;\n s.pumping = true;\n try {\n while (s.running && !isFinished(s)) {\n if (!s.hydrated) await s.ready;\n const transport = s.transport;\n if (buildLanes(s) === null) return;\n if (transport?.parked && s.pending.length === 0) return;\n if (s.attach !== \"attached\" || !transport) {\n if (\n (transport?.connection.status === \"standby\" &&\n transport.connection.reason === \"idle\") ||\n (transport?.parked && s.pending.length > 0)\n ) {\n transport.connection.reconnect();\n }\n await waitForWake(s);\n continue;\n }\n const resumeDelay = s.resumeAt - Date.now();\n if (resumeDelay > 0) {\n await sleepUntilWake(s, resumeDelay);\n continue;\n }\n const lanes = buildLanes(s);\n if (!lanes) continue;\n const epoch = s.attachEpoch;\n const persistence = persistBeforeSend(s);\n if (persistence) await persistence;\n if (!s.running || isFinished(s)) return;\n if (epoch !== s.attachEpoch || s.attach !== \"attached\") continue;\n for (const entry of lanes.entries) entry.attempted = true;\n let result;\n try {\n // Shared storage: the lock across the send keeps per-lane arrival\n // ordered across sharers during attach handover.\n const send = () => transport.send(lanes.frame);\n result = await (s.shared && !s.deactivated && lanes.entries.length > 0\n ? s.store.lock!(send)\n : send());\n } catch {\n if (!s.running || isFinished(s)) return;\n if (lanes.frame.ctx?.length) {\n s.lanesOnAttach = true;\n transport.connection.reconnect();\n await waitForWake(s);\n continue;\n }\n s.frameFailures += 1;\n await sleepUntilWake(s, backoff(s.frameFailures));\n continue;\n }\n if (!s.running) return;\n s.frameFailures = 0;\n if (\n epoch === s.attachEpoch &&\n (result.type === \"ok\" || result.type === \"refusal\")\n ) {\n for (const entry of lanes.frame.ctx ?? []) {\n if (s.contexts.get(entry.protocol) === entry)\n s.dirtyContexts.delete(entry.protocol);\n }\n }\n if (result.type === \"ok\") {\n if (epoch === s.attachEpoch) {\n for (const entry of lanes.entries) {\n if (s.pending.includes(entry)) {\n entry.posted = true;\n s.lifecycle?.onPosted?.(entry.inv);\n }\n }\n }\n } else if (result.type === \"refusal\") {\n if (epoch === s.attachEpoch) handleRefusal(s, result.syn);\n } else if (result.type === \"stale-lease\") {\n // A POST outlived its attach: reattach first, the hello arbitrates.\n if (epoch === s.attachEpoch) {\n transport.connection.reconnect();\n await waitForWake(s);\n }\n } else if (result.type === \"no-lease\") {\n // No out-of-band write channel: the frame rides a fresh attach.\n if (epoch === s.attachEpoch) {\n s.lanesOnAttach = true;\n transport.connection.reconnect();\n while (s.running && !isFinished(s) && epoch === s.attachEpoch) {\n await waitForWake(s);\n }\n }\n }\n }\n } catch (error) {\n storageFailed(s, error);\n } finally {\n s.pumping = false;\n }\n};\n\nconst start = (s: Session) => {\n s.running = true;\n if (!s.hydrated) {\n void s.ready!.then(\n () => {\n if (s.running) start(s);\n },\n () => {},\n );\n return;\n }\n if (s.shared) {\n s.shared.unsubscribe = s.store.subscribe!(() => {\n transactBackground(s, () => consumeVerdicts(s));\n });\n s.running = true;\n transactBackground(\n s,\n () => {\n if (s.store.load() === null) s.store.save(s.record);\n s.recordPersisted = true;\n adoptStored(s);\n consumeVerdicts(s);\n },\n () => void pump(s),\n );\n return;\n }\n if (!s.recordPersisted) {\n s.recordPersisted = true;\n s.store.save(s.record);\n }\n adoptStored(s);\n s.running = true;\n void pump(s);\n};\n\nconst stop = (s: Session) => {\n s.running = false;\n if (s.shared) {\n s.shared.unsubscribe?.();\n s.shared.unsubscribe = null;\n }\n wake(s);\n settleAll(s, \"unmount\");\n};\n\nconst setTransport = (s: Session, transport: RemoteLink) => {\n if (s.transport === transport) return;\n s.transport = transport;\n wake(s);\n};\n\nconst enqueueInner = (\n s: Session,\n command: WireCommand,\n params: readonly unknown[],\n resolve: (payload: unknown) => void,\n reject: (error: unknown) => void,\n) => {\n const protocol = command.protocol;\n const ephemeral = isEphemeral(s, protocol);\n const seq = ephemeral\n ? (Object.hasOwn(s.ephemeralSeqs, protocol)\n ? s.ephemeralSeqs[protocol]!\n : 0) + 1\n : Math.max(\n laneOf(s.record, protocol).nextSeq,\n durableSeqOf(s, protocol) + 1,\n );\n const entry: Pending = {\n seq,\n command,\n inv: {\n protocol,\n method: command.method,\n params,\n ts: Date.now(),\n seq,\n clientId: s.record.clientId,\n },\n attempted: false,\n posted: false,\n applied: false,\n resolve,\n reject,\n };\n s.pending.push(entry);\n if (ephemeral) s.ephemeralSeqs[protocol] = seq;\n else\n setRecord(\n s,\n withLane(s.record, protocol, {\n ...laneOf(s.record, protocol),\n nextSeq: seq + 1,\n commands: mergeBacklog(s, protocol),\n }),\n );\n s.lifecycle?.onStart(entry.inv);\n};\n\nconst enqueue = (\n s: Session,\n command: WireCommand,\n params: readonly unknown[],\n resolve: (payload: unknown) => void,\n reject: (error: unknown) => void,\n) => {\n if (!s.shared) {\n enqueueInner(s, command, params, resolve, reject);\n wake(s);\n void pump(s);\n return;\n }\n void transact(s, () => {\n // A send queued behind the lock before this tab unmounted still lands in\n // the shared journal: another sharer adopts and replays it.\n if (isFinished(s)) {\n reject(new StatewireSendError({ fate: \"aborted\", cause: \"stream-gone\" }));\n return;\n }\n enqueueInner(s, command, params, resolve, reject);\n }).then(() => {\n wake(s);\n void pump(s);\n }, reject);\n};\n\nconst offered = (s: Session, protocol: string) => {\n const offers = protocolOffers(s.options);\n return offers === \"*\" || offers.some((offer) => offer.name === protocol);\n};\n\n// A stored command may have reached a server: attempted settles it lost,\n// never aborted, when a channel death ends the session.\nconst adoptStored = (s: Session) => {\n let adopted = false;\n for (const [protocol, lane] of Object.entries(s.record.lanes)) {\n if (!offered(s, protocol)) continue;\n const known = new Set(laneEntries(s, protocol).map((p) => p.seq));\n for (const { seq, ...command } of lane.commands) {\n if (known.has(seq)) continue;\n const params =\n command.meta === undefined\n ? command.params\n : (reviveValue(\n structuredClone(command.params),\n command.meta,\n ) as unknown[]);\n const entry: Pending = {\n seq,\n command: { protocol, ...command },\n inv: {\n protocol,\n method: command.method,\n params,\n ts: Date.now(),\n seq,\n clientId: s.record.clientId,\n },\n attempted: true,\n posted: false,\n applied: false,\n resolve: () => {},\n reject: () => {},\n };\n s.pending.push(entry);\n s.lifecycle?.onStart(entry.inv);\n adopted = true;\n }\n }\n if (adopted) s.pending.sort((a, b) => a.seq - b.seq);\n};\n\nconst sendCommand = (\n s: Session,\n method: string,\n params: readonly unknown[],\n protocol = s.options.protocol ?? DEFAULT_PROTOCOL,\n): Promise<unknown> => {\n const negotiated = s.selection\n ? s.selection.protocols.some((p) => p.name === protocol)\n : offered(s, protocol);\n if (!negotiated)\n throw new Error(`statewire: protocol \"${protocol}\" is not negotiated`);\n if (!s.hydrated) {\n const result = s.ready!.then(() =>\n sendCommand(s, method, params, protocol),\n );\n result.catch(() => {});\n return result;\n }\n if (s.storageError !== undefined) {\n const result = Promise.reject(s.storageError);\n result.catch(() => {});\n return result;\n }\n if (!s.running) {\n return rejectedSend({ fate: \"aborted\", cause: \"unmount\" });\n }\n if (isFinished(s)) {\n return rejectedSend({ fate: \"aborted\", cause: \"stream-gone\" });\n }\n const result = new Promise<unknown>((resolve, reject) => {\n const { params: encoded, meta } = encodeParams(params);\n enqueue(\n s,\n {\n protocol,\n produced: {\n wire: s.options.wireVersion ?? { version: WIRE_VERSION },\n protocols:\n protocolOffers(s.options) === \"*\" && s.selection\n ? s.selection.protocols\n : protocolOffers(s.options),\n },\n method,\n params: encoded,\n ...(meta !== undefined && { meta }),\n },\n params,\n resolve,\n reject,\n );\n });\n result.catch(() => {});\n return result;\n};\n\nconst findFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): StatewireClient.FailedCommand | undefined =>\n (laneOf(s.record, entry.protocol).failed ?? []).find(\n (f) =>\n f.seq === entry.seq && f.ts === entry.ts && f.command === entry.command,\n );\n\nconst unknownFailed = (entry: StatewireClient.FailedCommand) =>\n new Error(`statewire: unknown failed command \"${entry.command}\"`);\n\nconst takeFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): StatewireClient.FailedCommand => {\n const lane = laneOf(s.record, entry.protocol);\n const found = findFailed(s, entry);\n if (found === undefined) throw unknownFailed(entry);\n setRecord(\n s,\n withLane(s.record, entry.protocol, {\n ...lane,\n failed: (lane.failed ?? []).filter((f) => f !== found),\n }),\n );\n s.notify();\n return found;\n};\n\nexport const discardFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): void => {\n if (!s.shared) {\n takeFailed(s, entry);\n return;\n }\n if (findFailed(s, entry) === undefined) throw unknownFailed(entry);\n transactBackground(s, () => {\n if (findFailed(s, entry) !== undefined) takeFailed(s, entry);\n });\n};\n\nexport const retryFailed = (\n s: Session,\n entry: StatewireClient.FailedCommand,\n): Promise<unknown> => {\n if (!s.running) {\n return rejectedSend({ fate: \"aborted\", cause: \"unmount\" });\n }\n if (isFinished(s)) {\n return rejectedSend({ fate: \"aborted\", cause: \"stream-gone\" });\n }\n const found = findFailed(s, entry);\n if (found === undefined) throw unknownFailed(entry);\n const params =\n found.meta === undefined\n ? found.params\n : (reviveValue(structuredClone(found.params), found.meta) as unknown[]);\n const result = new Promise<unknown>((resolve, reject) => {\n const retry = () => {\n if (!s.running) {\n reject(new StatewireSendError({ fate: \"aborted\", cause: \"unmount\" }));\n return;\n }\n if (isFinished(s)) {\n reject(\n new StatewireSendError({ fate: \"aborted\", cause: \"stream-gone\" }),\n );\n return;\n }\n const current = findFailed(s, entry);\n if (current === undefined) {\n reject(unknownFailed(entry));\n return;\n }\n takeFailed(s, current);\n enqueueInner(\n s,\n {\n protocol: current.protocol,\n ...(current.produced !== undefined && { produced: current.produced }),\n method: current.command,\n params: [...current.params],\n ...(current.meta !== undefined && { meta: current.meta }),\n },\n params,\n resolve,\n reject,\n );\n };\n if (!s.shared) {\n retry();\n wake(s);\n void pump(s);\n return;\n }\n void transact(s, retry).then(() => {\n wake(s);\n void pump(s);\n }, reject);\n });\n result.catch(() => {});\n return result;\n};\n\nexport const documentSource = (s: Session): StatewireDocuments.Source => ({\n get: (protocol, key, prefix = s.options.keyPrefixes?.[protocol]) => {\n const mounted = findDocument(s.documents, protocol, key, prefix);\n if (mounted !== undefined) return mounted.value;\n if (!s.documentStore || key === undefined) return undefined;\n const absolute = resolveDocumentKey(key, prefix);\n if (absolute === undefined) return undefined;\n const cached = s.documentStore.load([\n s.documentStore.namespace ?? \"\",\n protocol,\n ...absolute,\n ]);\n if (cached === undefined) return undefined;\n const offers = protocolOffers(s.options);\n const offer =\n offers === \"*\"\n ? s.selection?.protocols.find((p) => p.name === protocol)\n : offers.find((p) => p.name === protocol);\n return offer !== undefined && inRange(cached.version, offer)\n ? cached.value\n : undefined;\n },\n list: () => s.documents.documents,\n subscribe: (listener) => {\n s.documentListeners.add(listener);\n return () => {\n s.documentListeners.delete(listener);\n };\n },\n});\n\nexport const invokeProtocol = (\n s: Session,\n protocol: string,\n method: string,\n params: readonly unknown[],\n) => sendCommand(s, method, params, protocol);\n\nconst storedCommandCompatible = (\n protocol: string,\n command: StatewireClient.SessionCommand,\n current: NonNullable<StatewireClient.SessionCommand[\"produced\"]>,\n) => {\n if (\n !command.produced ||\n !inRange(command.produced.wire.version, current.wire)\n )\n return false;\n const previous = command.produced.protocols;\n if (current.protocols === \"*\") return true;\n if (previous === \"*\") return false;\n const produced = previous.find((p) => p.name === protocol);\n const offer = current.protocols.find((p) => p.name === protocol);\n return (\n produced !== undefined &&\n offer !== undefined &&\n inRange(produced.version, offer)\n );\n};\n\nconst validateLanes = (record: StatewireClient.SessionRecord) => {\n if (\n typeof record.lanes !== \"object\" ||\n record.lanes === null ||\n Object.values(record.lanes).some((lane) => !Array.isArray(lane.commands))\n )\n throw new Error(\n \"statewire: session storage loaded a record without command lanes\",\n );\n};\n\nconst loadSessionRecord = (\n store: StatewireClient.SessionStorage,\n options: StatewireSessionOptions,\n) => {\n let stored = store.load();\n if (stored !== null) validateLanes(stored);\n const current = {\n wire: options.wireVersion ?? { version: WIRE_VERSION },\n protocols: protocolOffers(options),\n };\n const compatible = (record: StatewireClient.SessionRecord) =>\n Object.entries(record.lanes).every(([protocol, lane]) =>\n lane.commands.every((command) =>\n storedCommandCompatible(protocol, command, current),\n ),\n );\n if (stored !== null && !compatible(stored)) {\n if (!store.migrate)\n throw new Error(\"statewire: stored commands require a storage migration\");\n stored = store.migrate(stored, current);\n if (stored !== null) {\n validateLanes(stored);\n if (!compatible(stored))\n throw new Error(\"statewire: migrated commands are incompatible\");\n store.save(stored);\n }\n }\n const record =\n stored === null\n ? { clientId: newClientId(), lanes: {} }\n : boundRecord(stored);\n if (record !== stored) store.save(record);\n return record;\n};\n\nexport const setContext = (\n s: Session,\n protocol: string,\n value: Statewire.Context,\n): void => {\n if (\n s.selection\n ? !s.selection.protocols.some((p) => p.name === protocol)\n : !offered(s, protocol)\n )\n throw new Error(`statewire: protocol \"${protocol}\" is not negotiated`);\n s.contexts.set(protocol, encodeContext(protocol, value));\n s.dirtyContexts.add(protocol);\n wake(s);\n void pump(s);\n};\n\nexport const useStatewireSession = (\n options: StatewireSessionOptions,\n): Session => {\n const [defaultStore] = useState(createMemorySessionStore);\n const mounted = useContext(SessionStorageContext);\n const documentStore = useContext(DocumentStorageContext);\n if (options.sessionStore !== undefined && mounted !== undefined) {\n throw new Error(\n \"statewire: session storage is set twice — drop the transport's sessionStore or the client's storage.session\",\n );\n }\n const store = options.sessionStore ?? mounted ?? defaultStore;\n if ((store.lock === undefined) !== (store.subscribe === undefined)) {\n throw new Error(\n \"statewire: session storage must provide lock and subscribe together\",\n );\n }\n const [s] = useState((): Session => {\n const record =\n store.ready === undefined\n ? loadSessionRecord(store, options)\n : { clientId: newClientId(), lanes: {} };\n const session: Session = {\n options,\n configuredContext: options.context,\n contexts: new Map(\n Object.entries(options.context ?? {}).map(([protocol, value]) => [\n protocol,\n encodeContext(protocol, value),\n ]),\n ),\n dirtyContexts: new Set(Object.keys(options.context ?? {})),\n attachContexts: new Map(),\n selection: undefined,\n record,\n ctx: {\n beforeAttach: () => persistBeforeSend(session),\n get clientId() {\n return session.record.clientId;\n },\n takeAttachLanes: () => takeAttachLanes(session),\n onHello: (args) => handleHello(session, args),\n onOps: (args) => handleOps(session, args),\n onCmds: (cmds) => handleCmds(session, cmds),\n onRefusal: (syn) => handleRefusal(session, syn),\n onIdle: (level) => setIdle(session, level),\n onDetach: () => handleDetach(session),\n onFinish: (args) => handleFinish(session, args),\n },\n recordPersisted: store.ready === undefined,\n hydrated: store.ready === undefined,\n ready: undefined,\n storageError: undefined,\n persistedRecord: store.ready === undefined ? record : null,\n store,\n documentStore,\n shared:\n store.lock !== undefined\n ? {\n txq: Promise.resolve(),\n syncQueued: false,\n parked: [],\n unsubscribe: null,\n }\n : false,\n ephemeral: false,\n deactivated: false,\n sessionKnown: false,\n durableSeq: {},\n ephemeralSeqs: {},\n resumeAt: 0,\n idle: false,\n onSessionLost: undefined,\n onDone: undefined,\n lanesOnAttach: false,\n attachEntries: new Set(),\n frameFailures: 0,\n pending: [],\n failedList: [],\n failedParts: [],\n canonical: undefined,\n documentListeners: new Set(),\n documents: { mode: null, documents: new Map() },\n lastPublished: undefined,\n changed: [],\n source: {\n snapshot: () => session.canonical,\n takeChanged: () => {\n const changed = session.changed;\n session.changed = [];\n return changed;\n },\n setOnChange: (listener) => {\n session.notify = listener ?? (() => {});\n },\n },\n attach: \"detached\",\n attachEpoch: 0,\n running: false,\n pumping: false,\n transport: null,\n waiters: [],\n lifecycle: null,\n notify: () => {},\n commands: createMethodProxy((method, params) =>\n sendCommand(session, method, params),\n ),\n };\n if (store.ready !== undefined) {\n session.ready = store.ready.then(() => {\n session.record = loadSessionRecord(store, session.options);\n session.recordPersisted = true;\n session.hydrated = true;\n if (session.running) session.notify();\n });\n session.ready = session.ready.catch((cause: unknown) => {\n const error = wrapStorageError(cause);\n session.storageError = error;\n session.transport?.storageFailed(error);\n throw error;\n });\n session.ready.catch(() => {});\n }\n bindCommandsHost(session.commands, {\n setListener: (listener) => {\n session.lifecycle = listener;\n },\n });\n return session;\n });\n if ((store.lock !== undefined) !== (s.shared !== false)) {\n throw new Error(\n \"statewire: session storage changed sharedness across renders — lock/subscribe must be present from the first render or never\",\n );\n }\n useEffect(() => {\n if (s.configuredContext === options.context) return;\n s.configuredContext = options.context;\n for (const [protocol, value] of Object.entries(options.context ?? {}))\n setContext(s, protocol, value);\n }, [s, options.context]);\n s.options = options;\n s.store = store;\n s.documentStore = documentStore;\n s.onSessionLost = options.onSessionLost;\n s.onDone = options.onDone;\n const keyPrefixes = JSON.stringify(options.keyPrefixes);\n useEffect(() => {\n cacheDocuments(s);\n }, [s, documentStore, keyPrefixes]);\n useEffect(\n () =>\n documentStore?.subscribe?.(() => {\n for (const listener of s.documentListeners) listener();\n }),\n [s, documentStore],\n );\n useEffect(() => {\n start(s);\n return () => stop(s);\n }, [s]);\n return s;\n};\n\nexport { setTransport };\n"],"mappings":";;;;;;;;;;;;;;;;AAgEA,MAAM2D,iBAAiBC,YAA2B;CAChD,MAAM,IAAIC,MAAM,8BAA8BD,SAAS;AACzD;AAEA,MAAME,gBACJC,YACqB;CACrB,MAAMG,SAASD,QAAQR,OAAgB,IAAIrB,mBAAmB2B,OAAO,CAAC;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EAC9B,KAAK,MAAM,CAAC9B,YAAU4P,YAAUnJ,OAAO0F,QAAQpJ,QAAQjB,WAAW,CAAC,CAAC,GAClE0T,WAAWzO,GAAG/G,YAAU4P,OAAK;CACjC,GAAG,CAAC7I,GAAGhE,QAAQjB,OAAO,CAAC;CACvBiF,EAAEhE,UAAUA;CACZgE,EAAE9C,QAAQA;CACV8C,EAAE7C,gBAAgBA;CAClB6C,EAAE3E,gBAAgBW,QAAQX;CAC1B2E,EAAEzE,SAASS,QAAQT;CACnB,MAAMiO,cAAcL,KAAKC,UAAUpN,QAAQwN,WAAW;CACtDnS,gBAAgB;EACdiS,eAAetJ,CAAC;CAClB,GAAG;EAACA;EAAG7C;EAAeqM;CAAW,CAAC;CAClCnS,gBAEI8F,eAAeiP,kBAAkB;EAC/B,KAAK,MAAMxC,cAAY5J,EAAE1B,mBAAmBsL,WAAS;CACvD,CAAC,GACH,CAAC5J,GAAG7C,aAAa,CACnB;CACA9F,gBAAgB;EACd8U,MAAMnM,CAAC;EACP,aAAaqM,KAAKrM,CAAC;CACrB,GAAG,CAACA,CAAC,CAAC;CACN,OAAOA;AACT"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { StatewireDocuments } from "../wire/documents.js";
|
|
2
2
|
import { StatewireProtocol } from "../wire/protocol.js";
|
|
3
3
|
import { StatewireClient } from "../statewire.js";
|
|
4
|
+
import { Statewire } from "../types.js";
|
|
4
5
|
//#region src/client/sessionStore.d.ts
|
|
5
6
|
/** The session storage `useStatewire` mounts, read by the transport's session. */
|
|
6
7
|
declare const SessionStorageContext: import("react").Context<StatewireClient.SessionStorage | undefined>;
|
|
@@ -9,6 +10,7 @@ declare const ProtocolContext: import("react").Context<StatewireProtocol.Options
|
|
|
9
10
|
/** Link options `useStatewire` hands down to whichever transport it mounts. */
|
|
10
11
|
declare const LinkContext: import("react").Context<{
|
|
11
12
|
isNew?: boolean | undefined;
|
|
13
|
+
context?: Readonly<Record<string, Statewire.Context>> | undefined;
|
|
12
14
|
}>;
|
|
13
15
|
declare const DocumentStorageContext: import("react").Context<StatewireDocuments.Storage | undefined>;
|
|
14
16
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionStore.d.ts","names":[],"sources":["../../src/client/sessionStore.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"sessionStore.d.ts","names":[],"sources":["../../src/client/sessionStore.ts"],"mappings":";;;;;;cAOa,uCAAqB,QAAA,gBAAA;cAIrB,gCAA+B,gBAAgB;cAU/C,iCAAe,QAAA,kBAAA;;cAGf,6BAAW;EACd;EACE,UAAA,SAAS,eAAe,UAAU;;cAGjC,wCAAsB,QAAA,mBAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sessionStore.js","names":["StatewireDocuments","createContext","StatewireProtocol","StatewireClient","SessionStorageContext","SessionStorage","undefined","createMemorySessionStore","record","SessionRecord","load","save","next","ProtocolContext","Options","LinkContext","isNew","DocumentStorageContext","Storage"],"sources":["../../src/client/sessionStore.ts"],"sourcesContent":["import type { StatewireDocuments } from \"../wire/documents\";\nimport { createContext } from \"react\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport type { StatewireClient } from \"../statewire\";\n\n/** The session storage `useStatewire` mounts, read by the transport's session. */\nexport const SessionStorageContext = createContext<\n StatewireClient.SessionStorage | undefined\n>(undefined);\n\nexport const createMemorySessionStore = (): StatewireClient.SessionStorage => {\n let record: StatewireClient.SessionRecord | null = null;\n return {\n load: () => record,\n save: (next) => {\n record = next;\n },\n };\n};\n\nexport const ProtocolContext = createContext<StatewireProtocol.Options>({});\n\n/** Link options `useStatewire` hands down to whichever transport it mounts. */\nexport const LinkContext = createContext<{
|
|
1
|
+
{"version":3,"file":"sessionStore.js","names":["StatewireDocuments","createContext","StatewireProtocol","Statewire","StatewireClient","SessionStorageContext","SessionStorage","undefined","createMemorySessionStore","record","SessionRecord","load","save","next","ProtocolContext","Options","LinkContext","isNew","context","Readonly","Record","Context","DocumentStorageContext","Storage"],"sources":["../../src/client/sessionStore.ts"],"sourcesContent":["import type { StatewireDocuments } from \"../wire/documents\";\nimport { createContext } from \"react\";\nimport type { StatewireProtocol } from \"../wire/protocol\";\nimport type { Statewire } from \"../types\";\nimport type { StatewireClient } from \"../statewire\";\n\n/** The session storage `useStatewire` mounts, read by the transport's session. */\nexport const SessionStorageContext = createContext<\n StatewireClient.SessionStorage | undefined\n>(undefined);\n\nexport const createMemorySessionStore = (): StatewireClient.SessionStorage => {\n let record: StatewireClient.SessionRecord | null = null;\n return {\n load: () => record,\n save: (next) => {\n record = next;\n },\n };\n};\n\nexport const ProtocolContext = createContext<StatewireProtocol.Options>({});\n\n/** Link options `useStatewire` hands down to whichever transport it mounts. */\nexport const LinkContext = createContext<{\n isNew?: boolean | undefined;\n context?: Readonly<Record<string, Statewire.Context>> | undefined;\n}>({});\n\nexport const DocumentStorageContext = createContext<\n StatewireDocuments.Storage | undefined\n>(undefined);\n"],"mappings":";;;AAOA,MAAaK,wBAAwBJ,cAEnCM,KAAAA,CAAS;AAEX,MAAaC,iCAAiE;CAC5E,IAAIC,SAA+C;CACnD,OAAO;EACLE,YAAYF;EACZG,OAAOC,SAAS;GACdJ,SAASI;EACX;CACF;AACF;AAEA,MAAaC,kBAAkBb,cAAyC,CAAC,CAAC;;AAG1E,MAAae,cAAcf,cAGxB,CAAC,CAAC;AAEL,MAAaqB,yBAAyBrB,cAEpCM,KAAAA,CAAS"}
|
package/dist/host/host.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ type CommandsSubmission = {
|
|
|
33
33
|
params: readonly unknown[];
|
|
34
34
|
clientId?: string;
|
|
35
35
|
caller?: StatewireHost.Caller;
|
|
36
|
+
context?: Statewire.Context;
|
|
36
37
|
attach?: StatewireHost.Attach;
|
|
37
38
|
onApplied?: () => void;
|
|
38
39
|
onSettle?: (outcome: CommandsOutcome) => void;
|
|
@@ -46,7 +47,7 @@ type CommandsHost = {
|
|
|
46
47
|
};
|
|
47
48
|
declare const getCommandsHost: (commands: object) => CommandsHost | undefined;
|
|
48
49
|
declare const bindCommandsHost: (commands: object, host: CommandsHost) => void;
|
|
49
|
-
declare const useStatewireCommands: <THandlers extends Statewire.Commands>(commands: (THandlers & ThisType<StatewireHost.Ctx>) | undefined | null | false) => Statewire.CommandsProxy<StatewireHost.HandledCommands<THandlers>>;
|
|
50
|
+
declare const useStatewireCommands: <THandlers extends Statewire.Commands>(commands: (THandlers & ThisType<StatewireHost.Ctx>) | undefined | null | false, options?: StatewireHost.CommandsOptions) => Statewire.CommandsProxy<StatewireHost.HandledCommands<THandlers>>;
|
|
50
51
|
//#endregion
|
|
51
52
|
export { CommandsHost, CommandsInvocation, CommandsListener, CommandsOutcome, CommandsSubmission, bindCommandsHost, documentIdentity, getCommandsHost, getStateHost, useStatewireCommands, useStatewireState };
|
|
52
53
|
//# sourceMappingURL=host.d.ts.map
|
package/dist/host/host.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../../src/host/host.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../../src/host/host.ts"],"mappings":";;;cAmBa,mBAAoB,kBAAkB;;cAItC,eACX,kBACC,cAAc;cAeJ,oBAAqB,QAChC,YAAY,qBACD,QAAQ,cAAc,SAAS;KAqGhC;WACD;WACA;WACA;WACA;WACA;WACA;;KAGC;EACN;EAAkB;;EAClB;EAAkB;;KAEZ;EACV,UAAU,KAAK;EACf,YAAY,KAAK;EACjB,YAAY,KAAK;;EAEjB,aAAa,KAAK;EAClB,WAAW,KAAK,oBAAoB,SAAS;;KAGnC;EACV;EACA;EACA;EACA,SAAS,cAAc;EACvB,UAAU,UAAU;EACpB,SAAS,cAAc;EACvB;EACA,YAAY,SAAS;;KAGX;EACV,cAAc,UAAU;EACxB,UAAU,MAAM,uBAAuB;;EAEvC;EACA;;cAKW,kBAAmB,qBAAmB;cAGtC,mBAAoB,kBAAkB,MAAM;cA0O5C,uBAAwB,kBAAkB,UAAU,UAC/D,WACK,YAAY,SAAS,cAAc,kCAIxC,UAAU,cAAc,oBACvB,UAAU,cAAc,cAAc,gBAAgB"}
|
package/dist/host/host.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { captureContext } from "../wire/context.js";
|
|
1
2
|
import { applyOps, sanitizeValue } from "../wire/ops.js";
|
|
2
3
|
import { StatewireReject } from "./engine.js";
|
|
3
4
|
import { createStateDraft } from "./draft.js";
|
|
@@ -106,17 +107,20 @@ const LOCAL_CALLER = Object.freeze({
|
|
|
106
107
|
auth: void 0,
|
|
107
108
|
isConnected: true
|
|
108
109
|
});
|
|
109
|
-
const toSendError = (error) =>
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
110
|
+
const toSendError = (error) => {
|
|
111
|
+
if (!(error instanceof StatewireSendError) && !(error instanceof StatewireReject)) console.error("statewire command failed", error);
|
|
112
|
+
return error instanceof StatewireSendError ? error : error instanceof StatewireReject ? new StatewireSendError({
|
|
113
|
+
fate: "rejected",
|
|
114
|
+
cause: "server",
|
|
115
|
+
message: error.message,
|
|
116
|
+
...error.code !== void 0 && { code: error.code },
|
|
117
|
+
...error.payload !== void 0 && { payload: error.payload }
|
|
118
|
+
}) : new StatewireSendError({
|
|
119
|
+
fate: "failed",
|
|
120
|
+
cause: "server",
|
|
121
|
+
message: "the command failed"
|
|
122
|
+
});
|
|
123
|
+
};
|
|
120
124
|
const applyInvocation = (cell, inv) => {
|
|
121
125
|
if (inv.applied) return;
|
|
122
126
|
inv.applied = true;
|
|
@@ -205,6 +209,7 @@ const dispatch = (cell, call) => {
|
|
|
205
209
|
const attach = call.origin?.attach;
|
|
206
210
|
const ctx = {
|
|
207
211
|
caller: call.origin?.caller ?? LOCAL_CALLER,
|
|
212
|
+
context: call.context ?? call.origin?.context ?? Object.freeze({}),
|
|
208
213
|
get attach() {
|
|
209
214
|
if (attach === void 0) throw new Error("statewire: in-process dispatch has no attach");
|
|
210
215
|
return attach;
|
|
@@ -258,9 +263,10 @@ const watchStall = (cell) => {
|
|
|
258
263
|
if (cell.handlers === null && cell.queue.length > 0 && !cell.unmounted) console.warn(`statewire: ${cell.queue.length} buffered command(s) waiting over ${STALL_WARN_MS}ms — did the host forget to arm useStatewireCommands?`);
|
|
259
264
|
}, STALL_WARN_MS);
|
|
260
265
|
};
|
|
261
|
-
const useStatewireCommands = (commands) => {
|
|
266
|
+
const useStatewireCommands = (commands, options) => {
|
|
262
267
|
const [built] = useState(() => {
|
|
263
268
|
const cell = {
|
|
269
|
+
context: void 0,
|
|
264
270
|
handlers: null,
|
|
265
271
|
queue: [],
|
|
266
272
|
active: /* @__PURE__ */ new Map(),
|
|
@@ -276,6 +282,7 @@ const useStatewireCommands = (commands) => {
|
|
|
276
282
|
return;
|
|
277
283
|
}
|
|
278
284
|
cell.queue.push({
|
|
285
|
+
context: captureContext(cell.context?.() ?? {}),
|
|
279
286
|
method,
|
|
280
287
|
params,
|
|
281
288
|
ts: Date.now(),
|
|
@@ -315,6 +322,7 @@ const useStatewireCommands = (commands) => {
|
|
|
315
322
|
proxy
|
|
316
323
|
};
|
|
317
324
|
});
|
|
325
|
+
built.cell.context = options?.context;
|
|
318
326
|
useEffect(() => {
|
|
319
327
|
const { cell: cell_0 } = built;
|
|
320
328
|
cell_0.unmounted = false;
|