@abraca/dabra 2.95.0 → 2.96.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.
@@ -1128,6 +1128,128 @@ const Kind = {
1128
1128
  */
1129
1129
  const SERVER_ROOT_ID = "00000000-0000-0000-0000-000000000000";
1130
1130
 
1131
+ //#endregion
1132
+ //#region packages/provider/src/LifecycleGate.ts
1133
+ /** How long the app must stay hidden before we act on it. */
1134
+ const HIDE_GRACE_MS = 1e4;
1135
+ /** The browser's own visibility, or a permanently-visible stub off-DOM. */
1136
+ function defaultSource() {
1137
+ const doc = globalThis.document;
1138
+ if (!doc || typeof doc.addEventListener !== "function") return {
1139
+ get: () => "visible",
1140
+ subscribe: () => () => {}
1141
+ };
1142
+ return {
1143
+ get: () => doc.visibilityState === "hidden" ? "hidden" : "visible",
1144
+ subscribe: (onChange) => {
1145
+ doc.addEventListener("visibilitychange", onChange);
1146
+ return () => doc.removeEventListener("visibilitychange", onChange);
1147
+ }
1148
+ };
1149
+ }
1150
+ var LifecycleGate = class {
1151
+ constructor(source = defaultSource(), graceMs = HIDE_GRACE_MS) {
1152
+ this.graceMs = graceMs;
1153
+ this.unsubscribe = null;
1154
+ this.hideTimer = null;
1155
+ this._backgrounded = false;
1156
+ this.listeners = /* @__PURE__ */ new Set();
1157
+ this.source = source;
1158
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1159
+ }
1160
+ /**
1161
+ * True when the app has been hidden for longer than the grace period.
1162
+ *
1163
+ * Deliberately NOT the same as `document.hidden`: a tab that was hidden two
1164
+ * seconds ago is still, for our purposes, in use.
1165
+ */
1166
+ get backgrounded() {
1167
+ return this._backgrounded;
1168
+ }
1169
+ /** Subscribe to background/foreground transitions. Returns an unsubscribe fn. */
1170
+ onChange(listener) {
1171
+ this.listeners.add(listener);
1172
+ return () => this.listeners.delete(listener);
1173
+ }
1174
+ /** Swap the visibility source. Used by tests to drive state deterministically. */
1175
+ setSource(source) {
1176
+ this.unsubscribe?.();
1177
+ this.source = source;
1178
+ this.unsubscribe = this.source.subscribe(() => this.onVisibilityChange());
1179
+ this.onVisibilityChange();
1180
+ }
1181
+ onVisibilityChange() {
1182
+ if (this.source.get() === "hidden") {
1183
+ if (this._backgrounded || this.hideTimer) return;
1184
+ this.hideTimer = setTimeout(() => {
1185
+ this.hideTimer = null;
1186
+ this.setBackgrounded(true);
1187
+ }, this.graceMs);
1188
+ return;
1189
+ }
1190
+ if (this.hideTimer) {
1191
+ clearTimeout(this.hideTimer);
1192
+ this.hideTimer = null;
1193
+ }
1194
+ this.setBackgrounded(false);
1195
+ }
1196
+ setBackgrounded(next) {
1197
+ if (this._backgrounded === next) return;
1198
+ this._backgrounded = next;
1199
+ for (const listener of [...this.listeners]) try {
1200
+ listener(next);
1201
+ } catch {}
1202
+ }
1203
+ destroy() {
1204
+ this.unsubscribe?.();
1205
+ this.unsubscribe = null;
1206
+ if (this.hideTimer) {
1207
+ clearTimeout(this.hideTimer);
1208
+ this.hideTimer = null;
1209
+ }
1210
+ this.listeners.clear();
1211
+ }
1212
+ };
1213
+ /**
1214
+ * The process-wide gate.
1215
+ *
1216
+ * Visibility is a property of the tab, not of any one provider or socket, so a
1217
+ * single shared instance is both correct and avoids paying for one
1218
+ * `visibilitychange` listener per document.
1219
+ */
1220
+ let shared = null;
1221
+ function getLifecycleGate() {
1222
+ if (!shared) shared = new LifecycleGate();
1223
+ return shared;
1224
+ }
1225
+ /**
1226
+ * Replace the shared gate. Tests use this to install a controllable source;
1227
+ * passing `null` restores the default browser-backed gate on next access.
1228
+ */
1229
+ function setLifecycleGate(gate) {
1230
+ if (shared && shared !== gate) shared.destroy();
1231
+ shared = gate;
1232
+ }
1233
+ /** A visibility source a test (or an embedder) can drive by hand. */
1234
+ var ManualVisibilitySource = class {
1235
+ constructor() {
1236
+ this.state = "visible";
1237
+ this.listeners = /* @__PURE__ */ new Set();
1238
+ }
1239
+ get() {
1240
+ return this.state;
1241
+ }
1242
+ subscribe(onChange) {
1243
+ this.listeners.add(onChange);
1244
+ return () => this.listeners.delete(onChange);
1245
+ }
1246
+ set(state) {
1247
+ if (this.state === state) return;
1248
+ this.state = state;
1249
+ for (const listener of [...this.listeners]) listener();
1250
+ }
1251
+ };
1252
+
1131
1253
  //#endregion
1132
1254
  //#region packages/provider/src/IncomingMessage.ts
1133
1255
  var IncomingMessage = class {
@@ -1235,6 +1357,7 @@ var AbracadabraWS = class extends EventEmitter {
1235
1357
  this.connectionAttempt = null;
1236
1358
  this.onlineListener = null;
1237
1359
  this.offlineListener = null;
1360
+ this.unsubscribeLifecycle = null;
1238
1361
  this.receivedOnOpenPayload = void 0;
1239
1362
  this.closeTries = 0;
1240
1363
  this.lastRefreshToken = null;
@@ -1254,6 +1377,9 @@ var AbracadabraWS = class extends EventEmitter {
1254
1377
  this.on("close", this.onClose.bind(this));
1255
1378
  this.on("message", this.onMessage.bind(this));
1256
1379
  this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
1380
+ this.unsubscribeLifecycle = getLifecycleGate().onChange((backgrounded) => {
1381
+ if (!backgrounded) this.checkConnection();
1382
+ });
1257
1383
  if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
1258
1384
  this.onlineListener = this.handleOnline.bind(this);
1259
1385
  this.offlineListener = this.handleOffline.bind(this);
@@ -1437,6 +1563,7 @@ var AbracadabraWS = class extends EventEmitter {
1437
1563
  this.connectionAttempt = null;
1438
1564
  }
1439
1565
  checkConnection() {
1566
+ if (getLifecycleGate().backgrounded) return;
1440
1567
  if (this.status !== WebSocketStatus.Connected) return;
1441
1568
  if (!this.lastMessageReceived) return;
1442
1569
  if (this.configuration.messageReconnectTimeout >= getUnixTime() - this.lastMessageReceived) return;
@@ -1562,6 +1689,8 @@ var AbracadabraWS = class extends EventEmitter {
1562
1689
  }
1563
1690
  this.onlineListener = null;
1564
1691
  this.offlineListener = null;
1692
+ this.unsubscribeLifecycle?.();
1693
+ this.unsubscribeLifecycle = null;
1565
1694
  clearInterval(this.intervals.connectionChecker);
1566
1695
  this.stopConnectionAttempt();
1567
1696
  this.disconnect();
@@ -1788,19 +1917,21 @@ var MessageReceiver = class {
1788
1917
  provider.reportWriteRejected("server did not apply the update (permission or validation)", "validation");
1789
1918
  }
1790
1919
  applyAwarenessMessage(provider) {
1791
- if (!provider.awareness) return;
1920
+ const awareness = provider.peekAwareness();
1921
+ if (!awareness) return;
1792
1922
  const { message } = this;
1793
- applyAwarenessUpdate(provider.awareness, message.readVarUint8Array(), provider);
1923
+ applyAwarenessUpdate(awareness, message.readVarUint8Array(), provider);
1794
1924
  }
1795
1925
  applyAuthMessage(provider) {
1796
1926
  const { message } = this;
1797
1927
  readAuthMessage(message.decoder, provider.sendToken.bind(provider), provider.permissionDeniedHandler.bind(provider), provider.authenticatedHandler.bind(provider));
1798
1928
  }
1799
1929
  applyQueryAwarenessMessage(provider) {
1800
- if (!provider.awareness) return;
1930
+ const awareness = provider.peekAwareness();
1931
+ if (!awareness) return;
1801
1932
  const { message } = this;
1802
1933
  message.writeVarUint(MessageType.Awareness);
1803
- message.writeVarUint8Array(encodeAwarenessUpdate(provider.awareness, Array.from(provider.awareness.getStates().keys())));
1934
+ message.writeVarUint8Array(encodeAwarenessUpdate(awareness, Array.from(awareness.getStates().keys())));
1804
1935
  }
1805
1936
  };
1806
1937
 
@@ -2568,12 +2699,20 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2568
2699
  this.forwardDisconnect = (e) => this.emit("disconnect", e);
2569
2700
  this.forwardDestroy = () => this.emit("destroy");
2570
2701
  this.forwardRateLimited = () => this.emit("rateLimited");
2702
+ this._awarenessDeferred = false;
2703
+ this._awarenessExplicitlyNull = false;
2571
2704
  this.lastWriteRejection = null;
2572
2705
  this.writeRejectionCount = 0;
2573
2706
  this.setConfiguration(configuration);
2574
2707
  this.configuration.document = configuration.document ? configuration.document : new yjs.Doc();
2575
- this.configuration.awareness = configuration.awareness !== void 0 ? configuration.awareness : new Awareness(this.document);
2576
- if (this.awareness && this.awareness.getLocalState() === null) this.awareness.setLocalState({});
2708
+ if (configuration.awareness !== void 0) {
2709
+ this.configuration.awareness = configuration.awareness;
2710
+ this._awarenessExplicitlyNull = configuration.awareness === null;
2711
+ } else if (configuration.lazyAwareness) {
2712
+ this.configuration.awareness = null;
2713
+ this._awarenessDeferred = true;
2714
+ } else this.configuration.awareness = new Awareness(this.document);
2715
+ if (!this._awarenessDeferred) this._initAwareness();
2577
2716
  this.on("open", this.configuration.onOpen);
2578
2717
  this.on("reconnected", this.configuration.onReconnected);
2579
2718
  this.on("message", this.configuration.onMessage);
@@ -2589,14 +2728,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2589
2728
  this.on("authenticationFailed", this.configuration.onAuthenticationFailed);
2590
2729
  this.on("writeRejected", this.configuration.onWriteRejected);
2591
2730
  this.on("rateLimited", this.configuration.onRateLimited);
2592
- this.awareness?.on("update", () => {
2593
- this.emit("awarenessUpdate", { states: awarenessStatesToArray(this.awareness.getStates()) });
2594
- });
2595
- this.awareness?.on("change", () => {
2596
- this.emit("awarenessChange", { states: awarenessStatesToArray(this.awareness.getStates()) });
2597
- });
2598
2731
  this.document.on("update", this.boundDocumentUpdateHandler);
2599
- this.awareness?.on("update", this.boundAwarenessUpdateHandler);
2600
2732
  this.registerEventListeners();
2601
2733
  if (this.configuration.forceSyncInterval && typeof this.configuration.forceSyncInterval === "number") this.intervals.forceSync = setInterval(this.forceSync.bind(this), this.configuration.forceSyncInterval);
2602
2734
  if (this.manageSocket) this.attach();
@@ -2617,9 +2749,68 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2617
2749
  get isAttached() {
2618
2750
  return this._isAttached;
2619
2751
  }
2752
+ /**
2753
+ * The presence instance for this document, built on demand.
2754
+ *
2755
+ * Reading this materializes a deferred instance (see `lazyAwareness`), which
2756
+ * is why every consumer — TipTap's CollaborationCaret, presence UI, app code
2757
+ * — keeps working unchanged: touching `.awareness` is itself the signal that
2758
+ * this document needs presence.
2759
+ *
2760
+ * Provider INTERNALS must use `peekAwareness()` instead, or the lazy path
2761
+ * materializes everything it was meant to avoid.
2762
+ */
2620
2763
  get awareness() {
2764
+ if (this._awarenessExplicitlyNull) return null;
2765
+ if (this._awarenessDeferred) this._materializeAwareness();
2621
2766
  return this.configuration.awareness;
2622
2767
  }
2768
+ /**
2769
+ * The Awareness instance if one exists, without ever creating one.
2770
+ *
2771
+ * @internal Used by provider internals and `MessageReceiver`. A deferred
2772
+ * document has no local presence, so there is nothing for an inbound
2773
+ * awareness frame to be applied to and nothing to answer a peer's query with
2774
+ * — and materializing on a peer's frame would hand every idle background
2775
+ * document a heartbeat as soon as anyone else joined the space.
2776
+ */
2777
+ peekAwareness() {
2778
+ return this._awarenessDeferred ? null : this.configuration.awareness;
2779
+ }
2780
+ /**
2781
+ * Build the deferred Awareness instance and bring it fully up to date:
2782
+ * seeded, wired, published, and caught up with the peers already present.
2783
+ */
2784
+ _materializeAwareness() {
2785
+ if (!this._awarenessDeferred) return;
2786
+ this._awarenessDeferred = false;
2787
+ this.configuration.awareness = new Awareness(this.document);
2788
+ this._initAwareness();
2789
+ if (this._isAttached) {
2790
+ this.send(AwarenessMessage, {
2791
+ awareness: this.configuration.awareness,
2792
+ clients: [this.document.clientID],
2793
+ documentName: this.configuration.name
2794
+ });
2795
+ this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2796
+ }
2797
+ }
2798
+ /**
2799
+ * Seed and wire an Awareness instance. Shared by the eager constructor path
2800
+ * and the lazy materialization path so the two cannot drift.
2801
+ */
2802
+ _initAwareness() {
2803
+ const awareness = this.configuration.awareness;
2804
+ if (!awareness) return;
2805
+ if (awareness.getLocalState() === null) awareness.setLocalState({});
2806
+ awareness.on("update", () => {
2807
+ this.emit("awarenessUpdate", { states: awarenessStatesToArray(awareness.getStates()) });
2808
+ });
2809
+ awareness.on("change", () => {
2810
+ this.emit("awarenessChange", { states: awarenessStatesToArray(awareness.getStates()) });
2811
+ });
2812
+ awareness.on("update", this.boundAwarenessUpdateHandler);
2813
+ }
2623
2814
  get hasUnsyncedChanges() {
2624
2815
  return this.unsyncedChanges > 0;
2625
2816
  }
@@ -2644,7 +2835,8 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2644
2835
  });
2645
2836
  }
2646
2837
  pageHide() {
2647
- if (this.awareness) removeAwarenessStates(this.awareness, [this.document.clientID], "page hide");
2838
+ const awareness = this.peekAwareness();
2839
+ if (awareness) removeAwarenessStates(awareness, [this.document.clientID], "page hide");
2648
2840
  }
2649
2841
  registerEventListeners() {
2650
2842
  if (typeof window === "undefined" || !("addEventListener" in window)) return;
@@ -2682,7 +2874,7 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2682
2874
  if (!this.isAuthenticated) return;
2683
2875
  const changedClients = added.concat(updated).concat(removed);
2684
2876
  this.send(AwarenessMessage, {
2685
- awareness: this.awareness,
2877
+ awareness: this.peekAwareness(),
2686
2878
  clients: changedClients,
2687
2879
  documentName: this.configuration.name
2688
2880
  });
@@ -2776,12 +2968,13 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2776
2968
  document: this.document,
2777
2969
  documentName: this.configuration.name
2778
2970
  });
