cross-tab-worker-databus 0.20.87 → 0.20.89

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.
@@ -358,6 +358,8 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
358
358
  * status handlers. On reconnect, re-subscribe any topics assigned to us.
359
359
  */
360
360
  private updateStatus;
361
+ private recordError;
362
+ private notifyError;
361
363
  private reportError;
362
364
  /** Report a persistence failure to the trace and the unified failure ledger,
363
365
  * unless it is a {@link PersistenceRetryCancelledError} cancellation from a
@@ -378,6 +380,10 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
378
380
  * error-handler failures are logged to the console to avoid infinite
379
381
  * recursion through reportError itself. */
380
382
  private invokeHandlers;
383
+ /** Resume the resources paused by a pagehide suspension. Both the native
384
+ * pageshow path and explicit start() must run this so an explicit resume
385
+ * cannot leave trace metrics and periodic cleanup timers permanently off. */
386
+ private resumeSuspendedResources;
381
387
  /**
382
388
  * Suspend the transport when the tab goes hidden. Stops the transport and
383
389
  * clears subscription state so it will be re-established on resume.
@@ -1 +1 @@
1
- {"version":3,"file":"data-bus.d.ts","sourceRoot":"","sources":["../../src/core/data-bus.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AAE7E,OAAO,KAAK,EACV,mBAAmB,EAEnB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACb,MAAM,SAAS,CAAC;AAEjB,OAAO,KAAK,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAC3E,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAGrE,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAE9E,OAAO,EAGL,cAAc,EACd,YAAY,EAEZ,cAAc,EAUf,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AChG,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAkBnC;;;;OAIG;IACH,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAQpC;;;;;OAKG;IACH,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAgBrC,iEAAiE;IACjE,mBAAmB,IAAI,IAAI;IAI3B,qBAAqB,IAAI,IAAI;IAI7B;;iFAE6E;IAC7E,OAAO,KAAK,aAAa,GAExB;IAED,uEAAuE;IACvE,KAAK,IAAI,IAAI;IAKb,OAAO,CAAC,QAAQ;IA4BhB,OAAO,CAAC,YAAY;IAYpB,OAAO,CAAC,IAAI;IAiBZ,OAAO,CAAC,QAAQ;CAWjB"}
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  selectRebalanceTarget,
21
21
  selectWorkerBackend,
22
22
  topicMatchesPattern
23
- } from "./chunk-ZNHJ5OMY.js";
23
+ } from "./chunk-77BQELW4.js";
24
24
  import {
25
25
  DEFAULT_STORAGE_PREFIX,
26
26
  PRUNE_STRATEGY,
@@ -539,10 +539,16 @@ var WebSocketTransport = class {
539
539
  * server cannot crash the message path. */
