cross-tab-worker-databus 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,21 @@
1
1
  import type { WorkerClusterOptions } from './cluster';
2
2
  import type { DataBusErrorHandler, DataBusMessageHandler, DataBusStatusHandler, DataBusTransport, WorkerStatus } from './types';
3
3
  import type { DataBusTraceOptions } from './trace';
4
+ import type { DataBusReplayPersistence } from './replay-persistence';
4
5
  /** Constructor options for {@link CrossTabDataBus}. Extends WorkerClusterOptions
5
6
  * (cluster coordination config) with the transport, initial connection config,
6
7
  * and trace options. */
7
8
  /** Replay (bounded local history) configuration. When present, the DataBus
8
- * keeps an in-memory ring buffer of the most recent dispatched publications
9
- * per topic, and `subscribe()` can deliver that history to late-joining
10
- * handlers. Buffers live in memory only — nothing is persisted. */
11
- export interface DataBusReplayOptions {
9
+ * keeps a bounded ring buffer of the most recent dispatched publications per
10
+ * topic, and `subscribe()` can deliver that history to late-joining handlers.
11
+ * Buffers live in memory by default; an optional persistence backend can make
12
+ * them durable. */
13
+ export interface DataBusReplayOptions<TData = unknown> {
12
14
  /** Maximum buffered publications per topic. Oldest entries are evicted
13
15
  * first. Default 100. */
14
16
  maxPerTopic?: number;
17
+ /** Optional durable history backend. Defaults to in-memory only. */
18
+ persistence?: DataBusReplayPersistence<TData>;
15
19
  }
16
20
  export interface CrossTabDataBusOptions<TConfig, TData> extends Omit<WorkerClusterOptions, 'handlers'> {
17
21
  transport: DataBusTransport<TConfig, TData>;
@@ -19,7 +23,7 @@ export interface CrossTabDataBusOptions<TConfig, TData> extends Omit<WorkerClust
19
23
  autoStart?: boolean;
20
24
  trace?: DataBusTraceOptions;
21
25
  /** Opt-in bounded per-topic history. Absent → no buffering, zero overhead. */
22
- replay?: DataBusReplayOptions;
26
+ replay?: DataBusReplayOptions<TData>;
23
27
  }
24
28
  /**
25
29
  * High-level cross-tab pub/sub client.
@@ -38,6 +42,8 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
38
42
  private readonly errorHandlers;
39
43
  private readonly replayBuffers;
40
44
  private readonly replayMaxPerTopic;
45
+ private readonly replayPersistence;
46
+ private readonly replayHydration;
41
47
  private readonly initialConfig;
42
48
  private readonly hasInitialConfig;
43
49
  private readonly trace;
@@ -117,6 +123,7 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
117
123
  /** Append a dispatched publication to the topic's replay ring buffer.
118
124
  * No-op when replay is disabled. */
119
125
  private recordReplay;
126
+ private hydrateReplay;
120
127
  /** Deliver buffered history to a newly-registered handler. For an exact
121
128
  * topic this is that topic's ring; for a wildcard subscription every
122
129
  * buffered topic matching the pattern contributes (in buffer insertion
@@ -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,MAAM,WAAW,CAAC;AAEtD,OAAO,KAAK,EACV,mBAAmB,EAEnB,qBAAqB,EACrB,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACb,MAAM,SAAS,CAAC;AAEjB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAcnD;;wBAEwB;AACxB;;;mEAGmE;AACnE,MAAM,WAAW,oBAAoB;IACnC;6BACyB;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,sBAAsB,CAAC,OAAO,EAAE,KAAK,CACpD,SAAQ,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC;IAC9C,SAAS,EAAE,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC5C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,oBAAoB,CAAC;CAC/B;AAED;;;;;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AI;IA4Bb;;;mFAG+E;IAC/E,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,qBAAqB,CAAC,KAAK,CAAC,GAAG,IAAI;IAWxE,oFAAoF;IACpF,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI;IAS3C,mHAAmH;IACnH,QAAQ,CAAC,OAAO,EAAE,oBAAoB,GAAG,MAAM,IAAI;IAUnD,+CAA+C;IAC/C,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,MAAM,IAAI;IAKjD,2CAA2C;IAC3C,SAAS,IAAI,YAAY;IAIzB;;mDAE+C;IAC/C,kBAAkB;IAIlB;;;OAGG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IA6B3B;;;;OAIG;IACH,OAAO,CAAC,sBAAsB;IAe9B;;yEAEqE;IACrE,OAAO,CAAC,QAAQ;IAWhB;wCACoC;IACpC,OAAO,CAAC,YAAY;YAcN,aAAa;IAmB3B;;;;qCAIiC;IACjC,OAAO,CAAC,aAAa;IAqBrB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAgCpB,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,iBAAiB;IASzB,8DAA8D;IAC9D,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,oBAAoB;IAM5B;;;;+CAI2C;IAC3C,OAAO,CAAC,cAAc;IAoBtB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAwBxB;qEACiE;IACjE,OAAO,CAAC,iBAAiB;IAMzB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAIvB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAiCvB;;;;OAIG;IACH,OAAO,CAAC,YAAY;IA6BpB;;;OAGG;IACH,OAAO,CAAC,aAAa;CAUtB"}
@@ -0,0 +1,13 @@
1
+ import type { DataBusMessage } from './types';
2
+ /** Optional persistence backend for replay history. */
3
+ export interface DataBusReplayPersistence<TData = unknown> {
4
+ load(): Promise<ReadonlyArray<DataBusMessage<TData>>>;
5
+ append(message: DataBusMessage<TData>): Promise<void>;
6
+ }
7
+ export interface IndexedDbReplayPersistenceOptions {
8
+ dbName?: string;
9
+ maxPerTopic: number;
10
+ }
11
+ /** Create a browser IndexedDB-backed replay store. */
12
+ export declare function createIndexedDbReplayPersistence<TData = unknown>(options: IndexedDbReplayPersistenceOptions): DataBusReplayPersistence<TData>;
13
+ //# sourceMappingURL=replay-persistence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-persistence.d.ts","sourceRoot":"","sources":["../../src/core/replay-persistence.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,uDAAuD;AACvD,MAAM,WAAW,wBAAwB,CAAC,KAAK,GAAG,OAAO;IACvD,IAAI,IAAI,OAAO,CAAC,aAAa,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IACtD,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvD;AAED,MAAM,WAAW,iCAAiC;IAChD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,sDAAsD;AACtD,wBAAgB,gCAAgC,CAAC,KAAK,GAAG,OAAO,EAC9D,OAAO,EAAE,iCAAiC,GACzC,wBAAwB,CAAC,KAAK,CAAC,CA6CjC"}
package/dist/index.d.ts CHANGED
@@ -10,6 +10,8 @@
10
10
  */
11
11
  export { CrossTabDataBus } from './core/data-bus';
12
12
  export type { CrossTabDataBusOptions, DataBusReplayOptions } from './core/data-bus';
13
+ export { createIndexedDbReplayPersistence } from './core/replay-persistence';
14
+ export type { DataBusReplayPersistence, IndexedDbReplayPersistenceOptions } from './core/replay-persistence';
13
15
  export type { DataBusCoordinationTraceEvent, DataBusErrorTraceEvent, DataBusLifecycleTraceEvent, DataBusMetricsTraceEvent, DataBusStatusTraceEvent, DataBusSubscriptionTraceEvent, DataBusTraceEvent, DataBusTraceMode, DataBusTraceOptions } from './core/trace';
14
16
  export { WorkerClusterRuntime } from './core/cluster';
15
17
  export type { WorkerClusterHandlers, WorkerClusterOptions, WorkerClusterSnapshot } from './core/cluster';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,YAAY,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACpF,YAAY,EACV,6BAA6B,EAC7B,sBAAsB,EACtB,0BAA0B,EAC1B,wBAAwB,EACxB,uBAAuB,EACvB,6BAA6B,EAC7B,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,EACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,YAAY,EACV,qBAAqB,EACrB,oBAAoB,EACpB,qBAAqB,EACtB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAChF,YAAY,EAAE,cAAc,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAC1F,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EACL,kBAAkB,EAClB,sBAAsB,EACvB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,6BAA6B,EAC7B,sBAAsB,EACtB,aAAa,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,EACL,0BAA0B,EAC1B,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,uBA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a,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC/D,OAAO,EACL,0BAA0B,EAC1B,cAAc,EACd,eAAe,EACf,mBAAmB,EACnB,uBAAuB,EACvB,qBAAqB,EACrB,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EACV,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,oBAAoB,EACpB,gBAAgB,EAChB,wBAAwB,EACxB,YAAY,EACZ,kBAAkB,EAClB,qBAAqB,EACrB,oBAAoB,EACpB,mBAAmB,EACnB,YAAY,EACZ,UAAU,EACV,WAAW,EACX,YAAY,EACb,MAAM,cAAc,CAAC"}
package/dist/index.js CHANGED
@@ -12,9 +12,57 @@ import {
12
12
  selectRebalanceTarget,
13
13
  selectWorkerBackend,
14
14
  topicMatchesPattern
15
- } from "./chunk-ZGQRELIV.js";
15
+ } from "./chunk-W7DAXK4D.js";
16
16
  import "./chunk-5WRI5ZAA.js";