2779
- if (this.awareness && this.awareness.getLocalState() !== null) this.send(AwarenessMessage, {
2780
- awareness: this.awareness,
2971
+ const openAwareness = this.peekAwareness();
2972
+ if (openAwareness && openAwareness.getLocalState() !== null) this.send(AwarenessMessage, {
2973
+ awareness: openAwareness,
2781
2974
  clients: [this.document.clientID],
2782
2975
  documentName: this.configuration.name
2783
2976
  });
2784
- if (this.awareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2977
+ if (openAwareness) this.send(QueryAwarenessMessage, { documentName: this.configuration.name });
2785
2978
  }
2786
2979
  send(message, args) {
2787
2980
  if (!this._isAttached) return;
@@ -2804,16 +2997,18 @@ var AbracadabraBaseProvider = class AbracadabraBaseProvider extends EventEmitter
2804
2997
  this.synced = false;
2805
2998
  this._hasEverAuthenticated = false;
2806
2999
  this.clearResubscribe();
2807
- if (this.awareness) removeAwarenessStates(this.awareness, Array.from(this.awareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
3000
+ const closeAwareness = this.peekAwareness();
3001
+ if (closeAwareness) removeAwarenessStates(closeAwareness, Array.from(closeAwareness.getStates().keys()).filter((client) => client !== this.document.clientID), this);
2808
3002
  }
2809
3003
  destroy() {
2810
3004
  this.emit("destroy");
2811
3005
  if (this._rpc) this._rpc.destroy();
2812
3006
  if (this.intervals.forceSync) clearInterval(this.intervals.forceSync);
2813
- if (this.awareness) {
2814
- removeAwarenessStates(this.awareness, [this.document.clientID], "provider destroy");
2815
- this.awareness.off("update", this.boundAwarenessUpdateHandler);
2816
- this.awareness.destroy();
3007
+ const ownAwareness = this.peekAwareness();
3008
+ if (ownAwareness) {
3009
+ removeAwarenessStates(ownAwareness, [this.document.clientID], "provider destroy");
3010
+ ownAwareness.off("update", this.boundAwarenessUpdateHandler);
3011
+ ownAwareness.destroy();
2817
3012
  }
2818
3013
  this.document.off("update", this.boundDocumentUpdateHandler);
2819
3014
  this.removeAllListeners();
@@ -2959,6 +3154,34 @@ function txPromise$2(store, request) {
2959
3154
  request.onerror = () => reject(request.error);
2960
3155
  });
2961
3156
  }
3157
+ /**
3158
+ * Resolve when the whole transaction commits.
3159
+ *
3160
+ * `txPromise` waits on a single request, which is the wrong unit once a
3161
+ * transaction carries a batch: the last `add` succeeding does not mean the
3162
+ * transaction committed, and reporting durability before commit is exactly the
3163
+ * lie the offline store must not tell.
3164
+ */
3165
+ function txComplete(tx) {
3166
+ return new Promise((resolve, reject) => {
3167
+ tx.oncomplete = () => resolve();
3168
+ tx.onerror = () => reject(tx.error);
3169
+ tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("transaction aborted"));
3170
+ });
3171
+ }
3172
+ /**
3173
+ * How long local edits are held before being written as one transaction.
3174
+ *
3175
+ * Yjs emits one update per keystroke, and the store used to open one IndexedDB
3176
+ * transaction for each — measured at 1.02 transactions per keystroke over 200
3177
+ * keystrokes. Coalescing trades a bounded window of durability for roughly an
3178
+ * order of magnitude fewer transactions. The window is small on purpose: these
3179
+ * edits have already gone to the server on the wire (that send is NOT batched),
3180
+ * so the exposure is an offline client that dies within the window.
3181
+ */
3182
+ const WRITE_COALESCE_MS = 150;
3183
+ /** Flush early once a burst reaches this many updates, regardless of the timer. */
3184
+ const MAX_WRITE_BATCH = 128;
2962
3185
  var OfflineStore = class {
2963
3186
  /**
2964
3187
  * @param docId The document UUID.
@@ -2973,6 +3196,9 @@ var OfflineStore = class {
2973
3196
  this.db = null;
2974
3197
  this.dbPromise = null;
2975
3198
  this._destroyed = false;
3199
+ this.writeBuffer = [];
3200
+ this.writeWaiters = [];
3201
+ this.flushTimer = null;
2976
3202
  this.storeKey = serverOrigin ? `${serverOrigin}/${docId}` : docId;
2977
3203
  }
2978
3204
  getDb() {
@@ -2983,13 +3209,91 @@ var OfflineStore = class {
2983
3209
  });
2984
3210
  return this.dbPromise;
2985
3211
  }
2986
- async persistUpdate(update) {
2987
- const db = await this.getDb();
2988
- if (!db) return;
2989
- const store = db.transaction("updates", "readwrite").objectStore("updates");
2990
- await txPromise$2(store, store.add(update));
3212
+ /**
3213
+ * Queue a local update for persistence.
3214
+ *
3215
+ * The returned promise settles when the update has actually been committed,
3216
+ * not when it was queued — so `await persistUpdate(u)` still means "on disk",
3217
+ * exactly as it did when every call opened its own transaction.
3218
+ */
3219
+ persistUpdate(update) {
3220
+ if (this._destroyed || !idbAvailable$4()) return Promise.resolve();
3221
+ this.writeBuffer.push(update);
3222
+ const settled = new Promise((resolve, reject) => {
3223
+ this.writeWaiters.push({
3224
+ resolve,
3225
+ reject
3226
+ });
3227
+ });
3228
+ if (this.writeBuffer.length >= MAX_WRITE_BATCH) this.flushWrites();
3229
+ else if (this.flushTimer === null) this.flushTimer = setTimeout(() => {
3230
+ this.flushWrites();
3231
+ }, WRITE_COALESCE_MS);
3232
+ return settled;
3233
+ }
3234
+ /**
3235
+ * Commit every buffered update as ONE transaction.
3236
+ *
3237
+ * Safe to call at any time, including with an empty buffer — every read path
3238
+ * calls it first so a caller can never observe a store that is missing writes
3239
+ * still sitting in memory.
3240
+ */
3241
+ async flushWrites() {
3242
+ if (this.flushTimer !== null) {
3243
+ clearTimeout(this.flushTimer);
3244
+ this.flushTimer = null;
3245
+ }
3246
+ const batch = this.writeBuffer;
3247
+ const waiters = this.writeWaiters;
3248
+ this.writeBuffer = [];
3249
+ this.writeWaiters = [];
3250
+ if (batch.length === 0) {
3251
+ for (const w of waiters) w.resolve();
3252
+ return;
3253
+ }
3254
+ try {
3255
+ const db = await this.getDb();
3256
+ if (db) {
3257
+ const tx = db.transaction("updates", "readwrite");
3258
+ const store = tx.objectStore("updates");
3259
+ for (const update of batch) store.add(update);
3260
+ await txComplete(tx);
3261
+ }
3262
+ for (const w of waiters) w.resolve();
3263
+ } catch (err) {
3264
+ for (const w of waiters) w.reject(err);
3265
+ throw err;
3266
+ }
3267
+ }
3268
+ /**
3269
+ * Issue the buffered writes synchronously, without awaiting them.
3270
+ *
3271
+ * For teardown paths that cannot await: `pagehide` (the page may not survive
3272
+ * a microtask) and `destroy()`. IndexedDB will not close a connection until
3273
+ * its running transactions finish, so writes issued here still land.
3274
+ */
3275
+ flushWritesSync() {
3276
+ if (this.flushTimer !== null) {
3277
+ clearTimeout(this.flushTimer);
3278
+ this.flushTimer = null;
3279
+ }
3280
+ const batch = this.writeBuffer;
3281
+ const waiters = this.writeWaiters;
3282
+ this.writeBuffer = [];
3283
+ this.writeWaiters = [];
3284
+ if (batch.length === 0) {
3285
+ for (const w of waiters) w.resolve();
3286
+ return;
3287
+ }
3288
+ const db = this.db;
3289
+ if (db) try {
3290
+ const store = db.transaction("updates", "readwrite").objectStore("updates");
3291
+ for (const update of batch) store.add(update);
3292
+ } catch {}
3293
+ for (const w of waiters) w.resolve();
2991
3294
  }
2992
3295
  async getPendingUpdates() {
3296
+ await this.flushWrites().catch(() => null);
2993
3297
  const db = await this.getDb();
2994
3298
  if (!db) return [];
2995
3299
  return new Promise((resolve, reject) => {
@@ -2999,6 +3303,13 @@ var OfflineStore = class {
2999
3303
  });
3000
3304
  }
3001
3305
  async clearPendingUpdates() {
3306
+ if (this.flushTimer !== null) {
3307
+ clearTimeout(this.flushTimer);
3308
+ this.flushTimer = null;
3309
+ }
3310
+ this.writeBuffer = [];
3311
+ for (const w of this.writeWaiters) w.resolve();
3312
+ this.writeWaiters = [];
3002
3313
  const db = await this.getDb();
3003
3314
  if (!db) return;
3004
3315
  const tx = db.transaction("updates", "readwrite");
@@ -3097,6 +3408,7 @@ var OfflineStore = class {
3097
3408
  })));
3098
3409
  }
3099
3410
  destroy() {
3411
+ this.flushWritesSync();
3100
3412
  this._destroyed = true;
3101
3413
  const db = this.db;
3102
3414
  this.db = null;
@@ -3202,8 +3514,13 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3202
3514
  }) ?? null;
3203
3515
  this.on("synced", () => this.flushPendingUpdates());
3204
3516
  this.restorePermissionSnapshot();
3205
- this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => setTimeout(resolve, 5e3))]).catch((err) => {
3517
+ let readyTimer = null;
3518
+ this.ready = Promise.race([this._initFromOfflineStore(), new Promise((resolve) => {
3519
+ readyTimer = setTimeout(resolve, 5e3);
3520
+ })]).catch((err) => {
3206
3521
  this.emit("error", { message: `Offline store init failed: ${err?.message ?? err}` });
3522
+ }).finally(() => {
3523
+ if (readyTimer !== null) clearTimeout(readyTimer);
3207
3524
  });
3208
3525
  }
3209
3526
  /**
@@ -3448,6 +3765,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3448
3765
  document: childDoc,
3449
3766
  websocketProvider: this.configuration.websocketProvider,
3450
3767
  token: this.configuration.token,
3768
+ lazyAwareness: true,
3451
3769
  subdocLoading: this.subdocLoading,
3452
3770
  disableOfflineStore: this.abracadabraConfig.disableOfflineStore,
3453
3771
  client: this._client ?? void 0,
@@ -3526,6 +3844,19 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3526
3844
  return this.childProviders;
3527
3845
  }
3528
3846
  /**
3847
+ * Land buffered offline writes before the page goes away.
3848
+ *
3849
+ * `OfflineStore` coalesces local updates into one transaction per ~150 ms
3850
+ * window (see WRITE_COALESCE_MS). That window is the only moment an edit
3851
+ * exists in memory but not on disk, and a closing tab is exactly when it
3852
+ * would be lost — so pagehide flushes it synchronously. `super.pageHide()`
3853
+ * still clears our awareness state for peers.
3854
+ */
3855
+ pageHide() {
3856
+ super.pageHide();
3857
+ this.offlineStore?.flushWritesSync();
3858
+ }
3859
+ /**
3529
3860
  * Override to persist every local update to IndexedDB before sending it
3530
3861
  * over the wire, ensuring no work is lost during connection outages.
3531
3862
  *
@@ -3573,6 +3904,7 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3573
3904
  update,
3574
3905
  documentName: this.configuration.name
3575
3906
  });
3907
+ await this.persistSnapshot();
3576
3908
  await store.clearPendingUpdates();
3577
3909
  }
3578
3910
  const pendingSubdocs = await store.getPendingSubdocs();
@@ -17477,10 +17809,24 @@ var BackgroundSyncManager = class extends EventEmitter {
17477
17809
  * @returns Cleanup function to stop the periodic sync.
17478
17810
  */
17479
17811
  startPeriodicSync(intervalMs = 300 * 1e3) {
17812
+ let missedWhileHidden = false;
17480
17813
  const handle = setInterval(() => {
17481
- if (!this._destroyed) this.syncAll().catch(() => null);
17814
+ if (this._destroyed) return;
17815
+ if (getLifecycleGate().backgrounded) {
17816
+ missedWhileHidden = true;
17817
+ return;
17818
+ }
17819
+ this.syncAll().catch(() => null);
17482
17820
  }, intervalMs);
17483
- return () => clearInterval(handle);
17821
+ const unsubscribe = getLifecycleGate().onChange((backgrounded) => {
17822
+ if (backgrounded || !missedWhileHidden || this._destroyed) return;
17823
+ missedWhileHidden = false;
17824
+ this.syncAll().catch(() => null);
17825
+ });
17826
+ return () => {
17827
+ clearInterval(handle);
17828
+ unsubscribe();
17829
+ };
17484
17830
  }
17485
17831
  /**
17486
17832
  * Clear all offline document data and sync state.
@@ -22489,6 +22835,340 @@ var DocumentManager = class {
22489
22835
  }
22490
22836
  };
22491
22837
 
22838
+ //#endregion
22839
+ //#region packages/provider/src/PerfCounters.ts
22840
+ let installed = false;
22841
+ let startedAt = 0;
22842
+ const liveTimers = /* @__PURE__ */ new Map();
22843
+ const groupCreated = /* @__PURE__ */ new Map();
22844
+ const groupFired = /* @__PURE__ */ new Map();
22845
+ let intervalsCreated = 0;
22846
+ let timeoutsCreated = 0;
22847
+ let timersFired = 0;
22848
+ let rafRequested = 0;
22849
+ let rafFired = 0;
22850
+ let idbTransactions = 0;
22851
+ let idbDatabasesOpened = 0;
22852
+ const idbByStore = /* @__PURE__ */ new Map();
22853
+ let framesSent = 0;
22854
+ let bytesSent = 0;
22855
+ let framesReceived = 0;
22856
+ let bytesReceived = 0;
22857
+ const sentByType = /* @__PURE__ */ new Map();
22858
+ let origSetInterval = null;
22859
+ let origClearInterval = null;
22860
+ let origSetTimeout = null;
22861
+ let origClearTimeout = null;
22862
+ let origRaf = null;
22863
+ let origIdbTransaction = null;
22864
+ let origIdbOpen = null;
22865
+ const socketRestores = [];
22866
+ /** The heartbeat every y-protocols Awareness instance starts: outdatedTimeout / 10. */
22867
+ const AWARENESS_HEARTBEAT_MS = 3e3;
22868
+ /**
22869
+ * Best-effort "who created this timer". Walks the stack past this module and
22870
+ * past the Node/browser internals, and reports the first frame that looks like
22871
+ * real code. Deliberately coarse: a file name is enough to tell an Awareness
22872
+ * heartbeat apart from a reconnect backoff, and anything finer would be noise.
22873
+ */
22874
+ function captureOrigin() {
22875
+ const stack = (/* @__PURE__ */ new Error()).stack;
22876
+ if (!stack) return "unknown";
22877
+ const lines = stack.split("\n").slice(1);
22878
+ for (const line of lines) {
22879
+ if (line.includes("PerfCounters")) continue;
22880
+ if (line.includes("node:internal")) continue;
22881
+ const nm = line.match(/node_modules\/(?:\.pnpm\/[^/]+\/node_modules\/)?(.+?):\d+:\d+/);
22882
+ if (nm?.[1]) return nm[1];
22883
+ const src = line.match(/([^/\\()]+\.(?:ts|mts|js|mjs)):\d+:\d+/);
22884
+ if (src?.[1]) return src[1];
22885
+ }
22886
+ return "unknown";
22887
+ }
22888
+ function groupKey(origin, delayMs) {
22889
+ return `${origin}@${delayMs}`;
22890
+ }
22891
+ function bump(map, key, by = 1) {
22892
+ map.set(key, (map.get(key) ?? 0) + by);
22893
+ }
22894
+ /**
22895
+ * Begin counting. Idempotent — a second call is a no-op rather than a
22896
+ * double-wrap, which would double every number and be very hard to notice.
22897
+ */
22898
+ function installPerfCounters() {
22899
+ if (installed) return;
22900
+ installed = true;
22901
+ startedAt = Date.now();
22902
+ const g = globalThis;
22903
+ origSetInterval = g.setInterval;
22904
+ origClearInterval = g.clearInterval;
22905
+ origSetTimeout = g.setTimeout;
22906
+ origClearTimeout = g.clearTimeout;
22907
+ g.setInterval = function patchedSetInterval(handler, delay, ...args) {
22908
+ const origin = captureOrigin();
22909
+ const delayMs = delay ?? 0;
22910
+ const key = groupKey(origin, delayMs);
22911
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22912
+ timersFired++;
22913
+ bump(groupFired, key);
22914
+ return handler(...cbArgs);
22915
+ } : handler;
22916
+ const id = origSetInterval.call(g, wrapped, delay, ...args);
22917
+ intervalsCreated++;
22918
+ bump(groupCreated, key);
22919
+ liveTimers.set(id, {
22920
+ origin,
22921
+ delayMs,
22922
+ kind: "interval"
22923
+ });
22924
+ return id;
22925
+ };
22926
+ g.clearInterval = function patchedClearInterval(id) {
22927
+ liveTimers.delete(id);
22928
+ return origClearInterval.call(g, id);
22929
+ };
22930
+ g.setTimeout = function patchedSetTimeout(handler, delay, ...args) {
22931
+ const origin = captureOrigin();
22932
+ const delayMs = delay ?? 0;
22933
+ const key = groupKey(origin, delayMs);
22934
+ let id;
22935
+ const wrapped = typeof handler === "function" ? (...cbArgs) => {
22936
+ timersFired++;
22937
+ bump(groupFired, key);
22938
+ liveTimers.delete(id);
22939
+ return handler(...cbArgs);
22940
+ } : handler;
22941
+ id = origSetTimeout.call(g, wrapped, delay, ...args);
22942
+ timeoutsCreated++;
22943
+ bump(groupCreated, key);
22944
+ liveTimers.set(id, {
22945
+ origin,
22946
+ delayMs,
22947
+ kind: "timeout"
22948
+ });
22949
+ return id;
22950
+ };
22951
+ g.clearTimeout = function patchedClearTimeout(id) {
22952
+ liveTimers.delete(id);
22953
+ return origClearTimeout.call(g, id);
22954
+ };
22955
+ if (typeof g.requestAnimationFrame === "function") {
22956
+ origRaf = g.requestAnimationFrame;
22957
+ g.requestAnimationFrame = function patchedRaf(cb) {
22958
+ rafRequested++;
22959
+ return origRaf.call(g, (t) => {
22960
+ rafFired++;
22961
+ return cb(t);
22962
+ });
22963
+ };
22964
+ }
22965
+ if (typeof g.IDBDatabase === "function") {
22966
+ origIdbTransaction = g.IDBDatabase.prototype.transaction;
22967
+ g.IDBDatabase.prototype.transaction = function patchedTransaction(storeNames, ...rest) {
22968
+ idbTransactions++;
22969
+ const names = Array.isArray(storeNames) ? storeNames : [storeNames];
22970
+ for (const n of names) bump(idbByStore, String(n));
22971
+ return origIdbTransaction.call(this, storeNames, ...rest);
22972
+ };
22973
+ }
22974
+ if (g.indexedDB && typeof g.indexedDB.open === "function") {
22975
+ origIdbOpen = g.indexedDB.open.bind(g.indexedDB);
22976
+ g.indexedDB.open = function patchedOpen(...args) {
22977
+ idbDatabasesOpened++;
22978
+ return origIdbOpen(...args);
22979
+ };
22980
+ }
22981
+ }
22982
+ /** Restore every patched global. Safe to call when not installed. */
22983
+ function uninstall() {
22984
+ if (!installed) return;
22985
+ const g = globalThis;
22986
+ if (origSetInterval) g.setInterval = origSetInterval;
22987
+ if (origClearInterval) g.clearInterval = origClearInterval;
22988
+ if (origSetTimeout) g.setTimeout = origSetTimeout;
22989
+ if (origClearTimeout) g.clearTimeout = origClearTimeout;
22990
+ if (origRaf) g.requestAnimationFrame = origRaf;
22991
+ if (origIdbTransaction && typeof g.IDBDatabase === "function") g.IDBDatabase.prototype.transaction = origIdbTransaction;
22992
+ if (origIdbOpen && g.indexedDB) g.indexedDB.open = origIdbOpen;
22993
+ for (const restore of socketRestores.splice(0)) restore();
22994
+ origSetInterval = null;
22995
+ origClearInterval = null;
22996
+ origSetTimeout = null;
22997
+ origClearTimeout = null;
22998
+ origRaf = null;
22999
+ origIdbTransaction = null;
23000
+ origIdbOpen = null;
23001
+ installed = false;
23002
+ reset();
23003
+ }
23004
+ /** Zero every counter. Live-timer bookkeeping is preserved — it is a census. */
23005
+ function reset() {
23006
+ startedAt = Date.now();
23007
+ groupCreated.clear();
23008
+ groupFired.clear();
23009
+ intervalsCreated = 0;
23010
+ timeoutsCreated = 0;
23011
+ timersFired = 0;
23012
+ rafRequested = 0;
23013
+ rafFired = 0;
23014
+ idbTransactions = 0;
23015
+ idbDatabasesOpened = 0;
23016
+ idbByStore.clear();
23017
+ framesSent = 0;
23018
+ bytesSent = 0;
23019
+ framesReceived = 0;
23020
+ bytesReceived = 0;
23021
+ sentByType.clear();
23022
+ }
23023
+ /**
23024
+ * Count frames on one AbracadabraWS. Returns a restore function; the restore is
23025
+ * also run by `uninstall()`.
23026
+ *
23027
+ * Wrapping the instance (rather than a global) is deliberate: in Node the
23028
+ * provider runs on the `ws` package, so patching `globalThis.WebSocket` would
23029
+ * silently measure nothing at all.
23030
+ */
23031
+ function instrumentSocket(socket) {
23032
+ const originalSend = socket.send.bind(socket);
23033
+ socket.send = (message) => {
23034
+ framesSent++;
23035
+ const bytes = byteLength(message);
23036
+ bytesSent += bytes;
23037
+ const type = readMessageType(message);
23038
+ if (type !== null) bump(sentByType, type);
23039
+ return originalSend(message);
23040
+ };
23041
+ const onMessage = (payload) => {
23042
+ framesReceived++;
23043
+ bytesReceived += byteLength(payload?.event?.data ?? payload?.data ?? payload);
23044
+ };
23045
+ socket.on("message", onMessage);
23046
+ const restore = () => {
23047
+ socket.send = originalSend;
23048
+ try {
23049
+ socket.off("message", onMessage);
23050
+ } catch {}
23051
+ };
23052
+ socketRestores.push(restore);
23053
+ return restore;
23054
+ }
23055
+ function byteLength(value) {
23056
+ if (!value) return 0;
23057
+ if (value instanceof Uint8Array) return value.byteLength;
23058
+ if (value instanceof ArrayBuffer) return value.byteLength;
23059
+ if (typeof value === "string") return value.length;
23060
+ const encoded = value?.toUint8Array?.() ?? value?.message;
23061
+ if (encoded instanceof Uint8Array) return encoded.byteLength;
23062
+ return 0;
23063
+ }
23064
+ /**
23065
+ * The Hocuspocus V2 frame puts a varstring document name first, then the
23066
+ * message type. We only need a stable label, so report the type byte as-is
23067
+ * rather than duplicating the wire decoder here.
23068
+ */
23069
+ function readMessageType(message) {
23070
+ const encoded = message?.toUint8Array?.() ?? message?.message ?? (message instanceof Uint8Array ? message : null);
23071
+ if (!(encoded instanceof Uint8Array) || encoded.length === 0) return null;
23072
+ let offset = 0;
23073
+ let nameLen = 0;
23074
+ let shift = 0;
23075
+ while (offset < encoded.length) {
23076
+ const byte = encoded[offset++];
23077
+ nameLen |= (byte & 127) << shift;
23078
+ if ((byte & 128) === 0) break;
23079
+ shift += 7;
23080
+ }
23081
+ const typeIndex = offset + nameLen;
23082
+ if (typeIndex >= encoded.length) return null;
23083
+ return `type:${encoded[typeIndex]}`;
23084
+ }
23085
+ function snapshot() {
23086
+ const elapsedMs = Math.max(1, Date.now() - startedAt);
23087
+ const liveByKey = /* @__PURE__ */ new Map();
23088
+ let intervalsLive = 0;
23089
+ let timeoutsLive = 0;
23090
+ let awarenessLive = 0;
23091
+ for (const rec of liveTimers.values()) {
23092
+ bump(liveByKey, groupKey(rec.origin, rec.delayMs));
23093
+ if (rec.kind === "interval") {
23094
+ intervalsLive++;
23095
+ if (isAwarenessHeartbeat(rec)) awarenessLive++;
23096
+ } else timeoutsLive++;
23097
+ }
23098
+ const groups = [...new Set([
23099
+ ...groupCreated.keys(),
23100
+ ...groupFired.keys(),
23101
+ ...liveByKey.keys()
23102
+ ])].map((key) => {
23103
+ const at = key.lastIndexOf("@");
23104
+ return {
23105
+ origin: key.slice(0, at),
23106
+ delayMs: Number(key.slice(at + 1)),
23107
+ created: groupCreated.get(key) ?? 0,
23108
+ live: liveByKey.get(key) ?? 0,
23109
+ fired: groupFired.get(key) ?? 0
23110
+ };
23111
+ }).sort((a, b) => b.live - a.live || b.fired - a.fired);
23112
+ let heartbeatFires = 0;
23113
+ for (const group of groups) if (group.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(group.origin)) heartbeatFires += group.fired;
23114
+ return {
23115
+ elapsedMs,
23116
+ timers: {
23117
+ intervalsCreated,
23118
+ intervalsLive,
23119
+ timeoutsCreated,
23120
+ timeoutsLive,
23121
+ fired: timersFired,
23122
+ firedPerSecond: Number((timersFired / elapsedMs * 1e3).toFixed(2)),
23123
+ groups
23124
+ },
23125
+ animationFrames: {
23126
+ requested: rafRequested,
23127
+ fired: rafFired
23128
+ },
23129
+ awareness: {
23130
+ liveInstances: awarenessLive,
23131
+ heartbeatFires
23132
+ },
23133
+ indexedDb: {
23134
+ transactions: idbTransactions,
23135
+ byStore: Object.fromEntries(idbByStore),
23136
+ databasesOpened: idbDatabasesOpened
23137
+ },
23138
+ sockets: {
23139
+ framesSent,
23140
+ bytesSent,
23141
+ framesReceived,
23142
+ bytesReceived,
23143
+ sentByType: Object.fromEntries(sentByType)
23144
+ }
23145
+ };
23146
+ }
23147
+ function isAwarenessOrigin(origin) {
23148
+ return origin.includes("awareness");
23149
+ }
23150
+ function isAwarenessHeartbeat(rec) {
23151
+ return rec.delayMs === AWARENESS_HEARTBEAT_MS && isAwarenessOrigin(rec.origin);
23152
+ }
23153
+ /** Field-by-field difference of two snapshots, for before/after comparisons. */
23154
+ function diff(before, after) {
23155
+ return {
23156
+ elapsedMs: after.elapsedMs - before.elapsedMs,
23157
+ timersFired: after.timers.fired - before.timers.fired,
23158
+ intervalsCreated: after.timers.intervalsCreated - before.timers.intervalsCreated,
23159
+ intervalsLive: after.timers.intervalsLive - before.timers.intervalsLive,
23160
+ awarenessLive: after.awareness.liveInstances - before.awareness.liveInstances,
23161
+ heartbeatFires: after.awareness.heartbeatFires - before.awareness.heartbeatFires,
23162
+ framesSent: after.sockets.framesSent - before.sockets.framesSent,
23163
+ bytesSent: after.sockets.bytesSent - before.sockets.bytesSent,
23164
+ idbTransactions: after.indexedDb.transactions - before.indexedDb.transactions
23165
+ };
23166
+ }
23167
+ /** Whether counting is currently active. */
23168
+ function isInstalled() {
23169
+ return installed;
23170
+ }
23171
+
22492
23172
  //#endregion
