cross-tab-worker-databus 0.20.85 → 0.20.86

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.
@@ -13,17 +13,20 @@ import { FAILURE_SOURCE, HEALTH_STATE, PRUNE_STRATEGY } from '../utils/constants
13
13
  * Buffers live in memory by default; an optional persistence backend can make
14
14
  * them durable. */
15
15
  export interface DataBusReplayOptions<TData = unknown> {
16
- /** Maximum buffered publications per topic. Oldest entries are evicted
17
- * first. Default 100. */
16
+ /** Maximum buffered publications per topic under 'count'/'both'. With 'age',
17
+ * timestamped history is bounded by `retentionMs` and timestamp-less legacy
18
+ * entries are capped by this value. Oldest entries are evicted first.
19
+ * Default 100. */
18
20
  maxPerTopic?: number;
19
21
  /** Optional durable history backend. Defaults to in-memory only. */
20
22
  persistence?: DataBusReplayPersistence<TData>;
21
23
  /** Optional producer-timestamp retention window in milliseconds. */
22
24
  retentionMs?: number;
23
25
  /** History trimming policy: 'count' (default) caps each topic at
24
- * `maxPerTopic`, 'age' prunes by `retentionMs`, and 'both' applies both. An
25
- * 'age' strategy without `retentionMs` has nothing to prune by and falls
26
- * back to the count cap. */
26
+ * `maxPerTopic`, 'age' prunes by `retentionMs`, and 'both' applies both.
27
+ * With 'age', timestamped entries are bounded by the retention window and
28
+ * timestamp-less legacy entries are capped by `maxPerTopic`. An 'age'
29
+ * strategy without `retentionMs` falls back to the count cap. */
27
30
  pruneStrategy?: (typeof PRUNE_STRATEGY)[keyof typeof PRUNE_STRATEGY];
28
31
  /** Optional periodic sweep interval for durable retention cleanup. */
29
32
  retentionSweepMs?: number;
@@ -176,6 +179,12 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
176
179
  private persistenceLastFailureAt;
177
180
  private persistenceLastErrorMessage;
178
181
  private startPromise;
182
+ private stopPromise;
183
+ private queuedStart;
184
+ private queuedStartReady;
185
+ private queuedStartReadyToken;
186
+ private queuedStartToken;
187
+ private canceledQueuedStartToken;
179
188
  private lastRecoveryAt;
180
189
  private recoveryAttempt;
181
190
  private recoveryExhausted;
@@ -188,6 +197,7 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
188
197
  private lastSuccessAt;
189
198
  private suspended;
190
199
  private pendingStop;
200
+ private lifecycleEpoch;
191
201
  private readonly recoveryCooldownMs;
192
202
  private readonly recoveryMaxAttempts;
193
203
  constructor(options: CrossTabDataBusOptions<TConfig, TData>);
@@ -195,11 +205,20 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
195
205
  * Start the DataBus with the given transport config.
196
206
  *
197
207
  * The first call starts the cluster and opens the transport. Concurrent calls
198
- * during an in-flight start return the same promise. Once the operation
199
- * settles (success or failure) the promise gate is cleared so a subsequent
200
- * start() or resumeTransport() can open a fresh lifecycle.
208
+ * during an in-flight open return the same promise. A call received while an
209
+ * explicit stop() is settling queues one fresh start after cleanup; a later
210
+ * stop() before that queued start runs cancels it, so the latest lifecycle
211
+ * intent wins. Once an operation settles (success or failure) its promise
212
+ * gate is cleared so a subsequent start() or resumeTransport() can open a
213
+ * fresh lifecycle.
201
214
  */
202
215
  start(config: TConfig): Promise<void>;
216
+ /** Return a cancellation-aware readiness view of the current queued start. */
217
+ private getQueuedStartReady;
218
+ /** Queue exactly one fresh start after an in-flight explicit stop settles. */
219
+ private queueStartAfterStop;
220
+ /** Reset failure and recovery diagnostics for a new explicit start session. */
221
+ private resetFailureState;
203
222
  /**
204
223
  * Open the transport, chained after `before` to ensure lifecycle ordering.
205
224
  * When `stopClusterOnFailure` is true (initial start), a transport failure
@@ -209,13 +228,17 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
209
228
  /**
210
229
  * Await the DataBus to be fully started (lazy init when using initialConfig).
211
230
  * Returns a rejected promise when the transport has failed and no start is in
212
- * flight — the caller can retry by calling start() or ready() again.
231
+ * flight — the caller can retry by calling start() or ready() again. While an
232
+ * explicit stop() is settling, this rejects unless a restart is queued behind
233
+ * it; false readiness during teardown is never reported.
213
234
  */
214
235
  ready(): Promise<void>;
215
236
  /**
216
237
  * Register a handler for `topic`. The handler fires on every publication
217
238
  * delivered to this tab, regardless of which tab published it. Returns an
218
- * unsubscribe function for convenience.
239
+ * unsubscribe function for convenience. During an explicit stop() the
240
+ * registration is rejected through onError and a no-op cleanup is returned,
241
+ * so a late subscriber cannot leak into a future restart.
219
242
  */
220
243
  subscribe(topic: string, handler: DataBusMessageHandler<TData>, options?: {
221
244
  replay?: boolean | number;
@@ -287,9 +310,12 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
287
310
  getMetrics(): DataBusMetricsSnapshot | null;
288
311
  /**
289
312
  * Gracefully stop the DataBus: unsubscribe all topics, stop the cluster,
290
- * and close the transport. Idempotent.
313
+ * and close the transport. Concurrent and repeated calls share the in-flight
314
+ * stop promise. A start() received while stopping runs after this completes,
315
+ * unless another stop() arrives first and cancels that queued restart.
291
316
  */
292
317
  stop(): Promise<void>;
318
+ private performStop;
293
319
  /**
294
320
  * Incoming message from the transport.
295
321
  * Records metrics, checks ownership via the cluster, broadcasts to other tabs,
@@ -357,6 +383,13 @@ export declare class CrossTabDataBus<TConfig = unknown, TData = unknown> {
357
383
  * during startup are not lost.
358
384
  */
359
385
  private runTransport;
386
+ /**
387
+ * Publications started after teardown begins cannot reach any transport.
388
+ * Surface that as a normal asynchronous API failure instead of letting
389
+ * runTransport() return silently. Empty publishBatch() calls remain a no-op
390
+ * and are filtered by the caller before this check.
391
+ */
392
+ private rejectPublishDuringStop;
360
393
  /**
361
394
  * Ensure the DataBus is started, throwing if no initialConfig was provided.
362
395
  * Called automatically by subscribe/publish/ready when autoStart is true.
@@ -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,EAC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;;OAIG;IACH,OAAO,CAAC,sBAAsB;IAuB9B,kFAAkF;IAClF,OAAO,CAAC,eAAe;IAIvB,6CAA6C;IAC7C,OAAO,CAAC,cAAc;IAItB;;yEAEqE;IACrE,OAAO,CAAC,QAAQ;IAWhB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAyCpB,OAAO,CAAC,WAAW;IAkBnB;;4DAEwD;IACxD,OAAO,CAAC,sBAAsB;IAM9B,OAAO,CAAC,iBAAiB;IASzB;;;8EAG0E;IAC1E,OAAO,CAAC,qBAAqB;IAW7B,8DAA8D;IAC9D,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,oBAAoB;IAM5B;;;;+CAI2C;IAC3C,OAAO,CAAC,cAAc;IAoBtB;;;OAGG;IACH,OAAO,CAAC,gBAAgB;IAyBxB;qEACiE;IACjE,OAAO,CAAC,iBAAiB;IAMzB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAIvB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IA+CvB;;;;OAIG;IACH,OAAO,CAAC,YAAY;IA6BpB;;;;;OAKG;IACH,OAAO,CAAC,uBAAuB;IAS/B;;;OAGG;IACH,OAAO,CAAC,aAAa;CAUtB"}
@@ -1,7 +1,7 @@
1
1
  import type { DataBusReplayPersistence } from './replay-persistence';
2
2
  import type { DataBusTraceReporter } from './trace';
3
3
  import type { DataBusMessage, DataBusMessageHandler } from './types';
4
- import { PRUNE_STRATEGY } from '../utils/constants';
4
+ import type { PRUNE_STRATEGY } from '../utils/constants';
5
5
  /** Thrown when a lifecycle transition cancels an in-flight persistence retry. */
6
6
  export declare class PersistenceRetryCancelledError extends Error {
7
7
  constructor();
@@ -10,7 +10,8 @@ export declare class PersistenceRetryCancelledError extends Error {
10
10
  export interface ReplayManagerDeps<TData = unknown> {
11
11
  /** Whether replay buffering is enabled at all (false → no-op instance). */
12
12
  enabled: boolean;
13
- /** Maximum buffered publications per topic. */
13
+ /** Per-topic count cap. AGE bounds timestamped entries by retention and
14
+ * still applies this cap to timestamp-less legacy entries. */
14
15
  maxPerTopic: number;
15
16
  /** Optional durable history backend; null → in-memory only. */
16
17
  persistence?: DataBusReplayPersistence<TData> | null;
@@ -1 +1 @@
1
- {"version":3,"file":"replay-manager.d.ts","sourceRoot":"","sources":["../../src/core/replay-manager.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,SAAS,CAAC;AAErE,OAAO,EAAyB,cAAc,EAA2C,MAAM,oBAAoB,CAAC;AAEpH,iFAAiF;AACjF,qBAAa,8BAA+B,SAAQ,KAAK;;CAKxD;AAED,uEAAuE;AACvE,MAAM,WAAW,iBAAiB,CAAC,KAAK,GAAG,OAAO;IAChD,2EAA2E;IAC3E,OAAO,EAAE,OAAO,CAAC;IACjB,+CAA+C;IAC/C,WAAW,EAAE,MAAM,CAAC;IACpB,+DAA+D;IAC/D,WAAW,CAAC,EAAE,wBAAwB,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC;IACrD,oEAAoE;IACpE,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,+BAA+B;IAC/B,aAAa,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,OAAO,cAAc,CAAC,CAAC;IACpE,sEAAsE;IACtE,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,kEAAkE;IAClE,2BAA2B,EAAE,MAAM,CAAC;IACpC,wDAAwD;IACxD,yBAAyB,EAAE,MAAM,CAAC;IAClC,0DAA0D;IAC1D,GAAG,EAAE,MAAM,MAAM,CAAC;IAClB,4DAA4D;IAC5D,KAAK,EAAE,oBAAoB,CAAC;IAC5B,4EAA4E;IAC5E,kBAAkB,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IA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IAC/E,WAAW,CAAC,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAChD;AAED,MAAM,WAAW,iCAAiC;IAChD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,OAAO,cAAc,CAAC,CAAC;IACrE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,sDAAsD;AACtD,wBAAgB,gCAAgC,CAAC,KAAK,GAAG,OAAO,EAC9D,OAAO,EAAE,iCAAiC,GACzC,wBAAwB,CAAC,KAAK,CAAC,CA6RjC"}
@@ -0,0 +1,21 @@
1
+ import type { DataBusMessage } from './types';
2
+ import { PRUNE_STRATEGY } from '../utils/constants';
3
+ /** Inputs shared by the in-memory ring and durable replay adapters. */
4
+ export interface ReplayPruningOptions {
5
+ maxPerTopic: number;
6
+ pruneStrategy: (typeof PRUNE_STRATEGY)[keyof typeof PRUNE_STRATEGY];
7
+ retentionMs: number | undefined;
8
+ now: number;
9
+ }
10
+ /**
11
+ * Apply the public replay pruning policy to an insertion-ordered history.
12
+ *
13
+ * `count` keeps the newest `maxPerTopic` entries. `both` applies the retention
14
+ * cutoff first and then the count cap. `age` intentionally leaves timestamped
15
+ * entries uncapped so the retention window is the only bound for them, while
16
+ * timestamp-less legacy entries are still capped by `maxPerTopic` because they
17
+ * have no timestamp by which they can ever expire. The returned array is the
18
+ * same instance when no entries need to be removed.
19
+ */
20
+ export declare function pruneReplayHistory<TData>(messages: DataBusMessage<TData>[], options: ReplayPruningOptions): DataBusMessage<TData>[];
21
+ //# sourceMappingURL=replay-pruning.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay-pruning.d.ts","sourceRoot":"","sources":["../../src/core/replay-pruning.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,uEAAuE;AACvE,MAAM,WAAW,oBAAoB;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,OAAO,cAAc,CAAC,CAAC;IACpE,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EACtC,QAAQ,EAAE,cAAc,CAAC,KAAK,CAAC,EAAE,EACjC,OAAO,EAAE,oBAAoB,GAC5B,cAAc,CAAC,KAAK,CAAC,EAAE,CAiCzB"}
package/dist/index.js CHANGED
@@ -14,12 +14,13 @@ import {
14
14
  hasActiveOwner,
15
15
  isWildcardTopic,
16
16
  parseDataBusPublication,
17
+ pruneReplayHistory,
17
18
  selectActiveWorkers,
18
19
  selectLeastLoadedWorker,
19
20
  selectRebalanceTarget,
20
21
  selectWorkerBackend,
21
22
  topicMatchesPattern
22
- } from "./chunk-PW63EWIK.js";
23
+ } from "./chunk-SDOV3UHG.js";
23
24
  import {
24
25
  DEFAULT_STORAGE_PREFIX,
25
26
  PRUNE_STRATEGY,
@@ -110,35 +111,29 @@ function createIndexedDbReplayPersistence(options) {
110
111
  grouped.set(message.topic, [...grouped.get(message.topic) ?? [], message]);
111
112
  }
112
113
  let hasError = false;
114
+ const fail = (error) => {
115
+ if (hasError) return;
116
+ hasError = true;
117
+ invalidate(db);
118
+ reject(error);
119
+ };
113
120
  for (const [topic, topicMessages] of grouped) {
114
121
  const request = store.get(topic);
115
122
  request.onsuccess = () => {
116
123
  if (hasError) return;
117
- let history = (request.result?.messages ?? []).concat(topicMessages);
118
- const ageBounded = pruneStrategy !== PRUNE_STRATEGY.COUNT && retentionMs !== void 0;
119
- if (ageBounded) {
120
- const cutoff = Date.now() - retentionMs;
121
- history = history.filter((item) => item.timestamp === void 0 || item.timestamp >= cutoff);
122
- }
123
- if (pruneStrategy !== PRUNE_STRATEGY.AGE || !ageBounded) history = history.slice(-maxPerTopic);
124
+ const history = pruneReplayHistory(
125
+ (request.result?.messages ?? []).concat(topicMessages),
126
+ { maxPerTopic, pruneStrategy, retentionMs, now: Date.now() }
127
+ );
124
128
  store.put({ topic, messages: history });
125
129
  };
126
- request.onerror = () => {
127
- if (hasError) return;
128
- hasError = true;
129
- invalidate(db);
130
- reject(request.error ?? new Error("Failed to read replay history."));
131
- };
130
+ request.onerror = () => fail(request.error ?? new Error("Failed to read replay history."));
132
131
  }
133
132
  transaction.oncomplete = () => {
134
133
  if (!hasError) resolve();
135
134
  };
136
- transaction.onerror = () => {
137
- if (hasError) return;
138
- hasError = true;
139
- invalidate(db);
140
- reject(transaction.error ?? new Error("Failed to persist replay history."));
141
- };
135
+ transaction.onerror = () => fail(transaction.error ?? new Error("Failed to persist replay history."));
136
+ transaction.onabort = () => fail(transaction.error ?? new Error("Failed to persist replay history."));
142
137
  });
143
138
  })();
144
139
  const open = () => {
@@ -166,19 +161,34 @@ function createIndexedDbReplayPersistence(options) {
166
161
  async load() {
167
162
  const db = await open();
168
163
  return new Promise((resolve, reject) => {
164
+ let transaction;
169
165
  let request;
170
166
  try {
171
- request = db.transaction(storeName, "readonly").objectStore(storeName).getAll();
167
+ transaction = db.transaction(storeName, "readonly");
168
+ request = transaction.objectStore(storeName).getAll();
172
169
  } catch (error) {
173
170
  invalidate(db);
174
171
  reject(error);
175
172
  return;
176
173
  }
177
- request.onsuccess = () => resolve(request.result.flatMap((record) => record.messages));
178
- request.onerror = () => {
174
+ let settled = false;
175
+ const fail = (error) => {
176
+ if (settled) return;
177
+ settled = true;
179
178
  invalidate(db);
180
- reject(request.error ?? new Error("Failed to load replay history."));
179
+ reject(error);
180
+ };
181
+ let records = [];
182
+ request.onsuccess = () => {
183
+ records = request.result;
181
184
  };
185
+ request.onerror = () => fail(request.error ?? new Error("Failed to load replay history."));
186
+ transaction.oncomplete = () => {
187
+ if (settled) return;
188
+ settled = true;
189
+ resolve(records.flatMap((record) => record.messages));
190
+ };
191
+ transaction.onabort = () => fail(transaction.error ?? new Error("Failed to load replay history."));
182
192
  });
183
193
  },
184
194
  append(message) {
@@ -202,12 +212,20 @@ function createIndexedDbReplayPersistence(options) {
202
212
  reject(error);
203
213
  return;
204
214
  }
205
- transaction.objectStore(storeName).clear();
206
- transaction.oncomplete = () => resolve();
207
- transaction.onerror = () => {
215
+ let settled = false;
216
+ const fail = (error) => {
217
+ if (settled) return;
218
+ settled = true;
208
219
  invalidate(db);
209
- reject(transaction.error ?? new Error("Failed to clear replay history."));
220
+ reject(error);
221
+ };
222
+ transaction.objectStore(storeName).clear();
223
+ transaction.oncomplete = () => {
224
+ settled = true;
225
+ resolve();
210
226
  };
227
+ transaction.onerror = () => fail(transaction.error ?? new Error("Failed to clear replay history."));
228
+ transaction.onabort = () => fail(transaction.error ?? new Error("Failed to clear replay history."));
211
229
  });
212
230
  })()
213
231
  });
@@ -226,12 +244,20 @@ function createIndexedDbReplayPersistence(options) {
226
244
  reject(error);
227
245
  return;
228
246
  }
229
- transaction.objectStore(storeName).delete(topic);
230
- transaction.oncomplete = () => resolve();
231
- transaction.onerror = () => {
247
+ let settled = false;
248
+ const fail = (error) => {
249
+ if (settled) return;
250
+ settled = true;
232
251
  invalidate(db);
233
- reject(transaction.error ?? new Error("Failed to clear topic replay history."));
252
+ reject(error);
234
253
  };
254
+ transaction.objectStore(storeName).delete(topic);
255
+ transaction.oncomplete = () => {
256
+ settled = true;
257
+ resolve();
258
+ };
259
+ transaction.onerror = () => fail(transaction.error ?? new Error("Failed to clear topic replay history."));
260
+ transaction.onabort = () => fail(transaction.error ?? new Error("Failed to clear topic replay history."));
235
261
  });
236
262
  })()