17
17
 
18
+ // src/core/replay-persistence.ts
19
+ function createIndexedDbReplayPersistence(options) {
20
+ const indexedDb = globalThis.indexedDB;
21
+ if (!indexedDb) throw new Error("IndexedDB is unavailable in this environment.");
22
+ const dbName = options.dbName ?? "cross-tab-worker-databus";
23
+ const storeName = "replay";
24
+ const maxPerTopic = options.maxPerTopic;
25
+ if (!Number.isSafeInteger(maxPerTopic) || maxPerTopic <= 0) {
26
+ throw new TypeError(`maxPerTopic must be a positive safe integer, got ${String(maxPerTopic)}.`);
27
+ }
28
+ let dbPromise = null;
29
+ const open = () => {
30
+ if (dbPromise) return dbPromise;
31
+ dbPromise = new Promise((resolve, reject) => {
32
+ const request = indexedDb.open(dbName, 1);
33
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: "topic" });
34
+ request.onsuccess = () => resolve(request.result);
35
+ request.onerror = () => reject(request.error ?? new Error("Failed to open replay database."));
36
+ });
37
+ return dbPromise;
38
+ };
39
+ return {
40
+ async load() {
41
+ const db = await open();
42
+ return new Promise((resolve, reject) => {
43
+ const request = db.transaction(storeName, "readonly").objectStore(storeName).getAll();
44
+ request.onsuccess = () => resolve(request.result.flatMap((record) => record.messages));
45
+ request.onerror = () => reject(request.error ?? new Error("Failed to load replay history."));
46
+ });
47
+ },
48
+ async append(message) {
49
+ const db = await open();
50
+ await new Promise((resolve, reject) => {
51
+ const transaction = db.transaction(storeName, "readwrite");
52
+ const store = transaction.objectStore(storeName);
53
+ const request = store.get(message.topic);
54
+ request.onsuccess = () => {
55
+ const messages = (request.result?.messages ?? []).concat(message).slice(-maxPerTopic);
56
+ store.put({ topic: message.topic, messages });
57
+ };
58
+ request.onerror = () => reject(request.error ?? new Error("Failed to read replay history."));
59
+ transaction.oncomplete = () => resolve();
60
+ transaction.onerror = () => reject(transaction.error ?? new Error("Failed to persist replay history."));
61
+ });
62
+ }
63
+ };
64
+ }
65
+
18
66
  // src/websocket.ts