540
540
  async handleMessage(raw) {
541
541
  if (typeof Blob !== "undefined" && raw instanceof Blob) {
542
+ const socket = this.socket;
543
+ const handlers = this.handlers;
542
544
  try {
543
- await this.handleMessage(await raw.arrayBuffer());
545
+ const buffer = await raw.arrayBuffer();
546
+ if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;
547
+ await this.handleMessage(buffer);
544
548
  } catch (error) {
545
- this.handlers?.onError(error);
549
+ if (this.socket === socket && this.handlers === handlers && this.socketActive) {
550
+ this.handlers?.onError(error);
551
+ }
546
552
  }
547
553
  return;
548
554
  }
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/core/replay-persistence.ts", "../src/websocket.ts"],
4
- "sourcesContent": ["import type { DataBusMessage } from './types';\nimport { pruneReplayHistory } from './replay-pruning';\nimport { DEFAULT_STORAGE_PREFIX, PRUNE_STRATEGY } from '../utils/constants';\nimport { assertPositiveFiniteNumber, assertPositiveSafeInteger, assertPruneStrategy } from '../utils/validation';\n\n/** Optional persistence backend for replay history. */\nexport interface DataBusReplayPersistence<TData = unknown> {\n load(): Promise<ReadonlyArray<DataBusMessage<TData>>>;\n append(message: DataBusMessage<TData>): Promise<void>;\n /** Optional bulk append used to amortize IndexedDB transaction overhead. */\n appendBatch?(messages: ReadonlyArray<DataBusMessage<TData>>): Promise<void>;\n /** Remove all persisted replay history. */\n clear?(): Promise<void>;\n /** Remove persisted replay history for one exact topic. */\n clearTopic?(topic: string): Promise<void>;\n /** Remove persisted messages older than the given epoch-millisecond cutoff. */\n clearBefore?(timestamp: number): Promise<void>;\n}\n\nexport interface IndexedDbReplayPersistenceOptions {\n dbName?: string;\n maxPerTopic: number;\n pruneStrategy?: (typeof PRUNE_STRATEGY)[keyof typeof PRUNE_STRATEGY];\n retentionMs?: number;\n}\n\n/** Create a browser IndexedDB-backed replay store. */\nexport function createIndexedDbReplayPersistence<TData = unknown>(\n options: IndexedDbReplayPersistenceOptions\n): DataBusReplayPersistence<TData> {\n const indexedDb = globalThis.indexedDB;\n if (!indexedDb) throw new Error('IndexedDB is unavailable in this environment.');\n const dbName = options.dbName ?? DEFAULT_STORAGE_PREFIX;\n const storeName = 'replay';\n const maxPerTopic = options.maxPerTopic;\n const pruneStrategy = options.pruneStrategy ?? PRUNE_STRATEGY.COUNT;\n const retentionMs = options.retentionMs;\n assertPruneStrategy(pruneStrategy);\n if (retentionMs !== undefined) assertPositiveFiniteNumber(retentionMs, 'retentionMs');\n assertPositiveSafeInteger(maxPerTopic, 'maxPerTopic');\n let dbPromise: Promise<IDBDatabase> | null = null;\n const invalidate = (db: IDBDatabase): void => {\n if (dbPromise) {\n void dbPromise.then(current => {\n if (current === db) {\n current.close();\n dbPromise = null;\n }\n }, () => undefined);\n }\n };\n // IndexedDB transactions are atomic, but a read-modify-write append can\n // still lose updates when callers start several appends concurrently.\n // Serialize all mutations per adapter instance while keeping reads free.\n // Consecutive append/appendBatch entries are coalesced into a single\n // transaction at the head of the queue, so a burst spanning many microtask\n // flushes issues one transaction instead of one per flush. Ordering against\n // clears is preserved: coalescing only merges adjacent batch entries and\n // never reorders them relative to a clear.\n type QueuedMutation =\n | { kind: 'batch'; messages: ReadonlyArray<DataBusMessage<TData>> }\n | { kind: 'run'; run: () => Promise<void> };\n const pending: Array<{\n mutation: QueuedMutation;\n resolve: () => void;\n reject: (error: unknown) => void;\n }> = [];\n let draining = false;\n\n const drain = async (): Promise<void> => {\n if (draining) return;\n draining = true;\n try {\n // Let a burst of synchronous enqueues accumulate into `pending` before\n // the first coalescing pass, so a single flush cycle's batches merge\n // into one transaction instead of two.\n await Promise.resolve();\n while (pending.length > 0) {\n const head = pending[0]!.mutation;\n if (head.kind === 'batch') {\n // Merge every adjacent batch entry into one transaction.\n const merged: DataBusMessage<TData>[] = [];\n const entries: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\n while (pending.length > 0) {\n const next = pending[0]!.mutation;\n if (next.kind !== 'batch') break;\n merged.push(...next.messages);\n entries.push({ resolve: pending[0]!.resolve, reject: pending[0]!.reject });\n pending.shift();\n }\n try {\n await appendTransaction(merged);\n for (const entry of entries) entry.resolve();\n } catch (error) {\n for (const entry of entries) entry.reject(error);\n }\n } else {\n const entry = pending.shift()!;\n try {\n await head.run();\n entry.resolve();\n } catch (error) {\n entry.reject(error);\n }\n }\n }\n } finally {\n draining = false;\n }\n };\n\n const enqueue = (mutation: QueuedMutation): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n pending.push({ mutation, resolve, reject });\n void drain();\n });\n\n /** Read-modify-write one topic-batched append inside a single transaction. */\n const appendTransaction = (messages: ReadonlyArray<DataBusMessage<TData>>): Promise<void> =>\n (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try {\n transaction = db.transaction(storeName, 'readwrite');\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n const store = transaction.objectStore(storeName);\n const grouped = new Map<string, DataBusMessage<TData>[]>();\n for (const message of messages) {\n grouped.set(message.topic, [...(grouped.get(message.topic) ?? []), message]);\n }\n let hasError = false;\n const fail = (error: unknown): void => {\n if (hasError) return;\n hasError = true;\n invalidate(db);\n reject(error);\n };\n for (const [topic, topicMessages] of grouped) {\n const request = store.get(topic);\n request.onsuccess = () => {\n if (hasError) return;\n const history = pruneReplayHistory(\n ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(topicMessages),\n { maxPerTopic, pruneStrategy, retentionMs, now: Date.now() }\n );\n store.put({ topic, messages: history });\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to read replay history.'));\n }\n transaction.oncomplete = () => {\n if (!hasError) resolve();\n };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to persist replay history.'));\n // A connection loss can abort a transaction without first dispatching a\n // request error. Without this path, the serialized mutation queue would\n // stay blocked forever after the promise never settles.\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to persist replay history.'));\n });\n })();\n const open = (): Promise<IDBDatabase> => {\n if (dbPromise) return dbPromise;\n const pending = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDb.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'topic' });\n request.onsuccess = () => {\n const db = request.result;\n // A schema upgrade in another tab invalidates this connection. Close\n // it and clear the cached promise so the next operation reopens a\n // usable connection instead of repeatedly targeting a dead database.\n db.onversionchange = () => {\n db.close();\n if (dbPromise) dbPromise = null;\n };\n resolve(db);\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to open replay database.'));\n });\n dbPromise = pending;\n // Do not permanently cache a rejected open promise. IndexedDB can fail\n // transiently (quota, private-mode initialization, a closing connection,\n // or a browser shutdown); the next operation must be able to retry.\n void pending.catch(() => {\n if (dbPromise === pending) dbPromise = null;\n });\n return pending;\n };\n return {\n async load() {\n const db = await open();\n return new Promise((resolve, reject) => {\n let transaction: IDBTransaction;\n let request: IDBRequest;\n try {\n transaction = db.transaction(storeName, 'readonly');\n request = transaction.objectStore(storeName).getAll();\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n let records: Array<{ messages: DataBusMessage<TData>[] }> = [];\n request.onsuccess = () => {\n records = request.result as Array<{ messages: DataBusMessage<TData>[] }>;\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to load replay history.'));\n transaction.oncomplete = () => {\n if (settled) return;\n settled = true;\n resolve(records.flatMap(record => record.messages));\n };\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to load replay history.'));\n });\n },\n append(message) {\n return enqueue({ kind: 'batch', messages: [message] });\n },\n appendBatch(messages) {\n if (messages.length === 0) return Promise.resolve();\n return enqueue({ kind: 'batch', messages });\n },\n clear() {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n transaction.objectStore(storeName).clear();\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to clear replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to clear replay history.'));\n });\n })()\n });\n },\n clearTopic(topic) {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n transaction.objectStore(storeName).delete(topic);\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to clear topic replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to clear topic replay history.'));\n });\n })()\n });\n },\n clearBefore(timestamp) {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n const store = transaction.objectStore(storeName);\n const request = store.getAll();\n request.onsuccess = () => {\n for (const record of request.result as Array<{ topic: string; messages: DataBusMessage<TData>[] }>) {\n const messages = record.messages.filter(message => message.timestamp === undefined || message.timestamp >= timestamp);\n if (messages.length === 0) store.delete(record.topic);\n else if (messages.length !== record.messages.length) store.put({ topic: record.topic, messages });\n }\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to read replay history.'));\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to prune replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to prune replay history.'));\n });\n })()\n });\n }\n };\n}\n", "/**\n * WebSocketTransport \u2014 a dependency-free transport over a plain WebSocket.\n *\n * Validates the `DataBusTransport` abstraction with a second, minimal backend:\n * any WebSocket server that speaks the tiny JSON protocol below can back the\n * same cross-tab clustering stack (owner dedup, sticky routes, EVENT fan-out)\n * that the Centrifuge backend uses.\n *\n * Wire protocol (JSON text frames):\n * - client \u2192 server: `{\"op\":\"subscribe\"|\"unsubscribe\"|\"publish\",\"topic\":...,\"data\":...}`\n * - client \u2192 server (batched): `{\"op\":\"publishBatch\",\"topic\":...,\"items\":[{data,...}]}`\n * - server \u2192 client: `{\"topic\":...,\"data\":...}` for publications; anything\n * without a string `topic` field is ignored (forward-compatible).\n */\nimport { CrossTabDataBus } from './core/data-bus';\nimport { parseDataBusPublication } from './core/publication';\nimport type { CrossTabDataBusOptions } from './core/data-bus';\nimport { WS_OP, WORKER_STATUS } from './utils/constants';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\n DataBusPublishOptions,\n DataBusPublicationItem,\n DataBusMessage,\n MaybePromise,\n WorkerStatus\n} from './core/types';\n\n/** Minimal WebSocket surface used by the transport. Matches the browser\n * `WebSocket` subset the transport touches; injectable for tests and runtimes. */\nexport interface WebSocketLike {\n /** Current connection state; 1 (OPEN) means frames may be sent. */\n readonly readyState?: number;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n}\n\n/** Connection configuration for {@link WebSocketTransport}. */\nexport interface WebSocketDataBusConfig {\n /** WebSocket endpoint, e.g. `wss://example.test/ws`. */\n url: string;\n /** Subprotocol(s) passed to the WebSocket handshake. */\n protocols?: string | string[];\n /** Custom socket factory. Defaults to the global `WebSocket`; injectable\n * for tests and non-browser runtimes. */\n webSocketFactory?: (url: string, protocols?: string | string[]) => WebSocketLike;\n /** Milliseconds to wait for the handshake before reporting `error` and\n * failing the start. Defaults to 30000 ms; pass\n * `0` or `Infinity` to wait indefinitely. The timeout exists because\n * `start()` resolves on connect, so a socket that never opens and never\n * errors would otherwise leave the DataBus start gate (and every operation\n * queued behind it) pending forever. */\n connectTimeoutMs?: number;\n}\n\n/** Options for creating a fully-configured CrossTabDataBus with a WebSocket transport. */\nexport interface CreateWebSocketDataBusOptions<TData = unknown>\n extends Omit<\n CrossTabDataBusOptions<WebSocketDataBusConfig, TData>,\n 'autoStart' | 'clusterKey' | 'initialConfig' | 'transport'\n > {\n /** WebSocket connection configuration. */\n connection: WebSocketDataBusConfig;\n /** Cluster key for cross-tab coordination. Defaults to the connection URL. */\n clusterKey?: string;\n}\n\n/** Default handshake budget. A socket that never opens and never fires\n * error/close would otherwise keep a started transport stuck in `connecting`\n * forever, with every queued operation parked behind an unsettled `start()`. */\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000;\n\nconst WS_OPEN = 1;\n\n/** Transport that talks a minimal JSON protocol over a plain WebSocket.\n * Connection lifecycle maps directly to the DataBus status vocabulary:\n * open \u2192 `connected`, close \u2192 `disconnected`, error \u2192 `error` (which the\n * DataBus treats as its auto-recovery trigger). The transport holds no\n * reconnection logic of its own \u2014 reopening is the DataBus's job. */\nexport class WebSocketTransport<TData = unknown>\n implements DataBusTransport<WebSocketDataBusConfig, TData>\n{\n readonly diagnosticsName = 'websocket';\n readonly diagnosticsBackend = 'native-websocket';\n private socket: WebSocketLike | null = null;\n private socketActive = false;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n // Handshake gate for the current start(). Resolves once the socket opens,\n // rejects when the attempt fails, so the DataBus start Promise \u2014 and every\n // operation parked behind it \u2014 settles at the real connection boundary.\n private connectPromise: Promise<void> | null = null;\n private connectResolve: (() => void) | null = null;\n private connectReject: ((error: unknown) => void) | null = null;\n private connectTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. Resolves once the\n * handshake completes and rejects when the attempt fails, matching the\n * `DataBusTransport.start` contract (\"resolves on connect or rejects on\n * failure\"). A factory failure is reported through `onStatus('error')` so\n * the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket && this.socketActive) {\n // Reuse the live socket instead of orphaning it. While the first\n // attempt is still connecting, share its handshake gate so a duplicate\n // start() cannot report readiness before the socket is usable.\n return this.connectPromise ?? undefined;\n }\n // A failed or closed socket is one-shot; retain its object only long\n // enough for a transparent same-object reopen to fire, but replace it\n // whenever start() is called again. Clearing the reference here also\n // makes every late callback from the old socket a no-op.\n this.socket = null;\n this.socketActive = false;\n this.handlers = handlers;\n // The factory may live on the constructor connection (createWebSocketDataBus\n // path) or on the runtime config (direct transport use) \u2014 accept both.\n const factory = config.webSocketFactory ?? this.connection.webSocketFactory ?? defaultWebSocketFactory;\n const protocols = config.protocols ?? this.connection.protocols;\n let socket: WebSocketLike;\n try {\n socket = factory(config.url, protocols);\n } catch (error) {\n handlers.onStatus(WORKER_STATUS.ERROR);\n handlers.onError(error);\n return;\n }\n const opening = new Promise<void>((resolve, reject) => {\n this.connectResolve = resolve;\n this.connectReject = reject;\n // Per-attempt handshake state. A socket that opens, then closes and\n // re-opens in place (a protocol-level recovery) may reuse the same\n // attempt; a timeout or a close/error before the first open permanently\n // invalidates it so a late onopen cannot report readiness.\n let handshakeCompleted = false;\n let handshakeFailed = false;\n const timeoutMs =\n config.connectTimeoutMs ?? this.connection.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n if (Number.isFinite(timeoutMs) && timeoutMs > 0) {\n this.connectTimer = setTimeout(() => {\n if (this.socket !== socket || this.handlers !== handlers || handshakeCompleted) return;\n handshakeFailed = true;\n this.connectTimer = null;\n this.socketActive = false;\n const error = new Error(`WebSocket did not open within ${timeoutMs}ms.`);\n handlers.onStatus(WORKER_STATUS.ERROR);\n handlers.onError(error);\n this.failConnect(error);\n // Abort the half-open handshake so the timed-out attempt cannot\n // linger in CONNECTING or deliver a late onopen.\n socket.close();\n }, timeoutMs);\n }\n socket.onopen = () => {\n if (this.socket !== socket || this.handlers !== handlers || handshakeFailed) return;\n this.socketActive = true;\n this.clearConnectTimer();\n // Re-assert every topic so a reopened socket (recovery path) restores\n // the server-side subscriptions without DataBus involvement.\n for (const topic of this.subscribedTopics) {\n this.sendFrame({ op: WS_OP.SUBSCRIBE, topic });\n }\n handlers.onStatus(WORKER_STATUS.CONNECTED);\n if (!handshakeCompleted) {\n handshakeCompleted = true;\n this.settleConnect();\n }\n };\n socket.onclose = () => {\n if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;\n this.socketActive = false;\n handlers.onStatus(WORKER_STATUS.DISCONNECTED);\n if (!handshakeCompleted) {\n handshakeFailed = true;\n this.failConnect(new Error('WebSocket closed before the handshake completed.'));\n }\n };\n socket.onerror = () => {\n if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;\n this.socketActive = false;\n handlers.onStatus(WORKER_STATUS.ERROR);\n if (!handshakeCompleted) {\n handshakeFailed = true;\n this.failConnect(new Error('WebSocket failed to open.'));\n }\n };\n socket.onmessage = event => {\n if (this.socket === socket && this.handlers === handlers && this.socketActive) {\n void this.handleMessage(event.data);\n }\n };\n this.socket = socket;\n this.socketActive = true;\n });\n this.connectPromise = opening;\n return opening;\n }\n\n /** Idempotent: re-subscribing an active topic re-sends the frame but does\n * not duplicate the local tracking entry. */\n subscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.add(topic);\n this.sendFrame({ op: WS_OP.SUBSCRIBE, topic });\n }\n\n /** Idempotent: unsubscribing an unknown topic is a no-op. */\n unsubscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.delete(topic);\n this.sendFrame({ op: WS_OP.UNSUBSCRIBE, topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown, options?: DataBusPublishOptions): MaybePromise<void> {\n if (data instanceof ArrayBuffer) {\n this.sendBinaryFrame(topic, data, options?.messageId, options?.timestamp);\n return;\n }\n this.sendFrame({\n op: WS_OP.PUBLISH,\n topic,\n data,\n ...(options?.messageId === undefined ? {} : { messageId: options.messageId }),\n ...(options?.timestamp === undefined ? {} : { timestamp: options.timestamp })\n });\n }\n\n /** Publish many items for one topic as a single wire frame. One-item\n * batches delegate to `publish` so the legacy single-publication frame\n * shape (including binary framing) is preserved. */\n publishBatch(topic: string, items: ReadonlyArray<DataBusPublicationItem>): MaybePromise<void> {\n if (items.length === 0) return;\n if (items.length === 1) {\n const single = items[0]!;\n return this.publish(topic, single.data, {\n ...(single.messageId === undefined ? {} : { messageId: single.messageId }),\n ...(single.timestamp === undefined ? {} : { timestamp: single.timestamp })\n });\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publishBatch\" frame.'));\n return;\n }\n // Binary payloads are embedded as byte arrays so the whole batch stays in\n // one JSON frame; the server re-fans them out as individual publications.\n this.socket.send(JSON.stringify({\n op: WS_OP.PUBLISH_BATCH,\n topic,\n items: items.map(item => ({\n data: item.data instanceof ArrayBuffer ? Array.from(new Uint8Array(item.data)) : item.data,\n ...(item.messageId === undefined ? {} : { messageId: item.messageId }),\n ...(item.timestamp === undefined ? {} : { timestamp: item.timestamp })\n }))\n }));\n }\n\n /** Close the socket and drop all state. Safe to call multiple times. */\n stop(): MaybePromise<void> {\n const socket = this.socket;\n const shouldClose = this.socketActive;\n this.socket = null;\n this.socketActive = false;\n this.handlers = null;\n this.subscribedTopics.clear();\n // Settle an in-flight handshake gate: a DataBus stop() awaits the start\n // Promise, so leaving it pending would hang teardown. Resolving (rather\n // than rejecting) keeps an intentional stop from surfacing as an error.\n this.settleConnect();\n this.connectPromise = null;\n if (shouldClose) socket?.close();\n }\n\n /** Resolve the in-flight handshake gate. Idempotent: once the socket has\n * opened (or a newer attempt replaced it) later calls are no-ops. */\n private settleConnect(): void {\n this.clearConnectTimer();\n const resolve = this.connectResolve;\n this.connectResolve = null;\n this.connectReject = null;\n resolve?.();\n }\n\n /** Reject the in-flight handshake gate. Idempotent on the same terms as\n * {@link settleConnect}. */\n private failConnect(error: unknown): void {\n this.clearConnectTimer();\n const reject = this.connectReject;\n this.connectResolve = null;\n this.connectReject = null;\n reject?.(error);\n }\n\n private clearConnectTimer(): void {\n if (this.connectTimer !== null) {\n clearTimeout(this.connectTimer);\n this.connectTimer = null;\n }\n }\n\n /** Send one JSON frame. Frames are dropped with an `onError` report when\n * the socket is not open \u2014 subscribe frames are re-sent on open, so the\n * only real loss is a publish during a disconnect window. */\n private sendFrame(payload: { op: string; topic: string; data?: unknown; messageId?: string; timestamp?: number }): void {\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error(`WebSocket is not open; dropped \"${payload.op}\" frame.`));\n return;\n }\n this.socket.send(JSON.stringify(payload));\n }\n\n private sendBinaryFrame(topic: string, data: ArrayBuffer, messageId?: string, timestamp?: number): void {\n if (messageId !== undefined || timestamp !== undefined) {\n // Binary frames retain their compact legacy shape; metadata is sent as a\n // JSON envelope so IDs are never silently lost.\n this.sendFrame({\n op: WS_OP.PUBLISH,\n topic,\n data: Array.from(new Uint8Array(data)),\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n });\n return;\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publish\" frame.'));\n return;\n }\n const topicBytes = new TextEncoder().encode(topic);\n if (topicBytes.length > 0xffff) {\n this.handlers?.onError(new Error('WebSocket topic is too long for a binary frame.'));\n return;\n }\n const frame = new Uint8Array(3 + topicBytes.length + data.byteLength);\n frame[0] = 0xc7;\n new DataView(frame.buffer).setUint16(1, topicBytes.length);\n frame.set(topicBytes, 3);\n frame.set(new Uint8Array(data), 3 + topicBytes.length);\n this.socket.send(frame.buffer);\n }\n\n /** Parse a server frame. Only objects carrying a string `topic` are\n * publications; malformed JSON and unknown shapes are ignored so a chatty\n * server cannot crash the message path. */\n private async handleMessage(raw: unknown): Promise<void> {\n // Browser WebSockets may deliver binary frames as Blob unless\n // `binaryType = 'arraybuffer'` is explicitly configured by the host.\n // Normalize Blob asynchronously and reuse the exact ArrayBuffer parser.\n if (typeof Blob !== 'undefined' && raw instanceof Blob) {\n try {\n await this.handleMessage(await raw.arrayBuffer());\n } catch (error) {\n this.handlers?.onError(error);\n }\n return;\n }\n let parsed: unknown;\n if (raw instanceof ArrayBuffer) {\n const bytes = new Uint8Array(raw);\n if (bytes[0] !== 0xc7 || bytes.length < 3) return;\n const topicLength = new DataView(raw).getUint16(1);\n if (bytes.length < 3 + topicLength) return;\n const topic = new TextDecoder().decode(bytes.subarray(3, 3 + topicLength));\n const data = bytes.slice(3 + topicLength).buffer;\n this.handlers?.onMessage({ topic, data: data as TData });\n return;\n }\n if (typeof raw !== 'string') return;\n try {\n parsed = JSON.parse(raw);\n } catch {\n this.handlers?.onError(new Error('WebSocket server sent a non-JSON frame.'));\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n const publication = parseDataBusPublication<TData>(parsed);\n if (publication) this.handlers?.onMessage(publication as DataBusMessage<TData>);\n }\n}\n\n/** Resolve the platform WebSocket, or null in runtimes without one (SSR/Node). */\nfunction defaultWebSocketFactory(url: string, protocols?: string | string[]): WebSocketLike {\n if (typeof WebSocket === 'undefined') {\n throw new Error('WebSocketTransport requires a WebSocket implementation.');\n }\n return new WebSocket(url, protocols) as unknown as WebSocketLike;\n}\n\n/** Create a CrossTabDataBus backed by a plain WebSocket transport.\n * Cross-tab clustering (owner dedup, sticky routes, failover) works identically\n * to the Centrifuge backend \u2014 only the transport I/O differs. */\nexport function createWebSocketDataBus<TData = unknown>(\n options: CreateWebSocketDataBusOptions<TData>\n): CrossTabDataBus<WebSocketDataBusConfig, TData> {\n const { clusterKey, connection, ...dataBusOptions } = options;\n return new CrossTabDataBus({\n ...dataBusOptions,\n autoStart: true,\n clusterKey: clusterKey ?? connection.url,\n initialConfig: connection,\n transport: new WebSocketTransport<TData>(connection)\n });\n}\n\n/** Re-export for convenience: the status type used by the transport. */\nexport type { WorkerStatus };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAAS,iCACd,SACiC;AACjC,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,+CAA+C;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY;AAClB,QAAM,cAAc,QAAQ;AAC5B,QAAM,gBAAgB,QAAQ,iBAAiB,eAAe;AAC9D,QAAM,cAAc,QAAQ;AAC5B,sBAAoB,aAAa;AACjC,MAAI,gBAAgB,OAAW,4B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,wBAAwB,KAAa,WAA8C;AAC1F,MAAI,OAAO,cAAc,aAAa;AACpC,UAAM,IAAI,MAAM,yDAAyD;AAAA,EAC3E;AACA,SAAO,IAAI,UAAU,KAAK,SAAS;AACrC;AAKO,SAAS,uBACd,SACgD;AAChD,QAAM,EAAE,YAAY,YAAY,GAAG,eAAe,IAAI;AACtD,SAAO,IAAI,gBAAgB;AAAA,IACzB,GAAG;AAAA,IACH,WAAW;AAAA,IACX,YAAY,cAAc,WAAW;AAAA,IACrC,eAAe;AAAA,IACf,WAAW,IAAI,mBAA0B,UAAU;AAAA,EACrD,CAAC;AACH;",
4
+ "sourcesContent": ["import type { DataBusMessage } from './types';\nimport { pruneReplayHistory } from './replay-pruning';\nimport { DEFAULT_STORAGE_PREFIX, PRUNE_STRATEGY } from '../utils/constants';\nimport { assertPositiveFiniteNumber, assertPositiveSafeInteger, assertPruneStrategy } from '../utils/validation';\n\n/** Optional persistence backend for replay history. */\nexport interface DataBusReplayPersistence<TData = unknown> {\n load(): Promise<ReadonlyArray<DataBusMessage<TData>>>;\n append(message: DataBusMessage<TData>): Promise<void>;\n /** Optional bulk append used to amortize IndexedDB transaction overhead. */\n appendBatch?(messages: ReadonlyArray<DataBusMessage<TData>>): Promise<void>;\n /** Remove all persisted replay history. */\n clear?(): Promise<void>;\n /** Remove persisted replay history for one exact topic. */\n clearTopic?(topic: string): Promise<void>;\n /** Remove persisted messages older than the given epoch-millisecond cutoff. */\n clearBefore?(timestamp: number): Promise<void>;\n}\n\nexport interface IndexedDbReplayPersistenceOptions {\n dbName?: string;\n maxPerTopic: number;\n pruneStrategy?: (typeof PRUNE_STRATEGY)[keyof typeof PRUNE_STRATEGY];\n retentionMs?: number;\n}\n\n/** Create a browser IndexedDB-backed replay store. */\nexport function createIndexedDbReplayPersistence<TData = unknown>(\n options: IndexedDbReplayPersistenceOptions\n): DataBusReplayPersistence<TData> {\n const indexedDb = globalThis.indexedDB;\n if (!indexedDb) throw new Error('IndexedDB is unavailable in this environment.');\n const dbName = options.dbName ?? DEFAULT_STORAGE_PREFIX;\n const storeName = 'replay';\n const maxPerTopic = options.maxPerTopic;\n const pruneStrategy = options.pruneStrategy ?? PRUNE_STRATEGY.COUNT;\n const retentionMs = options.retentionMs;\n assertPruneStrategy(pruneStrategy);\n if (retentionMs !== undefined) assertPositiveFiniteNumber(retentionMs, 'retentionMs');\n assertPositiveSafeInteger(maxPerTopic, 'maxPerTopic');\n let dbPromise: Promise<IDBDatabase> | null = null;\n const invalidate = (db: IDBDatabase): void => {\n if (dbPromise) {\n void dbPromise.then(current => {\n if (current === db) {\n current.close();\n dbPromise = null;\n }\n }, () => undefined);\n }\n };\n // IndexedDB transactions are atomic, but a read-modify-write append can\n // still lose updates when callers start several appends concurrently.\n // Serialize all mutations per adapter instance while keeping reads free.\n // Consecutive append/appendBatch entries are coalesced into a single\n // transaction at the head of the queue, so a burst spanning many microtask\n // flushes issues one transaction instead of one per flush. Ordering against\n // clears is preserved: coalescing only merges adjacent batch entries and\n // never reorders them relative to a clear.\n type QueuedMutation =\n | { kind: 'batch'; messages: ReadonlyArray<DataBusMessage<TData>> }\n | { kind: 'run'; run: () => Promise<void> };\n const pending: Array<{\n mutation: QueuedMutation;\n resolve: () => void;\n reject: (error: unknown) => void;\n }> = [];\n let draining = false;\n\n const drain = async (): Promise<void> => {\n if (draining) return;\n draining = true;\n try {\n // Let a burst of synchronous enqueues accumulate into `pending` before\n // the first coalescing pass, so a single flush cycle's batches merge\n // into one transaction instead of two.\n await Promise.resolve();\n while (pending.length > 0) {\n const head = pending[0]!.mutation;\n if (head.kind === 'batch') {\n // Merge every adjacent batch entry into one transaction.\n const merged: DataBusMessage<TData>[] = [];\n const entries: Array<{ resolve: () => void; reject: (error: unknown) => void }> = [];\n while (pending.length > 0) {\n const next = pending[0]!.mutation;\n if (next.kind !== 'batch') break;\n merged.push(...next.messages);\n entries.push({ resolve: pending[0]!.resolve, reject: pending[0]!.reject });\n pending.shift();\n }\n try {\n await appendTransaction(merged);\n for (const entry of entries) entry.resolve();\n } catch (error) {\n for (const entry of entries) entry.reject(error);\n }\n } else {\n const entry = pending.shift()!;\n try {\n await head.run();\n entry.resolve();\n } catch (error) {\n entry.reject(error);\n }\n }\n }\n } finally {\n draining = false;\n }\n };\n\n const enqueue = (mutation: QueuedMutation): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n pending.push({ mutation, resolve, reject });\n void drain();\n });\n\n /** Read-modify-write one topic-batched append inside a single transaction. */\n const appendTransaction = (messages: ReadonlyArray<DataBusMessage<TData>>): Promise<void> =>\n (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try {\n transaction = db.transaction(storeName, 'readwrite');\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n const store = transaction.objectStore(storeName);\n const grouped = new Map<string, DataBusMessage<TData>[]>();\n for (const message of messages) {\n grouped.set(message.topic, [...(grouped.get(message.topic) ?? []), message]);\n }\n let hasError = false;\n const fail = (error: unknown): void => {\n if (hasError) return;\n hasError = true;\n invalidate(db);\n reject(error);\n };\n for (const [topic, topicMessages] of grouped) {\n const request = store.get(topic);\n request.onsuccess = () => {\n if (hasError) return;\n const history = pruneReplayHistory(\n ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(topicMessages),\n { maxPerTopic, pruneStrategy, retentionMs, now: Date.now() }\n );\n store.put({ topic, messages: history });\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to read replay history.'));\n }\n transaction.oncomplete = () => {\n if (!hasError) resolve();\n };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to persist replay history.'));\n // A connection loss can abort a transaction without first dispatching a\n // request error. Without this path, the serialized mutation queue would\n // stay blocked forever after the promise never settles.\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to persist replay history.'));\n });\n })();\n const open = (): Promise<IDBDatabase> => {\n if (dbPromise) return dbPromise;\n const pending = new Promise<IDBDatabase>((resolve, reject) => {\n const request = indexedDb.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'topic' });\n request.onsuccess = () => {\n const db = request.result;\n // A schema upgrade in another tab invalidates this connection. Close\n // it and clear the cached promise so the next operation reopens a\n // usable connection instead of repeatedly targeting a dead database.\n db.onversionchange = () => {\n db.close();\n if (dbPromise) dbPromise = null;\n };\n resolve(db);\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to open replay database.'));\n });\n dbPromise = pending;\n // Do not permanently cache a rejected open promise. IndexedDB can fail\n // transiently (quota, private-mode initialization, a closing connection,\n // or a browser shutdown); the next operation must be able to retry.\n void pending.catch(() => {\n if (dbPromise === pending) dbPromise = null;\n });\n return pending;\n };\n return {\n async load() {\n const db = await open();\n return new Promise((resolve, reject) => {\n let transaction: IDBTransaction;\n let request: IDBRequest;\n try {\n transaction = db.transaction(storeName, 'readonly');\n request = transaction.objectStore(storeName).getAll();\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n let records: Array<{ messages: DataBusMessage<TData>[] }> = [];\n request.onsuccess = () => {\n records = request.result as Array<{ messages: DataBusMessage<TData>[] }>;\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to load replay history.'));\n transaction.oncomplete = () => {\n if (settled) return;\n settled = true;\n resolve(records.flatMap(record => record.messages));\n };\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to load replay history.'));\n });\n },\n append(message) {\n return enqueue({ kind: 'batch', messages: [message] });\n },\n appendBatch(messages) {\n if (messages.length === 0) return Promise.resolve();\n return enqueue({ kind: 'batch', messages });\n },\n clear() {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n transaction.objectStore(storeName).clear();\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to clear replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to clear replay history.'));\n });\n })()\n });\n },\n clearTopic(topic) {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n transaction.objectStore(storeName).delete(topic);\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to clear topic replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to clear topic replay history.'));\n });\n })()\n });\n },\n clearBefore(timestamp) {\n return enqueue({\n kind: 'run',\n run: () => (async () => {\n const db = await open();\n return new Promise<void>((resolve, reject) => {\n let transaction: IDBTransaction;\n try { transaction = db.transaction(storeName, 'readwrite'); }\n catch (error) { invalidate(db); reject(error); return; }\n let settled = false;\n const fail = (error: unknown): void => {\n if (settled) return;\n settled = true;\n invalidate(db);\n reject(error);\n };\n const store = transaction.objectStore(storeName);\n const request = store.getAll();\n request.onsuccess = () => {\n for (const record of request.result as Array<{ topic: string; messages: DataBusMessage<TData>[] }>) {\n const messages = record.messages.filter(message => message.timestamp === undefined || message.timestamp >= timestamp);\n if (messages.length === 0) store.delete(record.topic);\n else if (messages.length !== record.messages.length) store.put({ topic: record.topic, messages });\n }\n };\n request.onerror = () => fail(request.error ?? new Error('Failed to read replay history.'));\n transaction.oncomplete = () => { settled = true; resolve(); };\n transaction.onerror = () => fail(transaction.error ?? new Error('Failed to prune replay history.'));\n transaction.onabort = () => fail(transaction.error ?? new Error('Failed to prune replay history.'));\n });\n })()\n });\n }\n };\n}\n", "/**\n * WebSocketTransport \u2014 a dependency-free transport over a plain WebSocket.\n *\n * Validates the `DataBusTransport` abstraction with a second, minimal backend:\n * any WebSocket server that speaks the tiny JSON protocol below can back the\n * same cross-tab clustering stack (owner dedup, sticky routes, EVENT fan-out)\n * that the Centrifuge backend uses.\n *\n * Wire protocol (JSON text frames):\n * - client \u2192 server: `{\"op\":\"subscribe\"|\"unsubscribe\"|\"publish\",\"topic\":...,\"data\":...}`\n * - client \u2192 server (batched): `{\"op\":\"publishBatch\",\"topic\":...,\"items\":[{data,...}]}`\n * - server \u2192 client: `{\"topic\":...,\"data\":...}` for publications; anything\n * without a string `topic` field is ignored (forward-compatible).\n */\nimport { CrossTabDataBus } from './core/data-bus';\nimport { parseDataBusPublication } from './core/publication';\nimport type { CrossTabDataBusOptions } from './core/data-bus';\nimport { WS_OP, WORKER_STATUS } from './utils/constants';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\n DataBusPublishOptions,\n DataBusPublicationItem,\n DataBusMessage,\n MaybePromise,\n WorkerStatus\n} from './core/types';\n\n/** Minimal WebSocket surface used by the transport. Matches the browser\n * `WebSocket` subset the transport touches; injectable for tests and runtimes. */\nexport interface WebSocketLike {\n /** Current connection state; 1 (OPEN) means frames may be sent. */\n readonly readyState?: number;\n send(data: string | ArrayBuffer): void;\n close(code?: number, reason?: string): void;\n onopen: (() => void) | null;\n onclose: (() => void) | null;\n onerror: (() => void) | null;\n onmessage: ((event: { data: unknown }) => void) | null;\n}\n\n/** Connection configuration for {@link WebSocketTransport}. */\nexport interface WebSocketDataBusConfig {\n /** WebSocket endpoint, e.g. `wss://example.test/ws`. */\n url: string;\n /** Subprotocol(s) passed to the WebSocket handshake. */\n protocols?: string | string[];\n /** Custom socket factory. Defaults to the global `WebSocket`; injectable\n * for tests and non-browser runtimes. */\n webSocketFactory?: (url: string, protocols?: string | string[]) => WebSocketLike;\n /** Milliseconds to wait for the handshake before reporting `error` and\n * failing the start. Defaults to 30000 ms; pass\n * `0` or `Infinity` to wait indefinitely. The timeout exists because\n * `start()` resolves on connect, so a socket that never opens and never\n * errors would otherwise leave the DataBus start gate (and every operation\n * queued behind it) pending forever. */\n connectTimeoutMs?: number;\n}\n\n/** Options for creating a fully-configured CrossTabDataBus with a WebSocket transport. */\nexport interface CreateWebSocketDataBusOptions<TData = unknown>\n extends Omit<\n CrossTabDataBusOptions<WebSocketDataBusConfig, TData>,\n 'autoStart' | 'clusterKey' | 'initialConfig' | 'transport'\n > {\n /** WebSocket connection configuration. */\n connection: WebSocketDataBusConfig;\n /** Cluster key for cross-tab coordination. Defaults to the connection URL. */\n clusterKey?: string;\n}\n\n/** Default handshake budget. A socket that never opens and never fires\n * error/close would otherwise keep a started transport stuck in `connecting`\n * forever, with every queued operation parked behind an unsettled `start()`. */\nconst DEFAULT_CONNECT_TIMEOUT_MS = 30_000;\n\nconst WS_OPEN = 1;\n\n/** Transport that talks a minimal JSON protocol over a plain WebSocket.\n * Connection lifecycle maps directly to the DataBus status vocabulary:\n * open \u2192 `connected`, close \u2192 `disconnected`, error \u2192 `error` (which the\n * DataBus treats as its auto-recovery trigger). The transport holds no\n * reconnection logic of its own \u2014 reopening is the DataBus's job. */\nexport class WebSocketTransport<TData = unknown>\n implements DataBusTransport<WebSocketDataBusConfig, TData>\n{\n readonly diagnosticsName = 'websocket';\n readonly diagnosticsBackend = 'native-websocket';\n private socket: WebSocketLike | null = null;\n private socketActive = false;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n // Handshake gate for the current start(). Resolves once the socket opens,\n // rejects when the attempt fails, so the DataBus start Promise \u2014 and every\n // operation parked behind it \u2014 settles at the real connection boundary.\n private connectPromise: Promise<void> | null = null;\n private connectResolve: (() => void) | null = null;\n private connectReject: ((error: unknown) => void) | null = null;\n private connectTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. Resolves once the\n * handshake completes and rejects when the attempt fails, matching the\n * `DataBusTransport.start` contract (\"resolves on connect or rejects on\n * failure\"). A factory failure is reported through `onStatus('error')` so\n * the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket && this.socketActive) {\n // Reuse the live socket instead of orphaning it. While the first\n // attempt is still connecting, share its handshake gate so a duplicate\n // start() cannot report readiness before the socket is usable.\n return this.connectPromise ?? undefined;\n }\n // A failed or closed socket is one-shot; retain its object only long\n // enough for a transparent same-object reopen to fire, but replace it\n // whenever start() is called again. Clearing the reference here also\n // makes every late callback from the old socket a no-op.\n this.socket = null;\n this.socketActive = false;\n this.handlers = handlers;\n // The factory may live on the constructor connection (createWebSocketDataBus\n // path) or on the runtime config (direct transport use) \u2014 accept both.\n const factory = config.webSocketFactory ?? this.connection.webSocketFactory ?? defaultWebSocketFactory;\n const protocols = config.protocols ?? this.connection.protocols;\n let socket: WebSocketLike;\n try {\n socket = factory(config.url, protocols);\n } catch (error) {\n handlers.onStatus(WORKER_STATUS.ERROR);\n handlers.onError(error);\n return;\n }\n const opening = new Promise<void>((resolve, reject) => {\n this.connectResolve = resolve;\n this.connectReject = reject;\n // Per-attempt handshake state. A socket that opens, then closes and\n // re-opens in place (a protocol-level recovery) may reuse the same\n // attempt; a timeout or a close/error before the first open permanently\n // invalidates it so a late onopen cannot report readiness.\n let handshakeCompleted = false;\n let handshakeFailed = false;\n const timeoutMs =\n config.connectTimeoutMs ?? this.connection.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;\n if (Number.isFinite(timeoutMs) && timeoutMs > 0) {\n this.connectTimer = setTimeout(() => {\n if (this.socket !== socket || this.handlers !== handlers || handshakeCompleted) return;\n handshakeFailed = true;\n this.connectTimer = null;\n this.socketActive = false;\n const error = new Error(`WebSocket did not open within ${timeoutMs}ms.`);\n handlers.onStatus(WORKER_STATUS.ERROR);\n handlers.onError(error);\n this.failConnect(error);\n // Abort the half-open handshake so the timed-out attempt cannot\n // linger in CONNECTING or deliver a late onopen.\n socket.close();\n }, timeoutMs);\n }\n socket.onopen = () => {\n if (this.socket !== socket || this.handlers !== handlers || handshakeFailed) return;\n this.socketActive = true;\n this.clearConnectTimer();\n // Re-assert every topic so a reopened socket (recovery path) restores\n // the server-side subscriptions without DataBus involvement.\n for (const topic of this.subscribedTopics) {\n this.sendFrame({ op: WS_OP.SUBSCRIBE, topic });\n }\n handlers.onStatus(WORKER_STATUS.CONNECTED);\n if (!handshakeCompleted) {\n handshakeCompleted = true;\n this.settleConnect();\n }\n };\n socket.onclose = () => {\n if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;\n this.socketActive = false;\n handlers.onStatus(WORKER_STATUS.DISCONNECTED);\n if (!handshakeCompleted) {\n handshakeFailed = true;\n this.failConnect(new Error('WebSocket closed before the handshake completed.'));\n }\n };\n socket.onerror = () => {\n if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;\n this.socketActive = false;\n handlers.onStatus(WORKER_STATUS.ERROR);\n if (!handshakeCompleted) {\n handshakeFailed = true;\n this.failConnect(new Error('WebSocket failed to open.'));\n }\n };\n socket.onmessage = event => {\n if (this.socket === socket && this.handlers === handlers && this.socketActive) {\n void this.handleMessage(event.data);\n }\n };\n this.socket = socket;\n this.socketActive = true;\n });\n this.connectPromise = opening;\n return opening;\n }\n\n /** Idempotent: re-subscribing an active topic re-sends the frame but does\n * not duplicate the local tracking entry. */\n subscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.add(topic);\n this.sendFrame({ op: WS_OP.SUBSCRIBE, topic });\n }\n\n /** Idempotent: unsubscribing an unknown topic is a no-op. */\n unsubscribe(topic: string): MaybePromise<void> {\n this.subscribedTopics.delete(topic);\n this.sendFrame({ op: WS_OP.UNSUBSCRIBE, topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown, options?: DataBusPublishOptions): MaybePromise<void> {\n if (data instanceof ArrayBuffer) {\n this.sendBinaryFrame(topic, data, options?.messageId, options?.timestamp);\n return;\n }\n this.sendFrame({\n op: WS_OP.PUBLISH,\n topic,\n data,\n ...(options?.messageId === undefined ? {} : { messageId: options.messageId }),\n ...(options?.timestamp === undefined ? {} : { timestamp: options.timestamp })\n });\n }\n\n /** Publish many items for one topic as a single wire frame. One-item\n * batches delegate to `publish` so the legacy single-publication frame\n * shape (including binary framing) is preserved. */\n publishBatch(topic: string, items: ReadonlyArray<DataBusPublicationItem>): MaybePromise<void> {\n if (items.length === 0) return;\n if (items.length === 1) {\n const single = items[0]!;\n return this.publish(topic, single.data, {\n ...(single.messageId === undefined ? {} : { messageId: single.messageId }),\n ...(single.timestamp === undefined ? {} : { timestamp: single.timestamp })\n });\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publishBatch\" frame.'));\n return;\n }\n // Binary payloads are embedded as byte arrays so the whole batch stays in\n // one JSON frame; the server re-fans them out as individual publications.\n this.socket.send(JSON.stringify({\n op: WS_OP.PUBLISH_BATCH,\n topic,\n items: items.map(item => ({\n data: item.data instanceof ArrayBuffer ? Array.from(new Uint8Array(item.data)) : item.data,\n ...(item.messageId === undefined ? {} : { messageId: item.messageId }),\n ...(item.timestamp === undefined ? {} : { timestamp: item.timestamp })\n }))\n }));\n }\n\n /** Close the socket and drop all state. Safe to call multiple times. */\n stop(): MaybePromise<void> {\n const socket = this.socket;\n const shouldClose = this.socketActive;\n this.socket = null;\n this.socketActive = false;\n this.handlers = null;\n this.subscribedTopics.clear();\n // Settle an in-flight handshake gate: a DataBus stop() awaits the start\n // Promise, so leaving it pending would hang teardown. Resolving (rather\n // than rejecting) keeps an intentional stop from surfacing as an error.\n this.settleConnect();\n this.connectPromise = null;\n if (shouldClose) socket?.close();\n }\n\n /** Resolve the in-flight handshake gate. Idempotent: once the socket has\n * opened (or a newer attempt replaced it) later calls are no-ops. */\n private settleConnect(): void {\n this.clearConnectTimer();\n const resolve = this.connectResolve;\n this.connectResolve = null;\n this.connectReject = null;\n resolve?.();\n }\n\n /** Reject the in-flight handshake gate. Idempotent on the same terms as\n * {@link settleConnect}. */\n private failConnect(error: unknown): void {\n this.clearConnectTimer();\n const reject = this.connectReject;\n this.connectResolve = null;\n this.connectReject = null;\n reject?.(error);\n }\n\n private clearConnectTimer(): void {\n if (this.connectTimer !== null) {\n clearTimeout(this.connectTimer);\n this.connectTimer = null;\n }\n }\n\n /** Send one JSON frame. Frames are dropped with an `onError` report when\n * the socket is not open \u2014 subscribe frames are re-sent on open, so the\n * only real loss is a publish during a disconnect window. */\n private sendFrame(payload: { op: string; topic: string; data?: unknown; messageId?: string; timestamp?: number }): void {\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error(`WebSocket is not open; dropped \"${payload.op}\" frame.`));\n return;\n }\n this.socket.send(JSON.stringify(payload));\n }\n\n private sendBinaryFrame(topic: string, data: ArrayBuffer, messageId?: string, timestamp?: number): void {\n if (messageId !== undefined || timestamp !== undefined) {\n // Binary frames retain their compact legacy shape; metadata is sent as a\n // JSON envelope so IDs are never silently lost.\n this.sendFrame({\n op: WS_OP.PUBLISH,\n topic,\n data: Array.from(new Uint8Array(data)),\n ...(messageId === undefined ? {} : { messageId }),\n ...(timestamp === undefined ? {} : { timestamp })\n });\n return;\n }\n if (this.socket?.readyState !== WS_OPEN) {\n this.handlers?.onError(new Error('WebSocket is not open; dropped \"publish\" frame.'));\n return;\n }\n const topicBytes = new TextEncoder().encode(topic);\n if (topicBytes.length > 0xffff) {\n this.handlers?.onError(new Error('WebSocket topic is too long for a binary frame.'));\n return;\n }\n const frame = new Uint8Array(3 + topicBytes.length + data.byteLength);\n frame[0] = 0xc7;\n new DataView(frame.buffer).setUint16(1, topicBytes.length);\n frame.set(topicBytes, 3);\n frame.set(new Uint8Array(data), 3 + topicBytes.length);\n this.socket.send(frame.buffer);\n }\n\n /** Parse a server frame. Only objects carrying a string `topic` are\n * publications; malformed JSON and unknown shapes are ignored so a chatty\n * server cannot crash the message path. */\n private async handleMessage(raw: unknown): Promise<void> {\n // Browser WebSockets may deliver binary frames as Blob unless\n // `binaryType = 'arraybuffer'` is explicitly configured by the host.\n // Normalize Blob asynchronously and reuse the exact ArrayBuffer parser.\n if (typeof Blob !== 'undefined' && raw instanceof Blob) {\n // Blob conversion is asynchronous. Capture the socket/handler pair so a\n // stop/start that replaces the connection while arrayBuffer() is pending\n // cannot let the stale frame leak into the new connection's handlers.\n const socket = this.socket;\n const handlers = this.handlers;\n try {\n const buffer = await raw.arrayBuffer();\n if (this.socket !== socket || this.handlers !== handlers || !this.socketActive) return;\n await this.handleMessage(buffer);\n } catch (error) {\n if (this.socket === socket && this.handlers === handlers && this.socketActive) {\n this.handlers?.onError(error);\n }\n }\n return;\n }\n let parsed: unknown;\n if (raw instanceof ArrayBuffer) {\n const bytes = new Uint8Array(raw);\n if (bytes[0] !== 0xc7 || bytes.length < 3) return;\n const topicLength = new DataView(raw).getUint16(1);\n if (bytes.length < 3 + topicLength) return;\n const topic = new TextDecoder().decode(bytes.subarray(3, 3 + topicLength));\n const data = bytes.slice(3 + topicLength).buffer;\n this.handlers?.onMessage({ topic, data: data as TData });\n return;\n }\n if (typeof raw !== 'string') return;\n try {\n parsed = JSON.parse(raw);\n } catch {\n this.handlers?.onError(new Error('WebSocket server sent a non-JSON frame.'));\n return;\n }\n if (!parsed || typeof parsed !== 'object') return;\n const publication = parseDataBusPublication<TData>(parsed);\n if (publication) this.handlers?.onMessage(publication as DataBusMessage<TData>);\n }\n}\n\n/** Resolve the platform WebSocket, or null in runtimes without one (SSR/Node). */\nfunction defaultWebSocketFactory(url: string, protocols?: string | string[]): WebSocketLike {\n if (typeof WebSocket === 'undefined') {\n throw new Error('WebSocketTransport requires a WebSocket implementation.');\n }\n return new WebSocket(url, protocols) as unknown as WebSocketLike;\n}\n\n/** Create a CrossTabDataBus backed by a plain WebSocket transport.\n * Cross-tab clustering (owner dedup, sticky routes, failover) works identically\n * to the Centrifuge backend \u2014 only the transport I/O differs. */\nexport function createWebSocketDataBus<TData = unknown>(\n options: CreateWebSocketDataBusOptions<TData>\n): CrossTabDataBus<WebSocketDataBusConfig, TData> {\n const { clusterKey, connection, ...dataBusOptions } = options;\n return new CrossTabDataBus({\n ...dataBusOptions,\n autoStart: true,\n clusterKey: clusterKey ?? connection.url,\n initialConfig: connection,\n transport: new WebSocketTransport<TData>(connection)\n });\n}\n\n/** Re-export for convenience: the status type used by the transport. */\nexport type { WorkerStatus };\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BO,SAAS,iCACd,SACiC;AACjC,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAW,OAAM,IAAI,MAAM,+CAA+C;AAC/E,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,YAAY;AAClB,QAAM,cAAc,QAAQ;AAC5B,QAAM,gBAAgB,QAAQ,iBAAiB,eAAe;AAC9D,QAAM,cAAc,QAAQ;AAC5B,sBAAoB,aAAa;AACjC,MAAI,gBAAgB,OAAW,4BAA2B,aAAa,aAAa;AACpF,4BAA0B,aAAa,aAAa;AACpD,MAAI,YAAyC;AAC7C,QAAM,aAAa,CAAC,OAA0B;AAC5C,QAAI,WAAW;AACb,WAAK,UAAU,KAAK,aAAW;AAC7B,YAAI,YAAY,IAAI;AAClB,kBAAQ,MAAM;AACd,sBAAY;AAAA,QACd;AAAA,MACF,GAAG,MAAM,MAAS;AAAA,IACpB;AAAA,EACF;AAYA,QAAM,UAID,CAAC;AACN,MAAI,WAAW;AAEf,QAAM,QAAQ,YAA2B;AACvC,QAAI,SAAU;AACd,eAAW;AACX,QAAI;AAIF,YAAM,QAAQ,QAAQ;AACtB,aAAO,QAAQ,SAAS,GAAG;AACzB,cAAM,OAAO,QAAQ,CAAC,EAAG;AACzB,YAAI,KAAK,SAAS,SAAS;AAEzB,gBAAM,SAAkC,CAAC;AACzC,gBAAM,UAA4E,CAAC;AACnF,iBAAO,QAAQ,SAAS,GAAG;AAC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GAC5C,eAAe,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAShD;AAED,wEAAwE;AACxE,YAAY,EAAE,YAAY,EAAE,CAAC"}
package/docs/api.md CHANGED
@@ -56,7 +56,7 @@ Creates a DataBus. When `initialConfig` is provided, it starts automatically by
56
56
  start(config: TConfig): Promise<void>
57
57
  ```
58
58
 
59
- Starts cluster coordination and transport. The first call actually starts the transport; concurrent calls during an in-flight open share the same start Promise without creating a duplicate transport. A call made on a healthy started instance is an immediate no-op. If the transport is down, `start()` acts as an explicit manual recovery: it preserves the cluster, subscriptions, and replay buffers, resets the failure/recovery ledger, and reopens the transport. If an explicit `stop()` is still settling, `start()` queues one fresh start behind that cleanup and returns a Promise that settles with the restart. That queued restart belongs to the latest lifecycle intent: a `stop()` arriving before it can run cancels it (resolving the queued start Promise without opening a transport), and a `start()` issued after that cancellation queues a fresh restart. After `stop()` has completed, `start()` can be called normally to restart.
59
+ Starts cluster coordination and transport. The first call actually starts the transport; concurrent calls during an in-flight open share the same start Promise without creating a duplicate transport. A call made on a healthy started instance is an immediate no-op. If the transport is down, `start()` acts as an explicit manual recovery: it preserves the cluster, subscriptions, and replay buffers, resets the failure/recovery ledger, and reopens the transport. If an explicit `stop()` is still settling, `start()` queues one fresh start behind that cleanup and returns a Promise that settles with the restart. That queued restart belongs to the latest lifecycle intent: a `stop()` arriving before it can run cancels it (resolving the queued start Promise without opening a transport), and a `start()` issued after that cancellation queues a fresh restart. After `stop()` has completed, `start()` can be called normally to restart. When an open fails, its cleanup and lifecycle gate settle before the startup-failure `onError` handlers run, so a `start()` retry issued synchronously from that callback begins a fresh attempt after the failed transport cleanup instead of returning the rejecting promise. A transport that reports `error` synchronously while `start()` is still in flight follows the same contract for both notifications: the internal status is updated immediately, but the user-facing `onStatus('error')` callback is deferred until `openTransport()` has completed cleanup, installed the failed transport's stop gate, recorded the failure, and cleared `startPromise`. A `start()` retry from that callback or from the subsequent startup-failure `onError` callback therefore queues a fresh lifecycle after cleanup. If the retry succeeds, it opens a new failure ledger and the original opening's rejection does not repopulate it.
60
60
 
61
61
  ### `ready()`
62
62
 
@@ -70,7 +70,7 @@ While an explicit `stop()` is settling, `ready()` rejects unless a `start()` has
70
70
 
71
71
  If a later `stop()` cancels that queued restart, the queued `start()` Promise still resolves without opening a transport, but `ready()` rejects with a lifecycle error rather than reporting a stopped bus as ready.
72
72
 
73
- While the tab is BFCache-suspended (after `pagehide` and before `pageshow`), `ready()` rejects with a suspended-state error. The suspend path reuses `startPromise` as the asynchronous `transport.stop()` gate, so returning it would resolve readiness against a deliberately stopped transport. `pageshow` or an explicit `start()` clears the suspension and installs a real reopen promise, after which `ready()` resolves normally once the transport is ready.
73
+ While the tab is BFCache-suspended (after `pagehide` and before `pageshow`), `ready()` rejects with a suspended-state error. The suspend path reuses `startPromise` as the asynchronous `transport.stop()` gate, so returning it would resolve readiness against a deliberately stopped transport. `pageshow` or an explicit `start()` clears the suspension and installs a real reopen promise, after which `ready()` resolves normally once the transport is ready. Both resume paths also restart the coordination plane: `pagehide` pauses the cluster independently of the transport (closing its channel, stopping its heartbeat, and releasing route assignments), so an explicit `start()` resumes the cluster too — otherwise the bus would report a healthy transport while cross-tab deliveries were still being discarded.
74
74
 
75
75
  If that queued restart fails during transport startup, `ready()` rejects with the underlying startup error even when no `initialConfig` was supplied. The failure is retained for explicit recovery rather than being replaced by the generic missing-configuration error.
76
76
 
@@ -210,7 +210,7 @@ Compact readiness verdict for dashboards, readiness probes, and support bundles.
210
210
 
211
211
  ```ts
212
212
  interface DataBusHealthSummary {
213
- healthy: boolean; // started, not suspended, live transport status is 'connected'
213
+ healthy: boolean; // started, not stopping/suspended, live transport status is 'connected'
214
214
  state: 'stopped' | 'starting' | 'healthy' | 'recovering' | 'suspended' | 'degraded';
215
215
  status: WorkerStatus;
216
216
  sdkVersion: string;
@@ -225,7 +225,7 @@ interface DataBusHealthSummary {
225
225
  }
226
226
  ```
227
227
 
228
- `state` semantics: `stopped` (not started), `starting` (initial open in flight), `recovering` (automatic transport recovery in progress), `suspended` (tab hidden, resumes on pageshow), `degraded` (automatic recovery exhausted — call `start()` or subscribe again to recover manually), `healthy`. Calling `start()` again while degraded keeps the cluster, subscriptions, and replay buffers intact, resets the failure/recovery ledger, and reopens the transport; subscribe and publish also trigger the same reopen path. `lastFailure` is a unified ledger across all failure sources and resets on every explicit `start()`. The `healthy` verdict follows the live transport status; `transport.ready` is diagnostic and can remain `false` for the brief window between a transport reporting `connected` and its `start()` Promise settling, during which operations are queued behind that in-flight start rather than dropped.
228
+ `state` semantics: `stopped` (not started, or an explicit `stop()` is still tearing down), `starting` (initial open in flight), `recovering` (automatic transport recovery in progress), `suspended` (tab hidden, resumes on pageshow), `degraded` (automatic recovery exhausted — call `start()` or subscribe again to recover manually), `healthy`. Calling `start()` again while degraded keeps the cluster, subscriptions, and replay buffers intact, resets the failure/recovery ledger, and reopens the transport; subscribe and publish also trigger the same reopen path. `lastFailure` is a unified ledger across all failure sources and resets on every explicit `start()`. The `healthy` verdict follows the live transport status, except that an in-flight `stop()` always reads as `stopped` because every other lifecycle API (`publish()`, `subscribe()`, `ready()`) already rejects during teardown; `transport.ready` is diagnostic and can remain `false` for the brief window between a transport reporting `connected` and its `start()` Promise settling, during which operations are queued behind that in-flight start rather than dropped.
229
229
 
230
230
  ### `getRecoveryStats()` / `getPersistenceStats()`
231
231
 
@@ -536,10 +536,10 @@ This process prevents overlap during graceful owner handoff while retaining avai
536
536
  These invariants are pinned by regression tests (see `tests/stability.test.ts` and `tests/replay-persistence.test.ts`) and must hold through future refactors:
537
537
 
538
538
  - **Handoff ACK validity.** A `ROUTE_RELEASED` is accepted only when the route still points at the receiver, the release comes from the recorded `handoffFromWorkerId`, and the ACK generation is at least as new as the stored route generation. Replayed ACKs from an earlier handoff round (e.g. an a↔b ping-pong) carry an older generation and are dropped.
539
- - **Replay persistence cleanup ordering.** A batched persistence flush queued behind the current task is filtered against the cleanup that wins the race: `unsubscribe` and `clearReplayTopic` drop the topic's pending entries, `clearReplayBefore` drops entries older than the cutoff. Cleared history is never re-appended by an in-flight flush.
539
+ - **Replay persistence cleanup ordering.** A batched persistence flush queued behind the current task is filtered against the cleanup that wins the race: `unsubscribe` and `clearReplayTopic` drop the topic's pending entries, `clearReplayBefore` drops entries older than the cutoff, and `suspend()`/`stop()` discard the whole queued batch before it can start under the next lifecycle generation. Cleared or stopped-session history is never re-appended by an in-flight flush.
540
540
  - **Storage write recovery.** Coalesced writes retry with exponential backoff (50 ms → 1.6 s cap). A structurally failing key is dropped after 5 attempts (with a `console.warn`) without permanently blocking other queued keys, and the backoff delay resets once the queue fully drains or `clear()` cancels the retries.
541
541
  - **Transport recovery budget.** Automatic recovery is paced by a cooldown, bounded by `recovery.maxAttempts`, and reports `exhausted` when the budget is spent. A successful reopen resets the attempt counter and the exhausted flag; explicit `subscribe` on a down transport can still recover manually. Scheduling alone does not reopen a connection: the backend must release the invalid connection before a retry can create or re-open one. `WebSocketTransport` resolves `start()` only after the socket opens, rejects a pre-open `error`/`close` or a `connectTimeoutMs` expiry, marks the socket active only until error/close, and drops the stale reference before the next `start()` invokes the factory, so late callbacks from the superseded socket are ignored.
542
- - **BFCache suspension.** Hiding the tab stops the transport, bumps the persistence-retry generation (cancelling in-flight persistence retries without surfacing errors), and gates dispatch; pageshow reopens the transport and re-establishes subscriptions exactly once per cycle.
542
+ - **BFCache suspension.** Hiding the tab stops the transport, bumps the persistence-retry generation (cancelling in-flight persistence retries without surfacing errors), pauses trace metrics and periodic dedup/replay cleanup, and gates dispatch; `pageshow` or an explicit `start()` reopens the transport, resumes those periodic resources, and re-establishes subscriptions exactly once per cycle.
543
543
  - **Handoff channel close ordering.** `pause()` defers the physical `channel.close()` by one task. Closing synchronously would discard messages still queued for delivery — including the handoff's `ROUTE_RELEASED` — stranding the handoff target with an unconfirmed route.
544
544
  - **Stranded-handoff recovery.** If the previous owner is gone and its `ROUTE_RELEASED` never arrives (dropped channel message under load, or a crash between the route write and the ACK), the reconcile loop re-elects a live owner once the unconfirmed handoff has been stuck longer than a worker TTL (10 s default): the route is rewritten with a fresh generation and the handoff marker cleared, so the normal confirmation path completes (pinned by regression). The age gate matters — a fresh unconfirmed route may simply be waiting out its confirmation flush — and while the previous owner is still alive the new owner keeps waiting, so the strict handoff keeps its no-overlap guarantee.
545
545
  - **Loss and recovery matrix.** Each coordination message has a bounded recovery path: a lost `CONTROL/SUBSCRIBE` is re-sent by the heartbeat reconcile for any route still lacking `confirmedAt`; a lost `REGISTRY` nudge costs at most one heartbeat interval (3 s default) because every tick reconciles anyway; a lost `ROUTE_RELEASED` is recovered by reconcile re-election once the previous owner is gone and the handoff has been stuck longer than a worker TTL (see the stranded-handoff invariant above, pinned by regression); publications dropped during a transport disconnect window are the one documented unrecoverable loss (transport contract). The storage-event fallback channel guarantees value-change delivery via a monotonic sequence in the envelope, and a dropped dispatch recovers through the same reconcile loop.
@@ -566,7 +566,7 @@ A runtime `error` intentionally keeps `transportReady` true: the flag records th
566
566
  | `suspended` | `boolean` | Tab is hidden; transport is intentionally stopped |
567
567
  | `transportReady` | `boolean` | Transport opened successfully for the current session; retained through a runtime `error` so `ready()` keeps tracking the installed transport (pending operations are held by the recovery gate, not by this flag) |
568
568
  | `startPromise` | `Promise \| null` | Gate for concurrent `start()` calls; cleared after settle |
569
- | `stopPromise` | `Promise \| null` | Shared gate for an explicit `stop()` and any restart queued behind it |
569
+ | `stopPromise` | `Promise \| null` | Shared gate for an explicit `stop()` and any restart queued behind it; reused only while `stopping` is true, because the field is cleared one microtask after `performStop()` settles |
570
570
  | `queuedStart` | `Promise \| null` | One fresh start waiting for an in-flight explicit stop to settle |
571
571
  | `queuedStartToken` | `number` | Monotonic token issued to each queued restart so a cancellation cannot be mistaken for a later one |
572
572
  | `canceledQueuedStartToken` | `number` | Highest queued-restart token invalidated by `stop()`; a continuation at or below it resolves without opening |
@@ -602,13 +602,15 @@ A runtime `error` intentionally keeps `transportReady` true: the flag records th
602
602
  **Key behaviors:**
603
603
 
604
604
  - **Concurrent start**: If `start()` is called while a real transport opening is in flight, the second call returns the same promise. Only one transport open is in flight at a time. A page-hide stop can also occupy `startPromise`; `start()` recognizes that `startPromise === pendingStop` and queues a reopen behind the stop rather than returning the cleanup promise as if it were a successful start.
605
- - **Start during explicit stop**: `stop()` publishes a shared `stopPromise` for concurrent callers. A `start()` received while it is settling stores one `queuedStart`; after the stop's `finally` clears the lifecycle state, the queued start performs a fresh lifecycle with the new config. Repeated calls during that window share both the stop and queued-start promises.
605
+ - **Failure notification ordering**: A transport can report `error` synchronously while its `start()` is still in flight. `openTransport()` updates the internal status immediately, but defers the user-facing `onStatus('error')` notification until it has cleared `transportReady`, torn down an initial-start cluster, installed the failed transport's stop gate, recorded the failure, and cleared `startPromise`. The startup-failure `onError` notification follows that cleanup as well. A synchronous `start()` retry from either callback therefore opens a fresh attempt after the stop gate instead of sharing the rejected promise. The retry resets the failure ledger, and the superseded opening's rejection is consumed by its own lifecycle cleanup so it cannot be recorded again after the retry succeeds. Ordinary concurrent starts during a genuinely in-flight open still share one promise.
606
+ - **Start during explicit stop**: `stop()` publishes a shared `stopPromise` for concurrent callers. A `start()` received while it is settling stores one `queuedStart`; after the stop's `finally` clears the lifecycle state, the queued start performs a fresh lifecycle with the new config. Repeated calls during that window share both the stop and queued-start promises. The shared gate is reused only while `stopping` is true: `performStop()` flips `stopping` back to false inside its `finally`, but `stopPromise` is cleared one microtask later, so a `start()`/`stop()` issued in that gap must fall through to a fresh teardown instead of resolving against the already-settled gate and leaving the restarted bus running.
606
607
  - **Stop cancels a queued restart**: The queued continuation is chained to the stop promise and cannot be un-scheduled, so a second `stop()` before it runs invalidates it instead. Each queued restart carries a monotonic token; `stop()` records the current token and releases the single queue slot, and the continuation resolves without opening a transport when its own token is no longer newer. The queued `start()` promise retains that resolve-on-cancellation contract, while a separate readiness view makes `ready()` reject for the canceled intent. Because a later `start()` issues a higher token, `stop → start → stop → start` still ends running while `stop → start → stop` ends stopped with no extra transport open.
607
608
  - **Stop-time publication rejection**: Once `stop()` sets `stopping`, new `publish()` and non-empty `publishBatch()` calls cannot reach a transport. They surface an error through `onError` rather than letting `runTransport()` return silently; empty batches stay no-ops. A publication already queued behind an in-flight open is canceled by the stop (latest intent wins), while page-hide suspension keeps its documented drop-without-defer semantics.
608
609
  - **Stop-time lifecycle-operation rejection**: The `stopping` gate also covers `subscribe()` and `ready()`. A late `subscribe()` is reported through `onError` and returns a no-op cleanup, preventing a handler from being erased by `topicHandlers.clear()` or leaking into a later restart without its handler. `ready()` rejects instead of resolving against the stopping transport. If `start()` has already queued a restart behind the stop, `ready()` returns that queued-start promise because it is the newest lifecycle intent.
610
+ - **Stop-time health verdict**: `getHealthSummary()` reports `state: 'stopped'` / `healthy: false` for the whole teardown, not only after `started` flips to false. The transport can keep reporting `connected` until its asynchronous `stop()` settles, so deriving health from the live status alone produced a snapshot that claimed the bus was usable while `publish()`, `subscribe()`, and `ready()` all already rejected. `started` still reflects the real lifecycle flag, and `transport` still reports the live status/`ready` values as diagnostics; a restart queued behind the stop reads as `starting` once the queued start owns the lifecycle.
609
611
  - **Queued-restart failure retention**: A queued restart that fails during transport startup clears `started` but retains its actual error for later `ready()` calls. Without `initialConfig`, those calls reject with the startup failure instead of the generic configuration error, while an explicit `start(config)` remains a clean manual retry with a fresh failure ledger.
610
- - **Suspend during start**: If `pagehide` fires while `openTransport` is in flight, `suspendTransport()` sets `suspended = true` and chains a `transport.stop()` after the in-flight start. The `openTransport` catch path detects `suspended` and abandons the open without treating it as a failure.
611
- - **Readiness during suspend**: A suspended bus sets `suspended = true` and reuses `startPromise`/`pendingStop` for the chained `transport.stop()`, so that promise proves cleanup completed rather than readiness. `ready()` checks `suspended` after the `stopping` gate and rejects with a suspended-state error instead of returning the stop gate. `pageshow`/`reopenTransport()` and an explicit `start()` clear the flag and install a real reopen promise, so `ready()` follows the newest lifecycle intent. `getHealthSummary()` already reported `{ healthy: false, state: 'suspended' }`; rejection keeps that verdict consistent with `ready()`.
612
+ - **Suspend during start**: If `pagehide` fires while `openTransport` is in flight, `suspendTransport()` sets `suspended = true` and chains a `transport.stop()` after the in-flight start. The `openTransport` catch path detects `suspended` and abandons the open without treating it as a failure. Repeated hide/show rounds that interleave a queued resume opening with an older stop gate install a fresh serial stop gate and restore the `startPromise === pendingStop` invariant, so the next `pageshow` reopens instead of reusing a superseded opening and leaving the bus suspended forever.
613
+ - **Readiness during suspend**: A suspended bus sets `suspended = true` and reuses `startPromise`/`pendingStop` for the chained `transport.stop()`, so that promise proves cleanup completed rather than readiness. `ready()` checks `suspended` after the `stopping` gate and rejects with a suspended-state error instead of returning the stop gate. `pageshow`/`reopenTransport()` and an explicit `start()` clear the flag and install a real reopen promise, so `ready()` follows the newest lifecycle intent. Because `pagehide` pauses the *cluster* independently of the transport, an explicit `start()` that leaves suspension resumes the cluster too; without that, the bus would report a healthy transport while its channel listener, heartbeat, and route assignments stayed dormant until the next `pageshow`, and every incoming publication would be discarded by `isAssigned()` against the cleared assignment map. `getHealthSummary()` already reported `{ healthy: false, state: 'suspended' }`; rejection keeps that verdict consistent with `ready()`.
612
614
  - **Superseded open invalidation**: Every fresh start, reopen, suspend, and stop advances `lifecycleEpoch`. An open captures its epoch, ignores stale status/message/error callbacks, and neither marks the transport ready nor performs failure cleanup after a newer transition owns the lifecycle. `stop()` therefore waits for pending opens/reopens and prevents a superseded open from becoming ready after the stop completes.
613
615
  - **Recovery cooldown**: When the transport reports `error` while `started` is true and `stopping` is false, `updateStatus` schedules an automatic `reopenTransport()` after `RECOVERY_COOLDOWN_MS` (1000 ms). A second error within the cooldown window is suppressed to prevent a tight retry loop.
614
616
  - **Transport recovery gate**: Scheduling a reopen also arms a recovery gate, so `subscribe` / `publish` issued during the cooldown cannot reach the failed connection; they are released after the reopen succeeds. The gate deliberately survives a failed automatic attempt: the next explicit operation starts an immediate on-demand reopen instead of waiting for the next paced attempt, and parked operations flush behind that success. Exhausting `recovery.maxAttempts`, or superseding the wait with `stop()` / `suspendTransport()`, releases the gate so the explicit-retry path and the documented suspend-drop semantics are preserved. A runtime `error` does not clear `transportReady`, because clearing it would let caller traffic reopen the transport outside the cooldown and report readiness against a connection that is not carrying data.
@@ -47,7 +47,7 @@ and regression-locked:
47
47
  | Invariant | Area | Regressed guarantee |
48
48
  |---|---|---|
49
49
  | Handoff ACK validity | coordination | `ROUTE_RELEASED` is honored only when the route still points to the receiver, the release matches `handoffFromWorkerId`, and the ACK generation is at least as new as the stored route — stale ACKs from an earlier a↔b ping-pong are dropped |
50
- | Replay persistence cleanup ordering | durability | Queued batch flushes are filtered against the winning cleanup (`unsubscribe`/`clearReplayTopic` drop the topic's pending entries, `clearReplayBefore` drops entries older than the cutoff); cleared history is never re-appended by an in-flight flush |
50
+ | Replay persistence cleanup ordering | durability | Queued batch flushes are filtered against the winning cleanup (`unsubscribe`/`clearReplayTopic` drop the topic's pending entries, `clearReplayBefore` drops entries older than the cutoff, and `suspend()`/`stop()` discard the queued batch); cleared or stopped-session history is never re-appended by an in-flight flush |
51
51
  | Storage write recovery | coordination | Coalesced writes retry with exponential backoff (50 ms → 1.6 s cap); a structurally failing key is dropped after 5 attempts (with `console.warn`) without blocking other queued keys; backoff resets once the queue drains or `clear()` cancels the retries |
52
52
  | Transport recovery budget | lifecycle | Auto-recovery is paced by a cooldown, bounded by `recovery.maxAttempts`, and reports `exhausted` when the budget is spent; a successful reopen resets attempt + exhausted, and an explicit `subscribe` on a down transport can still recover manually |
53
53
  | BFCache suspension | lifecycle | Hiding the tab stops the transport and silently cancels in-flight persistence retries; pageshow reopens the transport and re-establishes subscriptions exactly once per cycle |
@@ -54,7 +54,7 @@ When `replay.retentionMs` is enabled, automatic durable cleanup is coalesced dur
54
54
 
55
55
  `replay.retentionSweepMs` optionally schedules the same cleanup on a periodic interval. It is useful for quiet topics whose old durable records should still expire; it requires `retentionMs` and a persistence adapter with `clearBefore()`. The timer follows visibility and lifecycle transitions and is disabled by default.
56
56
 
57
- `replay.persistenceRetry` optionally controls transient persistence recovery. `maxAttempts` is the total number of attempts (default `1`), and `backoffMs` is the initial delay before retry (default `50`). Delays grow exponentially and are capped; final failures retain the existing `onError` and reliability behavior.
57
+ `replay.persistenceRetry` optionally controls transient persistence recovery. `maxAttempts` is the total number of attempts (default `1`), and `backoffMs` is the initial delay before retry (default `50`). Delays grow exponentially and are capped; final failures retain the existing `onError` and reliability behavior. A batch flush still queued in a microtask when the bus suspends or stops is discarded with its lifecycle generation rather than starting a durable append after teardown.
58
58
 
59
59
  ### Replay Options
60
60
 
package/docs/roadmap.md CHANGED
@@ -1,6 +1,23 @@
1
1
  # Roadmap
2
2
 
3
- 0.20.87 is the current development line. The project is intentionally continuing through reliability-focused minor releases before a 1.0.0 stability freeze.
3
+ 0.20.89 is released. The project is intentionally continuing through reliability-focused releases before a 1.0.0 stability freeze.
4
+
5
+ ## 0.20.89 delivered scope
6
+
7
+ The line continues the async-callback isolation audit: every fix below binds a callback, queued microtask, or promise continuation to the lifecycle generation that created it, so a superseded session cannot write into its replacement.
8
+
9
+ - Async teardown and restart boundaries: a settled `stop()` gate can no longer swallow a later teardown (`stop → start → stop` now ends stopped), and `getHealthSummary()` reports `state: 'stopped'` for a stopping bus instead of contradicting the `publish()` / `subscribe()` / `ready()` rejections it is already issuing.
10
+ - Replay persistence isolation: microtask-queued batch flushes and a queued retention cleanup are discarded once `suspend()` / `stop()` supersedes their generation, so stopped-session history cannot be appended to the durable store.
11
+ - Durable hydration cancellation: a `load()` that resolves after `suspend()` or `stop()` can no longer append into buffers teardown has already cleared, and is reported as a lifecycle cancellation rather than a persistence failure.
12
+ - Trace session isolation: a stopped trace reporter stays inert — queued `asyncSink` events from the old session are dropped and the stopped flag is cleared by an explicit restart so its lifecycle `start` is emitted again.
13
+ - Transport and Worker callback isolation: Centrifuge credential-provider results are bound to the exact Worker/port/session that requested them, async `CentrifugeSession` client/subscription callbacks are ignored after `STOP` or reinit, and a `Blob` binary frame from a replaced WebSocket connection can no longer be dispatched as if it belonged to the new one.
14
+ - Regression safety net: the seeded lifecycle fuzzer now covers 1_500 interleavings and asserts that a sequence whose last explicit intent was `stop()` settles in `state: 'stopped'` with no live transport.
15
+
16
+ ## 0.20.88 delivered scope
17
+
18
+ - Startup-failure recovery is now re-entrant. A transport that reports `error` synchronously while its initial `openTransport()` is still settling can be retried from either the `onStatus('error')` or `onError` callback; the failed open finishes cleanup first, the retry starts a fresh lifecycle, and the stale rejection cannot repopulate the reset failure ledger.
19
+ - Repeated BFCache `pagehide`/`pageshow` cycles during an in-flight initial open no longer strand the bus in a permanently suspended state. Suspend reuses the existing stop gate only when it still represents the current lifecycle, otherwise it installs a fresh serial stop so the next resume actually reopens the transport.
20
+ - Explicit `start()` is now a complete resume path after BFCache suspension: it restores cross-tab coordination as well as the transport, and restarts trace metrics, dedup expiry, and replay retention work that `pagehide` had paused.
4
21
 
5
22
  ## 0.20.87 delivered scope
6
23
 
package/docs/zh/api.md CHANGED
@@ -56,7 +56,7 @@ new CrossTabDataBus<TConfig, TData>(options)
56
56
  start(config: TConfig): Promise<void>
57
57
  ```
58
58
 
59
- 启动集群协调和 transport。首次调用真正启动 transport;打开过程尚未结束时,并发调用共享同一个启动 Promise,不重复创建 transport。对健康且已启动的实例调用是立即 resolve 的空操作。若 transport 已断开,`start()` 作为显式手动恢复:保留 cluster、订阅和 replay 缓冲区,重置失败/恢复账本并重新打开 transport。若显式 `stop()` 尚未完成,`start()` 会在清理之后排队一次全新启动,并返回随重启完成而 settle 的 Promise。该排队重启归属于最近一次生命周期意图:若它在真正执行前又收到 `stop()`,则会被取消(排队 start 的 Promise resolve,但不会打开 transport);取消之后再调用 `start()` 会以更高令牌重新排队。`stop()` 完成后也可正常再次调用 `start()` 重启。
59
+ 启动集群协调和 transport。首次调用真正启动 transport;打开过程尚未结束时,并发调用共享同一个启动 Promise,不重复创建 transport。对健康且已启动的实例调用是立即 resolve 的空操作。若 transport 已断开,`start()` 作为显式手动恢复:保留 cluster、订阅和 replay 缓冲区,重置失败/恢复账本并重新打开 transport。若显式 `stop()` 尚未完成,`start()` 会在清理之后排队一次全新启动,并返回随重启完成而 settle 的 Promise。该排队重启归属于最近一次生命周期意图:若它在真正执行前又收到 `stop()`,则会被取消(排队 start 的 Promise resolve,但不会打开 transport);取消之后再调用 `start()` 会以更高令牌重新排队。`stop()` 完成后也可正常再次调用 `start()` 重启。open 失败时,清理和生命周期 gate 会先 settle,再调用启动失败的 `onError` handler;因此在该回调中同步调用 `start()` 重试会在失败 transport 清理完成后开启一次全新尝试,而不是返回同一个已拒绝的 Promise。transport 在 `start()` 仍在飞行时同步上报 `error` 时,两类通知遵循同一契约:内部状态会立即更新,但用户可见的 `onStatus('error')` 会延迟到 `openTransport()` 完成清理、安装失败 transport 的 stop gate、记录失败并清除 `startPromise` 之后。此时从该状态回调或随后启动失败的 `onError` 回调中同步调用 `start()`,都会在清理完成后排队一次全新生命周期;若重试成功,它会开启新的失败账本,原 opening 的 rejection 不会再次写回。
60
60
 
61
61
  ### `ready()`
62
62
 
@@ -70,7 +70,7 @@ ready(): Promise<void>
70
70
 
71
71
  若后续 `stop()` 取消了该排队重启,排队 `start()` Promise 仍按既定语义 resolve 且不会打开 transport,但 `ready()` 会以生命周期错误 reject,而不会把已停止的 bus 报告为 ready。
72
72
 
73
- Tab 处于 BFCache 挂起态时(`pagehide` 之后、`pageshow` 之前),`ready()` 会以挂起态错误 reject。挂起路径会把 `startPromise` 复用为异步 `transport.stop()` 的 gate,若直接返回它,就会针对一个被有意停止的 transport 报告 ready。`pageshow` 或显式 `start()` 会清除挂起标记并安装真正的重开 Promise,此后 `ready()` 会在 transport 就绪后正常 resolve
73
+ Tab 处于 BFCache 挂起态时(`pagehide` 之后、`pageshow` 之前),`ready()` 会以挂起态错误 reject。挂起路径会把 `startPromise` 复用为异步 `transport.stop()` 的 gate,若直接返回它,就会针对一个被有意停止的 transport 报告 ready。`pageshow` 或显式 `start()` 会清除挂起标记并安装真正的重开 Promise,此后 `ready()` 会在 transport 就绪后正常 resolve。两条恢复路径都会同时重启协调面:`pagehide` 会独立于 transport 暂停 cluster(关闭 channel、停止 heartbeat 并释放 route 分配),因此显式 `start()` 也会一并恢复 cluster——否则 bus 会报告 transport 健康,而跨 Tab 投递仍被丢弃。
74
74
 
75
75
  若该排队重启在 transport 启动阶段失败,即使未传入 `initialConfig`,`ready()` 也会以底层启动错误 reject。该失败会保留给显式恢复,而不会被通用的「缺少配置」错误掩盖。
76
76
 
@@ -208,7 +208,7 @@ getHealthSummary(): DataBusHealthSummary
208
208
 
209
209
  ```ts
210
210
  interface DataBusHealthSummary {
211
- healthy: boolean; // 已启动、未挂起、transport 实时状态为 connected
211
+ healthy: boolean; // 已启动、未在停止中、未挂起、transport 实时状态为 connected
212
212
  state: 'stopped' | 'starting' | 'healthy' | 'recovering' | 'suspended' | 'degraded';
213
213
  status: WorkerStatus;
214
214
  sdkVersion: string;
@@ -223,7 +223,7 @@ interface DataBusHealthSummary {
223
223
  }
224
224
  ```
225
225
 
226
- `state` 语义:`stopped`(未启动)、`starting`(首次连接进行中)、`recovering`(transport 自动恢复进行中)、`suspended`(Tab 隐藏,pageshow 后自动恢复)、`degraded`(自动恢复已耗尽,需要手动 `start()` 或重新 subscribe 触发恢复)、`healthy`。处于 degraded 时再次调用 `start()` 会保留 cluster、订阅和 replay 缓冲区,重置失败/恢复账本后重新打开 transport;subscribe 与 publish 也走同一恢复路径。`lastFailure` 是覆盖全部失败来源的统一账本,每次显式 `start()` 后重置。`healthy` 依据 transport 的实时状态判定;`transport.ready` 是诊断字段,在 transport 已报告 `connected`、但其 `start()` Promise 尚未 settle 的短暂窗口内可能仍为 `false`,此时操作会排队等待该在途 start,而不会丢失。
226
+ `state` 语义:`stopped`(未启动,或显式 `stop()` 仍在 teardown)、`starting`(首次连接进行中)、`recovering`(transport 自动恢复进行中)、`suspended`(Tab 隐藏,pageshow 后自动恢复)、`degraded`(自动恢复已耗尽,需要手动 `start()` 或重新 subscribe 触发恢复)、`healthy`。处于 degraded 时再次调用 `start()` 会保留 cluster、订阅和 replay 缓冲区,重置失败/恢复账本后重新打开 transport;subscribe 与 publish 也走同一恢复路径。`lastFailure` 是覆盖全部失败来源的统一账本,每次显式 `start()` 后重置。`healthy` 依据 transport 的实时状态判定,但当显式 `stop()` 仍在进行时一律报告 `stopped`:teardown 期间其余生命周期 API(`publish()`、`subscribe()`、`ready()`)已经拒绝操作,健康判定不能与之矛盾。`transport.ready` 是诊断字段,在 transport 已报告 `connected`、但其 `start()` Promise 尚未 settle 的短暂窗口内可能仍为 `false`,此时操作会排队等待该在途 start,而不会丢失。
227
227
 
228
228
  ### `getMetrics()`
229
229