22493
23173
  exports.AbracadabraBaseProvider = AbracadabraBaseProvider;
22494
23174
  exports.AbracadabraClient = AbracadabraClient;
@@ -22525,13 +23205,16 @@ exports.FileTransferChannel = FileTransferChannel;
22525
23205
  exports.FileTransferHandle = FileTransferHandle;
22526
23206
  exports.Forbidden = Forbidden;
22527
23207
  exports.GEO_TYPE_META_SCHEMAS = GEO_TYPE_META_SCHEMAS;
23208
+ exports.HIDE_GRACE_MS = HIDE_GRACE_MS;
22528
23209
  exports.HocuspocusProvider = HocuspocusProvider;
22529
23210
  exports.HocuspocusProviderWebsocket = HocuspocusProviderWebsocket;
22530
23211
  exports.IdentityDocProvider = IdentityDocProvider;
22531
23212
  exports.KEY_EXCHANGE_CHANNEL = KEY_EXCHANGE_CHANNEL;
22532
23213
  exports.Kind = Kind;
23214
+ exports.LifecycleGate = LifecycleGate;
22533
23215
  exports.LocalStorageDeviceSessionStorage = LocalStorageDeviceSessionStorage;
22534
23216
  exports.ManualSignaling = ManualSignaling;
23217
+ exports.ManualVisibilitySource = ManualVisibilitySource;
22535
23218
  exports.MessageTooBig = MessageTooBig;