19
67
  var WS_OPEN = 1;
20
68
  var WebSocketTransport = class {
@@ -123,6 +171,7 @@ export {
123
171
  WebSocketTransport,
124
172
  WorkerClusterRuntime,
125
173
  createBrowserEnvironment,
174
+ createIndexedDbReplayPersistence,
126
175
  createOpaqueKey,
127
176
  createWebSocketDataBus,
128
177
  getOrCreateTabId,
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/websocket.ts"],
4
- "sourcesContent": ["/**\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 * - 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 type { CrossTabDataBusOptions } from './core/data-bus';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\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): 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}\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\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 private socket: WebSocketLike | null = null;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. A factory failure is\n * reported through `onStatus('error')` so the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket) return;\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('error');\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\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: 'subscribe', topic });\n }\n handlers.onStatus('connected');\n };\n socket.onclose = () => handlers.onStatus('disconnected');\n socket.onerror = () => handlers.onStatus('error');\n socket.onmessage = event => this.handleMessage(event.data);\n this.socket = socket;\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: '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: 'unsubscribe', topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown): MaybePromise<void> {\n this.sendFrame({ op: 'publish', topic, data });\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 this.socket = null;\n this.handlers = null;\n this.subscribedTopics.clear();\n socket?.close();\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 }): 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 /** 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 handleMessage(raw: unknown): void {\n let parsed: unknown;\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 frame = parsed as Record<string, unknown>;\n if (typeof frame.topic !== 'string') return;\n this.handlers?.onMessage({ topic: frame.topic, data: frame.data as 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": ";;;;;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UAAM,SAAS,KAAK;AACpB,SAAK,SAAS;AACd,SAAK,WAAW;AAChB,SAAK,iBAAiB,MAAM;AAC5B,YAAQ,MAAM;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKQ,UAAU,SAA8D;AAC9E,QAAI,KAAK,QAAQ,eAAe,SAAS;AACvC,WAAK,UAAU,QAAQ,IAAI,MAAM,mCAAmC,QAAQ,EAAE,UAAU,CAAC;AACzF;AAAA,IACF;AACA,SAAK,OAAO,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA,EAKQ,cAAc,KAAoB;AACxC,QAAI;AACJ,QAAI,OAAO,QAAQ,SAAU;AAC7B,QAAI;AACF,eAAS,KAAK,MAAM,GAAG;AAAA,IACzB,QAAQ;AACN,WAAK,UAAU,QAAQ,IAAI,MAAM,yCAAyC,CAAC;AAC3E;AAAA,IACF;AACA,QAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAC3C,UAAM,QAAQ;AACd,QAAI,OAAO,MAAM,UAAU,SAAU;AACrC,SAAK,UAAU,UAAU,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,KAAc,CAAC;AAAA,EAC5E;AACF;AAGA,SAAS,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;",
3
+ "sources": ["../src/core/replay-persistence.ts", "../src/websocket.ts"],
4
+ "sourcesContent": ["import type { DataBusMessage } from './types';\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}\n\nexport interface IndexedDbReplayPersistenceOptions {\n dbName?: string;\n maxPerTopic: 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 ?? 'cross-tab-worker-databus';\n const storeName = 'replay';\n const maxPerTopic = options.maxPerTopic;\n if (!Number.isSafeInteger(maxPerTopic) || maxPerTopic <= 0) {\n throw new TypeError(`maxPerTopic must be a positive safe integer, got ${String(maxPerTopic)}.`);\n }\n let dbPromise: Promise<IDBDatabase> | null = null;\n const open = (): Promise<IDBDatabase> => {\n if (dbPromise) return dbPromise;\n dbPromise = new Promise((resolve, reject) => {\n const request = indexedDb.open(dbName, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(storeName, { keyPath: 'topic' });\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error ?? new Error('Failed to open replay database.'));\n });\n return dbPromise;\n };\n return {\n async load() {\n const db = await open();\n return new Promise((resolve, reject) => {\n const request = db.transaction(storeName, 'readonly').objectStore(storeName).getAll();\n request.onsuccess = () => resolve(request.result.flatMap(record => record.messages as DataBusMessage<TData>[]));\n request.onerror = () => reject(request.error ?? new Error('Failed to load replay history.'));\n });\n },\n async append(message) {\n const db = await open();\n await new Promise<void>((resolve, reject) => {\n const transaction = db.transaction(storeName, 'readwrite');\n const store = transaction.objectStore(storeName);\n const request = store.get(message.topic);\n request.onsuccess = () => {\n const messages = ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(message).slice(-maxPerTopic);\n store.put({ topic: message.topic, messages });\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to read replay history.'));\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => reject(transaction.error ?? new Error('Failed to persist replay history.'));\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 * - 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 type { CrossTabDataBusOptions } from './core/data-bus';\nimport type {\n DataBusTransport,\n DataBusTransportHandlers,\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): 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}\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\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 private socket: WebSocketLike | null = null;\n private handlers: DataBusTransportHandlers<TData> | null = null;\n private readonly subscribedTopics = new Set<string>();\n\n constructor(private readonly connection: WebSocketDataBusConfig) {}\n\n /** Open the WebSocket and wire lifecycle listeners. A factory failure is\n * reported through `onStatus('error')` so the DataBus can recover. */\n start(config: WebSocketDataBusConfig, handlers: DataBusTransportHandlers<TData>): MaybePromise<void> {\n if (this.socket) return;\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('error');\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\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: 'subscribe', topic });\n }\n handlers.onStatus('connected');\n };\n socket.onclose = () => handlers.onStatus('disconnected');\n socket.onerror = () => handlers.onStatus('error');\n socket.onmessage = event => this.handleMessage(event.data);\n this.socket = socket;\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: '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: 'unsubscribe', topic });\n }\n\n /** Publish `data` to `topic` as a JSON frame. Requires an open socket. */\n publish(topic: string, data: unknown): MaybePromise<void> {\n this.sendFrame({ op: 'publish', topic, data });\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 this.socket = null;\n this.handlers = null;\n this.subscribedTopics.clear();\n socket?.close();\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 }): 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 /** 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 handleMessage(raw: unknown): void {\n let parsed: unknown;\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 frame = parsed as Record<string, unknown>;\n if (typeof frame.topic !== 'string') return;\n this.handlers?.onMessage({ topic: frame.topic, data: frame.data as 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": ";;;;;;;;;;;;;;;;;;AAcO,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,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,eAAe,GAAG;AAC1D,UAAM,IAAI,UAAU,oDAAoD,OAAO,WAAW,CAAC,GAAG;AAAA,EAChG;AACA,MAAI,YAAyC;AAC7C,QAAM,OAAO,MAA4B;AACvC,QAAI,UAAW,QAAO;AACtB,gBAAY,IAAI,QAAQ,CAAC,SAAS,WAAW;AAC3C,YAAM,UAAU,UAAU,KAAK,QAAQ,CAAC;AACxC,cAAQ,kBAAkB,MAAM,QAAQ,OAAO,kBAAkB,WAAW,EAAE,SAAS,QAAQ,CAAC;AAChG,cAAQ,YAAY,MAAM,QAAQ,QAAQ,MAAM;AAChD,cAAQ,UAAU,MAAM,OAAO,QAAQ,SAAS,IAAI,MAAM,iCAAiC,CAAC;AAAA,IAC9F,CAAC;AACD,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,MAAM,OAAO;AACX,YAAM,KAAK,MAAM,KAAK;AACtB,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,cAAM,UAAU,GAAG,YAAY,WAAW,UAAU,EAA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AAI,OAAO,QAAQ,SAAU;AAC7B,QAAI;AACF,eAAS,KAAK,MAAM,GAAG;AAAA,IACzB,QAAQ;AACN,WAAK,UAAU,QAAQ,IAAI,MAAM,yCAAyC,CAAC;AAC3E;AAAA,IACF;AACA,QAAI,CAAC,UAAU,OAAO,WAAW,SAAU;AAC3C,UAAM,QAAQ;AACd,QAAI,OAAO,MAAM,UAAU,SAAU;AACrC,SAAK,UAAU,UAAU,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,KAAc,CAAC;AAAA,EAC5E;AACF;AAGA,SAAS,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;",
6
6
  "names": []
7
7
  }
package/docs/README.md CHANGED
@@ -10,6 +10,7 @@
10
10
  | [API Reference](./api.md) | Public API, types, methods, return values, and behavior |
11
11
  | [Architecture](./architecture.md) | Worker cluster, routing, storage, migration, and degradation design |
12
12
  | [Capabilities Matrix](./capabilities.md) | Implemented, not implemented, and planned capabilities matrix |
13
+ | [Roadmap](./roadmap.md) | Release-oriented priorities and verification checklist |
13
14
  | [../examples/demo](../examples/demo) | Runnable multi-tab browser demo |
14
15
  | [../CHANGELOG.md](../CHANGELOG.md) | Version changelog |
15
16
 
@@ -19,4 +20,4 @@
19
20
  2. For production configuration, read [Configuration](./configuration.md).
20
21
  3. When developing wrappers or custom transports, read [API Reference](./api.md).
21
22
  4. When troubleshooting cross-tab behavior, read [Architecture](./architecture.md).
22
- 5. When evaluating current boundaries and future plans, read [Capabilities Matrix](./capabilities.md).
23
+ 5. When evaluating current boundaries and future plans, read [Capabilities Matrix](./capabilities.md).
package/docs/api.md CHANGED
@@ -80,7 +80,7 @@ Registers a local subscription and returns a cleanup function.
80
80
  - The current tab only leaves the topic after the last handler is released.
81
81
  - Subscriptions are automatically queued when the transport is not yet ready.
82
82
  - Wildcard subscriptions: a topic ending in `.*` (`chat.*`) matches any remainder, and `*` matches everything. The pattern is routed, owned, and transport-subscribed as a literal channel; publications tagged with a matching concrete topic (or with the pattern itself) are delivered to wildcard handlers. See `topicMatchesPattern` below.
83
- - Replay (opt-in): construct the bus with `replay: { maxPerTopic }` and pass `{ replay: true | n }` as the third `subscribe()` argument. `maxPerTopic` must be a positive safe integer. The new handler immediately receives the buffered history (up to `n`, capped by `maxPerTopic`, default 100) with `message.replayed: true`, so late joiners do not miss earlier publications. Only dispatched publications are buffered (a topic with no local subscriber drops them as unowned); buffers are in-memory and cleared when the last handler for the topic unsubscribes. Wildcard subscriptions replay across every buffered topic matching the pattern.
83
+ - Replay (opt-in): construct the bus with `replay: { maxPerTopic }` and pass `{ replay: true | n }` as the third `subscribe()` argument. `maxPerTopic` must be a positive safe integer. The new handler immediately receives the buffered history (up to `n`, capped by `maxPerTopic`, default 100) with `message.replayed: true`, so late joiners do not miss earlier publications. Only dispatched publications are buffered (a topic with no local subscriber drops them as unowned); buffers are in-memory and cleared when the last handler for the topic unsubscribes. Wildcard subscriptions replay across every buffered topic matching the pattern. For reload/BFCache persistence, pass an optional `persistence` created by `createIndexedDbReplayPersistence({ maxPerTopic })`; persistence is asynchronous and failures are reported through `onError` without breaking live delivery.
84
84
 
85
85
  ### `unsubscribe(topic, handler?)`
86
86
 
@@ -0,0 +1,18 @@
1
+ # Roadmap
2
+
3
+ 0.4.0 is released. The next work is intentionally organized as 0.5.0 candidates so performance and persistence changes can land together with their compatibility notes.
4
+
5
+ ## 0.5.0 candidates
6
+
7
+ 1. **Publish-path profiling and optimization** — use both `pnpm bench` and `pnpm bench:browser`; optimize only after isolating storage batching, routing, and UI/server overhead separately.
8
+ 2. **Persistent replay history** — add an IndexedDB adapter for replay history across page reloads and BFCache sessions, with explicit retention and schema-version controls. Keep in-memory replay as the zero-dependency default.
9
+ 3. **Vue composables** — provide a Vue 3 adapter mirroring the React hooks lifecycle and subscription semantics without making Vue a core dependency.
10
+ 4. **End-to-end binary demo** — exercise real `ArrayBuffer` frames through the WebSocket demo path; keep the existing base64 JSON fallback for servers that only support JSON.
11
+ 5. **Push CI browser gate** — run the existing Playwright suite on pushes when a Chrome environment is available; keep local/manual execution as the fallback for contributors.
12
+
13
+ ## Release checklist
14
+
15
+ - Update the `[Unreleased]` section and version date.
16
+ - Run `pnpm check`, `pnpm lint`, `pnpm test:e2e`, `pnpm bench`, and `pnpm bench:browser`.
17
+ - Run ESM/CJS package-consumption smoke tests from the packed tarball.
18
+ - Tag the release and verify the GitHub Release and npm `latest` dist-tag.
package/docs/zh/README.md CHANGED
@@ -12,6 +12,7 @@
12
12
  | [API 参考](./api.md) | 公共入口、类型、方法、返回值和行为 |
13
13
  | [架构说明](./architecture.md) | Worker 集群、路由、存储、迁移和降级设计 |
14
14
  | [能力矩阵](./capabilities.md) | 已实现、未实现和计划待实现的能力矩阵 |
15
+ | [路线图](./roadmap.md) | 面向版本的优先级与验证清单 |
15
16
  | [../..//examples/demo](../../examples/demo) | 可运行的多标签浏览器演示 |
16
17
  | [../../CHANGELOG.md](../../CHANGELOG.md) | 版本变更记录 |
17
18
 
@@ -21,4 +22,4 @@
21
22
  2. 生产配置阅读 [配置说明](./configuration.md)。
22
23
  3. 开发封装或自定义 transport 时阅读 [API 参考](./api.md)。
23
24
  4. 排查跨 Tab 行为时阅读 [架构说明](./architecture.md)。
24
- 5. 评估当前边界和后续计划时阅读 [能力矩阵](./capabilities.md)。
25
+ 5. 评估当前边界和后续计划时阅读 [能力矩阵](./capabilities.md)。
package/docs/zh/api.md CHANGED
@@ -80,7 +80,7 @@ subscribe(
80
80
  - 最后一个 handler 释放后,当前 Tab 才退出该 Topic。
81
81
  - transport 尚未 ready 时订阅自动排队。
82
82
  - 通配符订阅:以 `.*` 结尾的 Topic(如 `chat.*`)匹配任意后缀,`*` 匹配全部。pattern 以字面量参与路由、归属与传输订阅;携带匹配的具体 topic(或 pattern 本身)的发布都会投递给通配 handler。匹配规则见下方 `topicMatchesPattern`。
83
- - 重放(可选):构造 bus 时传 `replay: { maxPerTopic }` 开启缓冲,`maxPerTopic` 必须是正安全整数;`subscribe()` 第三个参数传 `{ replay: true | n }` 后,新 handler 会立即收到缓冲历史(最多 `n` 条,受 `maxPerTopic` 上限约束,默认 100),消息带 `message.replayed: true` 标记——晚加入的 handler 不会错过更早的发布。只有被分发过的消息才入缓冲(无本地订阅者的 topic 会被 owner 丢弃);缓冲仅存内存,该 topic 最后一个 handler 退订时清空。通配订阅会对所有匹配 pattern 的已缓冲 topic 做回放。
83
+ - 重放(可选):构造 bus 时传 `replay: { maxPerTopic }` 开启缓冲,`maxPerTopic` 必须是正安全整数;`subscribe()` 第三个参数传 `{ replay: true | n }` 后,新 handler 会立即收到缓冲历史(最多 `n` 条,受 `maxPerTopic` 上限约束,默认 100),消息带 `message.replayed: true` 标记——晚加入的 handler 不会错过更早的发布。只有被分发过的消息才入缓冲(无本地订阅者的 topic 会被 owner 丢弃);缓冲仅存内存,该 topic 最后一个 handler 退订时清空。通配订阅会对所有匹配 pattern 的已缓冲 topic 做回放。需要跨 reload/BFCache 持久化时,可传入 `createIndexedDbReplayPersistence({ maxPerTopic })` 创建的 `persistence`;持久化为异步操作,失败会通过 `onError` 报告,不影响实时投递。
84
84
 
85
85
  ### `unsubscribe(topic, handler?)`
86
86
 
@@ -0,0 +1,18 @@
1
+ # 路线图
2
+
3
+ 0.4.0 已发布。下一阶段统一按 0.5.0 候选推进,让性能、持久化和兼容性说明一起落地。
4
+
5
+ ## 0.5.0 候选
6
+
7
+ 1. **publish 路径 profile 与优化**:结合 `pnpm bench` 和 `pnpm bench:browser`,先拆分 storage batching、路由和页面/服务端开销,再决定是否优化;
8
+ 2. **重放持久化**:增加 IndexedDB 历史适配器,支持 reload 与 BFCache 会话间恢复;保留纯内存重放作为零依赖默认;
9
+ 3. **Vue composable**:复制 React hooks 的生命周期与订阅语义,Vue 仍保持可选依赖;
10
+ 4. **二进制 demo 真链路**:让 WebSocket demo 端到端覆盖真实 `ArrayBuffer` 帧,同时保留仅支持 JSON 服务端的 base64 fallback;
11
+ 5. **Push CI 浏览器门禁**:环境提供 Chrome 时在 push 上运行 Playwright,贡献者本地仍可手动执行。
12
+
13
+ ## 发版检查清单
14
+
15
+ - 更新 `[Unreleased]` 与版本日期;
16
+ - 执行 `pnpm check`、`pnpm lint`、`pnpm test:e2e`、`pnpm bench`、`pnpm bench:browser`;
17
+ - 从打包 tarball 做 ESM/CJS 消费冒烟验证;
18
+ - 推送 tag 后核验 GitHub Release 与 npm `latest` dist-tag。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cross-tab-worker-databus",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Framework-agnostic cross-tab data bus with Dedicated/Shared Worker clustering and Centrifuge support.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -71,6 +71,7 @@
71
71
  "test:watch": "vitest",
72
72
  "test:coverage": "vitest run --coverage",
73
73
  "bench": "vitest bench --run",
74
+ "bench:browser": "pnpm build && node scripts/bench-browser.mjs",
74
75
  "test:e2e": "pnpm build && playwright test",
75
76
  "typecheck": "tsc --noEmit",
76
77
  "prepublishOnly": "pnpm check"