237
263
  });
@@ -250,6 +276,13 @@ function createIndexedDbReplayPersistence(options) {
250
276
  reject(error);
251
277
  return;
252
278
  }
279
+ let settled = false;
280
+ const fail = (error) => {
281
+ if (settled) return;
282
+ settled = true;
283
+ invalidate(db);
284
+ reject(error);
285
+ };
253
286
  const store = transaction.objectStore(storeName);
254
287
  const request = store.getAll();
255
288
  request.onsuccess = () => {
@@ -259,15 +292,13 @@ function createIndexedDbReplayPersistence(options) {
259
292
  else if (messages.length !== record.messages.length) store.put({ topic: record.topic, messages });
260
293
  }
261
294
  };
262
- request.onerror = () => {
263
- invalidate(db);
264
- reject(request.error ?? new Error("Failed to read replay history."));
265
- };
266
- transaction.oncomplete = () => resolve();
267
- transaction.onerror = () => {
268
- invalidate(db);
269
- reject(transaction.error ?? new Error("Failed to prune replay history."));
295
+ request.onerror = () => fail(request.error ?? new Error("Failed to read replay history."));
296
+ transaction.oncomplete = () => {
297
+ settled = true;
298
+ resolve();
270
299
  };
300
+ transaction.onerror = () => fail(transaction.error ?? new Error("Failed to prune replay history."));
301
+ transaction.onabort = () => fail(transaction.error ?? new Error("Failed to prune replay history."));
271
302
  });