22536
23219
  exports.MessageType = MessageType;
22537
23220
  exports.MetaManager = MetaManager;
@@ -22587,6 +23270,8 @@ exports.filenameToLabel = filenameToLabel;
22587
23270
  exports.foldRecords = foldRecords;
22588
23271
  exports.forgetServerIdentity = forgetServerIdentity;
22589
23272
  exports.generateMnemonic = generateMnemonic;
23273
+ exports.getLifecycleGate = getLifecycleGate;
23274
+ exports.installPerfCounters = installPerfCounters;
22590
23275
  exports.isEncryptedContent = isEncryptedContent;
22591
23276
  exports.isPlaceholderLabel = isPlaceholderLabel;
22592
23277
  exports.isServerScopedStore = isServerScopedStore;
@@ -22605,6 +23290,10 @@ exports.normalizeRootId = normalizeRootId;
22605
23290
  exports.openSyncedProvider = openSyncedProvider;
22606
23291
  exports.parseFrontmatter = parseFrontmatter;
22607
23292
  exports.patchEntry = patchEntry;
23293
+ exports.perfCountersInstalled = isInstalled;
23294
+ exports.perfDiff = diff;
23295
+ exports.perfInstrumentSocket = instrumentSocket;
23296
+ exports.perfSnapshot = snapshot;
22608
23297
  exports.pickEntrySpace = pickEntrySpace;
22609
23298
  exports.populateYDocFromMarkdown = populateYDocFromMarkdown;
22610
23299
  exports.readAuthMessage = readAuthMessage;
@@ -22613,13 +23302,16 @@ exports.readEntries = readEntries;
22613
23302
  exports.reconcileDocCover = reconcileDocCover;
22614
23303
  exports.recordFromYAny = recordFromYAny;
22615
23304
  exports.removeServer = removeServer;
23305
+ exports.resetPerfCounters = reset;
22616
23306
  exports.resolvePageType = resolvePageType;
22617
23307
  exports.resolveServer = resolveServer;
22618
23308
  exports.saveServerRegistry = saveServerRegistry;
22619
23309
  exports.serverRegistryPath = serverRegistryPath;
22620
23310
  exports.setDefault = setDefault;
23311
+ exports.setLifecycleGate = setLifecycleGate;
22621
23312
  exports.signChallengeWithSeed = signChallengeWithSeed;
22622
23313
  exports.toPlain = toPlain;
23314
+ exports.uninstallPerfCounters = uninstall;
22623
23315
  exports.unwrapSeed = unwrapSeed;
22624
23316
  exports.validateMnemonic = validateMnemonic;
22625
23317
  exports.waitForSync = waitForSync;