272
303
  })()
273
304
  });
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 { 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 for (const [topic, topicMessages] of grouped) {\n const request = store.get(topic);\n request.onsuccess = () => {\n if (hasError) return;\n let history = ((request.result?.messages ?? []) as DataBusMessage<TData>[]).concat(topicMessages);\n // Mirrors ReplayManager: an AGE strategy with no retention window\n // has nothing to prune by, so the count cap still applies (else the\n // stored topic record would grow without bound).\n const ageBounded = pruneStrategy !== PRUNE_STRATEGY.COUNT && retentionMs !== undefined;\n if (ageBounded) {\n const cutoff = Date.now() - retentionMs;\n history = history.filter(item => item.timestamp === undefined || item.timestamp >= cutoff);\n }\n if (pruneStrategy !== PRUNE_STRATEGY.AGE || !ageBounded) history = history.slice(-maxPerTopic);\n store.put({ topic, messages: history });\n };\n request.onerror = () => {\n if (hasError) return;\n hasError = true;\n invalidate(db);\n reject(request.error ?? new Error('Failed to read replay history.'));\n };\n }\n transaction.oncomplete = () => {\n if (!hasError) resolve();\n };\n transaction.onerror = () => {\n if (hasError) return;\n hasError = true;\n invalidate(db);\n reject(transaction.error ?? new Error('Failed to persist replay history.'));\n };\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 request: IDBRequest;\n try {\n request = db.transaction(storeName, 'readonly').objectStore(storeName).getAll();\n } catch (error) {\n invalidate(db);\n reject(error);\n return;\n }\n request.onsuccess = () => resolve((request.result as Array<{ messages: DataBusMessage<TData>[] }>).flatMap(record => record.messages));\n request.onerror = () => {\n invalidate(db);\n reject(request.error ?? new Error('Failed to load replay history.'));\n };\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 transaction.objectStore(storeName).clear();\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(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 transaction.objectStore(storeName).delete(topic);\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(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 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 = () => { invalidate(db); reject(request.error ?? new Error('Failed to read replay history.')); };\n transaction.oncomplete = () => resolve();\n transaction.onerror = () => { invalidate(db); reject(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}\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 readonly diagnosticsName = 'websocket';\n readonly diagnosticsBackend = 'native-websocket';\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(WORKER_STATUS.ERROR);\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\n if (this.socket !== socket || this.handlers !== handlers) return;\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 };\n socket.onclose = () => {\n if (this.socket === socket && this.handlers === handlers) handlers.onStatus(WORKER_STATUS.DISCONNECTED);\n };\n socket.onerror = () => {\n if (this.socket === socket && this.handlers === handlers) handlers.onStatus(WORKER_STATUS.ERROR);\n };\n socket.onmessage = event => {\n if (this.socket === socket && this.handlers === handlers) void this.handleMessage(event.data);\n };\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: 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 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; 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
-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Q,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,cAAc,wBAA+B,MAAM;AACzD,QAAI,YAAa,MAAK,UAAU,UAAU,WAAoC;AAAA,EAChF;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;",
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}\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 readonly diagnosticsName = 'websocket';\n readonly diagnosticsBackend = 'native-websocket';\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(WORKER_STATUS.ERROR);\n handlers.onError(error);\n return;\n }\n socket.onopen = () => {\n if (this.socket !== socket || this.handlers !== handlers) return;\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 };\n socket.onclose = () => {\n if (this.socket === socket && this.handlers === handlers) handlers.onStatus(WORKER_STATUS.DISCONNECTED);\n };\n socket.onerror = () => {\n if (this.socket === socket && this.handlers === handlers) handlers.onStatus(WORKER_STATUS.ERROR);\n };\n socket.onmessage = event => {\n if (this.socket === socket && this.handlers === handlers) void this.handleMessage(event.data);\n };\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: 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 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; 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,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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