ahmed-rivet-convex 2.2.6 → 2.2.8

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.
@@ -940,6 +940,9 @@ var RefCountUpdates = class {
940
940
  this.#refsCounted = this.#isLazyDelegate ? /* @__PURE__ */ new Set() : null;
941
941
  }
942
942
  async compute() {
943
+ if (!this.#isLazyDelegate) {
944
+ return this.#computeNet();
945
+ }
943
946
  for (const n of this.#newHeads) {
944
947
  await this.#changeRefCount(n, 1);
945
948
  }
@@ -977,6 +980,153 @@ var RefCountUpdates = class {
977
980
  }
978
981
  return this.#refCountUpdates;
979
982
  }
983
+ /**
984
+ * For stores that count every ref eagerly (the IndexedDB perdag). A
985
+ * persist replaces one path of a tree: the new root counts each of its
986
+ * children +1 and the old root -1, so nearly every child ends where it
987
+ * started. Counting them one by one loaded and rewrote each child's ref
988
+ * count — an IndexedDB get and put per child, ~300 of each per persist
989
+ * at 50k rows, the long-lived tab's write storm. Here deltas are summed
990
+ * first: a count is loaded only when it can matter, and only counts that
991
+ * changed (plus every put chunk, as documented) are returned. A chunk
992
+ * passes a change on to its refs when its count crosses zero — the same
993
+ * result as counting one by one.
994
+ *
995
+ * Order matters for cost, not for the result. Increments are passed on
996
+ * first and decrements held back until no increment is left: a persist
997
+ * of N writes puts a chain of N new commits whose first sits on the old
998
+ * head, so the chain's +1 reaches the old head N levels after the old
999
+ * head's own -1. Passing the -1 on at once dropped the whole old tree to
1000
+ * zero, then back.
1001
+ *
1002
+ * A +1 to a stored chunk this write did not put cannot make it newly
1003
+ * reachable: the store deletes a chunk whose count reaches 0, so every
1004
+ * chunk it holds has a count of at least 1. Such a count is not loaded
1005
+ * until the end (it is needed then only if it changed), and if it turns
1006
+ * out to be 0 after all, the change is passed on then.
1007
+ *
1008
+ * INVARIANT the assumed >= 1 shortcut depends on: the eager store deletes
1009
+ * any chunk whose count reaches 0. `StoreImpl.#applyRefCountUpdates`
1010
+ * does that for every returned entry with a count of 0
1011
+ * (`#removeAllRelatedKeys`), and it is safe that only changed counts and
1012
+ * put chunks are returned, because an unreturned count is by definition
1013
+ * unchanged and so already stored correctly. The quiescence check below
1014
+ * verifies the invariant instead of trusting it: every assumed chunk
1015
+ * whose net is not 0 is loaded, and a stored 0 is passed on as a real
1016
+ * 0 -> positive change. An assumed chunk whose net returns to 0 is never
1017
+ * loaded and never returned.
1018
+ */
1019
+ async #computeNet() {
1020
+ const delegate = this.#delegate;
1021
+ const putChunks = this.#putChunks;
1022
+ const net = /* @__PURE__ */ new Map();
1023
+ const loaded = /* @__PURE__ */ new Map();
1024
+ const propagated = /* @__PURE__ */ new Map();
1025
+ const assumed = /* @__PURE__ */ new Set();
1026
+ const held = /* @__PURE__ */ new Set();
1027
+ let dirty = /* @__PURE__ */ new Set();
1028
+ const add = (hash, delta) => {
1029
+ net.set(hash, (net.get(hash) ?? 0) + delta);
1030
+ dirty.add(hash);
1031
+ };
1032
+ const load = (hashes) => Promise.all(
1033
+ Array.from(hashes, async (hash) => {
1034
+ if (!loaded.has(hash)) {
1035
+ loaded.set(hash, await delegate.getRefCount(hash) || 0);
1036
+ }
1037
+ })
1038
+ );
1039
+ const want = (hash) => {
1040
+ const old = loaded.get(hash);
1041
+ if (old === void 0 || hash === emptyHash) {
1042
+ return 0;
1043
+ }
1044
+ const now = old + (net.get(hash) ?? 0);
1045
+ return old === 0 && now > 0 ? 1 : old > 0 && now === 0 ? -1 : 0;
1046
+ };
1047
+ const passOn = async (hashes) => {
1048
+ const changes = [];
1049
+ for (const hash of hashes) {
1050
+ const w = want(hash);
1051
+ const d = w - (propagated.get(hash) ?? 0);
1052
+ if (d !== 0) {
1053
+ propagated.set(hash, w);
1054
+ changes.push([hash, d]);
1055
+ }
1056
+ }
1057
+ const refs = await Promise.all(
1058
+ changes.map(([hash]) => delegate.getRefs(hash))
1059
+ );
1060
+ for (let i = 0; i < changes.length; i++) {
1061
+ if (!isProd) {
1062
+ assert(refs[i], "refs must be defined");
1063
+ }
1064
+ for (const ref of refs[i] ?? []) add(ref, changes[i][1]);
1065
+ }
1066
+ };
1067
+ for (const n of this.#newHeads) add(n, 1);
1068
+ for (const o of this.#oldHeads) add(o, -1);
1069
+ for (; ; ) {
1070
+ if (dirty.size > 0) {
1071
+ const current = dirty;
1072
+ dirty = /* @__PURE__ */ new Set();
1073
+ const toLoad = [];
1074
+ for (const hash of current) {
1075
+ const n = net.get(hash) ?? 0;
1076
+ if (loaded.has(hash) || n === 0) {
1077
+ continue;
1078
+ }
1079
+ if (n < 0 || putChunks.has(hash)) {
1080
+ toLoad.push(hash);
1081
+ } else {
1082
+ assumed.add(hash);
1083
+ }
1084
+ }
1085
+ await load(toLoad);
1086
+ const up = [];
1087
+ for (const hash of current) {
1088
+ const d = want(hash) - (propagated.get(hash) ?? 0);
1089
+ if (d > 0) {
1090
+ up.push(hash);
1091
+ } else if (d < 0) {
1092
+ held.add(hash);
1093
+ }
1094
+ }
1095
+ await passOn(up);
1096
+ continue;
1097
+ }
1098
+ if (held.size > 0) {
1099
+ const down = [...held];
1100
+ held.clear();
1101
+ await passOn(down);
1102
+ continue;
1103
+ }
1104
+ const unverified = [...assumed].filter(
1105
+ (hash) => !loaded.has(hash) && (net.get(hash) ?? 0) !== 0
1106
+ );
1107
+ assumed.clear();
1108
+ if (unverified.length === 0) {
1109
+ break;
1110
+ }
1111
+ await load(unverified);
1112
+ for (const hash of unverified) dirty.add(hash);
1113
+ }
1114
+ await load(putChunks);
1115
+ const updates = this.#refCountUpdates;
1116
+ for (const [hash, old] of loaded) {
1117
+ const now = old + (net.get(hash) ?? 0);
1118
+ if (now !== old || putChunks.has(hash)) {
1119
+ if (!isProd) {
1120
+ assert(
1121
+ now >= 0,
1122
+ `ref count update must be non-negative. ${hash}:${now}`
1123
+ );
1124
+ }
1125
+ updates.set(hash, now);
1126
+ }
1127
+ }
1128
+ return updates;
1129
+ }
980
1130
  async #changeRefCount(hash, delta) {
981
1131
  await this.#ensureRefCountLoaded(hash);
982
1132
  if (this.#updateRefCount(hash, delta)) {
@@ -2903,24 +3053,36 @@ var liveTransactions = /* @__PURE__ */ new Set();
2903
3053
  function txFailure(tx) {
2904
3054
  return tx.error ?? new DOMException("IndexedDB transaction aborted", "AbortError");
2905
3055
  }
2906
- var freezeReleaseInstalled = false;
2907
- function track(tx) {
2908
- if (!freezeReleaseInstalled) {
2909
- freezeReleaseInstalled = true;
2910
- globalThis.document?.addEventListener(
2911
- "freeze",
2912
- () => {
2913
- for (const open of liveTransactions) {
2914
- try {
2915
- open.abort();
2916
- } catch {
2917
- }
3056
+ var frozen;
3057
+ function whenPageResumed() {
3058
+ return frozen ? frozen.promise : promiseVoid;
3059
+ }
3060
+ function installFreezeListeners() {
3061
+ globalThis.document?.addEventListener(
3062
+ "freeze",
3063
+ () => {
3064
+ frozen ??= resolver4();
3065
+ for (const open of liveTransactions) {
3066
+ try {
3067
+ open.abort();
3068
+ } catch {
2918
3069
  }
2919
- liveTransactions.clear();
2920
- },
2921
- { capture: true }
2922
- );
2923
- }
3070
+ }
3071
+ liveTransactions.clear();
3072
+ },
3073
+ { capture: true }
3074
+ );
3075
+ globalThis.document?.addEventListener(
3076
+ "resume",
3077
+ () => {
3078
+ frozen?.resolve();
3079
+ frozen = void 0;
3080
+ },
3081
+ { capture: true }
3082
+ );
3083
+ }
3084
+ installFreezeListeners();
3085
+ function track(tx) {
2924
3086
  liveTransactions.add(tx);
2925
3087
  const done = () => liveTransactions.delete(tx);
2926
3088
  tx.addEventListener("complete", done);
@@ -3020,6 +3182,9 @@ function openDatabaseOnce(name) {
3020
3182
  var IDBNotFoundError = class extends Error {
3021
3183
  name = "IDBNotFoundError";
3022
3184
  };
3185
+ function isIDBNotFoundError(e) {
3186
+ return e instanceof IDBNotFoundError;
3187
+ }
3023
3188
 
3024
3189
  // ../replicache/src/kv/mem-store.ts
3025
3190
  import { RWLock as RWLock2 } from "@rocicorp/lock";
@@ -3257,8 +3422,8 @@ async function apply(lc, dbWrite, patch) {
3257
3422
  for (const p of patch) {
3258
3423
  switch (p.op) {
3259
3424
  case "put": {
3260
- const frozen = deepFreeze(p.value);
3261
- await dbWrite.put(lc, p.key, frozen);
3425
+ const frozen2 = deepFreeze(p.value);
3426
+ await dbWrite.put(lc, p.key, frozen2);
3262
3427
  break;
3263
3428
  }
3264
3429
  case "update": {
@@ -3278,8 +3443,8 @@ async function apply(lc, dbWrite, patch) {
3278
3443
  if (p.merge) {
3279
3444
  addToEntries(p.merge);
3280
3445
  }
3281
- const frozen = deepFreeze(Object.fromEntries(entries));
3282
- await dbWrite.put(lc, p.key, frozen);
3446
+ const frozen2 = deepFreeze(Object.fromEntries(entries));
3447
+ await dbWrite.put(lc, p.key, frozen2);
3283
3448
  break;
3284
3449
  }
3285
3450
  case "del": {
@@ -3745,7 +3910,7 @@ function makeChannelNameV1(replicacheName) {
3745
3910
  function isNewClientChannelMessageV1(message) {
3746
3911
  return typeof message === "object" && typeof message.clientGroupID === "string" && typeof message.idbName === "string";
3747
3912
  }
3748
- function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, isNewClientGroup, onUpdateNeeded, perdag) {
3913
+ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, isNewClientGroup, onUpdateNeeded, perdag, onError) {
3749
3914
  if (signal.aborted) {
3750
3915
  return;
3751
3916
  }
@@ -3756,7 +3921,7 @@ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, is
3756
3921
  channelV0.postMessage([clientGroupID]);
3757
3922
  channelV0.close();
3758
3923
  }
3759
- channelV1.onmessage = async (e) => {
3924
+ const handleMessage = async (e) => {
3760
3925
  const { data } = e;
3761
3926
  if (isNewClientChannelMessageV1(data)) {
3762
3927
  const { clientGroupID: newClientGroupID, idbName: newClientIDBName } = data;
@@ -3776,6 +3941,16 @@ function initNewClientChannel(replicacheName, idbName, signal, clientGroupID, is
3776
3941
  }
3777
3942
  }
3778
3943
  };
3944
+ channelV1.onmessage = async (e) => {
3945
+ try {
3946
+ await handleMessage(e);
3947
+ } catch (err2) {
3948
+ if (!onError) {
3949
+ throw err2;
3950
+ }
3951
+ onError(err2);
3952
+ }
3953
+ };
3779
3954
  signal.addEventListener("abort", () => channelV1.close(), { once: true });
3780
3955
  }
3781
3956
 
@@ -3824,10 +3999,10 @@ async function pendingMutationsForAPI(dagRead) {
3824
3999
  }
3825
4000
 
3826
4001
  // ../replicache/src/bg-interval.ts
3827
- function initBgIntervalProcess(processName, process2, delayMs, lc, signal) {
3828
- void runBgIntervalProcess(processName, process2, delayMs, lc, signal);
4002
+ function initBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn) {
4003
+ void runBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn);
3829
4004
  }
3830
- async function runBgIntervalProcess(processName, process2, delayMs, lc, signal) {
4005
+ async function runBgIntervalProcess(processName, process2, delayMs, lc, signal, stopOn) {
3831
4006
  if (signal.aborted) {
3832
4007
  return;
3833
4008
  }
@@ -3848,6 +4023,9 @@ async function runBgIntervalProcess(processName, process2, delayMs, lc, signal)
3848
4023
  } catch (e) {
3849
4024
  if (signal.aborted) {
3850
4025
  lc.debug?.("Error running most likely due to close.", e);
4026
+ } else if (stopOn?.(e)) {
4027
+ lc.debug?.("Stopping: every later run would fail the same way.", e);
4028
+ break;
3851
4029
  } else {
3852
4030
  lc.error?.("Error running.", e);
3853
4031
  }
@@ -3875,7 +4053,9 @@ function initClientGC(clientID, dagStore, clientMaxInactiveTime, gcInterval, onC
3875
4053
  },
3876
4054
  () => gcInterval,
3877
4055
  lc,
3878
- signal
4056
+ signal,
4057
+ // Works on this instance's own database: once it is gone, stop.
4058
+ isIDBNotFoundError
3879
4059
  );
3880
4060
  }
3881
4061
  function gcClients(clientID, dagStore, clientMaxInactiveTime, onClientsDeleted) {
@@ -3919,7 +4099,9 @@ function initClientGroupGC(dagStore, enableMutationRecovery, lc, signal) {
3919
4099
  },
3920
4100
  () => GC_INTERVAL_MS,
3921
4101
  lc,
3922
- signal
4102
+ signal,
4103
+ // Works on this instance's own database: once it is gone, stop.
4104
+ isIDBNotFoundError
3923
4105
  );
3924
4106
  }
3925
4107
  function gcClientGroups(dagStore, enableMutationRecovery) {
@@ -4161,16 +4343,22 @@ async function collectIDBDatabases(idbDatabasesStore, now, maxAge, kvDropStore,
4161
4343
  if (deletedClientsToRemove.length > 0) {
4162
4344
  let allDeletedClients = deletedClientsToRemove;
4163
4345
  for (const name of dbNamesToKeep) {
4164
- await withWrite(newDagStore(name), async (dagWrite) => {
4165
- const newDeletedClients = await addDeletedClients(
4166
- dagWrite,
4167
- deletedClientsToRemove
4168
- );
4169
- allDeletedClients = mergeDeletedClients(
4170
- allDeletedClients,
4171
- newDeletedClients
4172
- );
4173
- });
4346
+ try {
4347
+ await withWrite(newDagStore(name), async (dagWrite) => {
4348
+ const newDeletedClients = await addDeletedClients(
4349
+ dagWrite,
4350
+ deletedClientsToRemove
4351
+ );
4352
+ allDeletedClients = mergeDeletedClients(
4353
+ allDeletedClients,
4354
+ newDeletedClients
4355
+ );
4356
+ });
4357
+ } catch (e) {
4358
+ if (!isIDBNotFoundError(e)) {
4359
+ throw e;
4360
+ }
4361
+ }
4174
4362
  }
4175
4363
  const normalizedDeletedClients = normalizeDeletedClients(allDeletedClients);
4176
4364
  await onClientsDeleted(normalizedDeletedClients);
@@ -4216,7 +4404,12 @@ function gatherDatabaseInfoForCollect(db, now, maxAge, enableMutationRecovery, n
4216
4404
  return canDatabaseBeCollectedAndGetDeletedClientIDs(
4217
4405
  enableMutationRecovery,
4218
4406
  newDagStore(db.name)
4219
- );
4407
+ ).catch((e) => {
4408
+ if (isIDBNotFoundError(e)) {
4409
+ return [true, []];
4410
+ }
4411
+ throw e;
4412
+ });
4220
4413
  }
4221
4414
  async function dropDatabase(dbName, opts) {
4222
4415
  const logContext = createLogContext(opts?.logLevel, opts?.logSinks, {
@@ -4267,12 +4460,17 @@ function startHeartbeats(clientID, dagStore, onClientStateNotFound, heartbeatInt
4267
4460
  onClientStateNotFound();
4268
4461
  return;
4269
4462
  }
4463
+ if (e instanceof IDBNotFoundError && !signal.aborted) {
4464
+ onClientStateNotFound(e);
4465
+ }
4270
4466
  throw e;
4271
4467
  }
4272
4468
  },
4273
4469
  () => heartbeatIntervalMs,
4274
4470
  lc,
4275
- signal
4471
+ signal,
4472
+ // Works on this instance's own database: once it is gone, stop.
4473
+ isIDBNotFoundError
4276
4474
  );
4277
4475
  }
4278
4476
  function writeHeartbeat(clientID, dagStore) {
@@ -4344,6 +4542,16 @@ var PersistBaseMovedError = class extends Error {
4344
4542
  }
4345
4543
  name = "PersistBaseMovedError";
4346
4544
  };
4545
+ async function zeroDataOrBaseMoved(getZeroData, hash) {
4546
+ try {
4547
+ return await getZeroData(hash);
4548
+ } catch (e) {
4549
+ if (e instanceof ChunkNotFoundError) {
4550
+ throw new PersistBaseMovedError(hash, e.hash);
4551
+ }
4552
+ throw e;
4553
+ }
4554
+ }
4347
4555
  async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, formatVersion, getZeroData, onGatherMemOnlyChunksForTest = () => Promise.resolve()) {
4348
4556
  if (closed()) {
4349
4557
  return;
@@ -4413,8 +4621,8 @@ async function persistDD31(lc, clientID, memdag, perdag, mutators, closed, forma
4413
4621
  return;
4414
4622
  }
4415
4623
  let memdagBaseSnapshotPersisted = false;
4416
- const zeroDataForMemdagBaseSnapshot = getZeroData && await getZeroData(memdagBaseSnapshot.chunk.hash);
4417
- const zeroDataForPerdagHeadAtRead = getZeroData && await getZeroData(perdagHeadHashAtRead);
4624
+ const zeroDataForMemdagBaseSnapshot = getZeroData && await zeroDataOrBaseMoved(getZeroData, memdagBaseSnapshot.chunk.hash);
4625
+ const zeroDataForPerdagHeadAtRead = getZeroData && await zeroDataOrBaseMoved(getZeroData, perdagHeadHashAtRead);
4418
4626
  if (closed()) {
4419
4627
  return;
4420
4628
  }
@@ -5073,18 +5281,26 @@ var SubscriptionsManagerImpl = class {
5073
5281
  if (subs.length === 0) {
5074
5282
  return;
5075
5283
  }
5076
- const results = await this.#queryInternal(
5077
- (tx) => Promise.allSettled(
5078
- subs.map(async (s) => {
5079
- const stx = new SubscriptionTransactionWrapper(tx);
5080
- try {
5081
- return await s.invoke(stx, kind, diffs);
5082
- } finally {
5083
- s.updateDeps(stx.keys, stx.scans);
5084
- }
5085
- })
5086
- )
5087
- );
5284
+ let results;
5285
+ try {
5286
+ results = await this.#queryInternal(
5287
+ (tx) => Promise.allSettled(
5288
+ subs.map(async (s) => {
5289
+ const stx = new SubscriptionTransactionWrapper(tx);
5290
+ try {
5291
+ return await s.invoke(stx, kind, diffs);
5292
+ } finally {
5293
+ s.updateDeps(stx.keys, stx.scans);
5294
+ }
5295
+ })
5296
+ )
5297
+ );
5298
+ } catch (e) {
5299
+ if (this.#signal.aborted) {
5300
+ return;
5301
+ }
5302
+ throw e;
5303
+ }
5088
5304
  this.callCallbacks(subs, results);
5089
5305
  }
5090
5306
  // Public method so that ZQL can wrap it in a transaction.
@@ -5111,11 +5327,15 @@ var SubscriptionsManagerImpl = class {
5111
5327
  this.hasPendingSubscriptionRuns = false;
5112
5328
  const subscriptions = [...this.#pendingSubscriptions];
5113
5329
  this.#pendingSubscriptions.clear();
5114
- await this.#fireSubscriptions(
5115
- subscriptions,
5116
- InitialRun,
5117
- void 0
5118
- );
5330
+ try {
5331
+ await this.#fireSubscriptions(
5332
+ subscriptions,
5333
+ InitialRun,
5334
+ void 0
5335
+ );
5336
+ } catch (e) {
5337
+ this.#lc.error?.("Error in initial subscription run:", e);
5338
+ }
5119
5339
  }
5120
5340
  }
5121
5341
  shouldComputeDiffs() {
@@ -5301,6 +5521,7 @@ var ReplicacheImpl = class {
5301
5521
  };
5302
5522
  }
5303
5523
  #closed = false;
5524
+ #idbNotFoundReported = false;
5304
5525
  #online = true;
5305
5526
  #clientID = makeClientID();
5306
5527
  #ready;
@@ -5392,9 +5613,22 @@ var ReplicacheImpl = class {
5392
5613
  *
5393
5614
  * The default behavior is to reload the page (using `location.reload()`). Set
5394
5615
  * this to `null` or provide your own function to prevent the page from
5395
- * reloading automatically.
5616
+ * reloading automatically. The default reloads at most once per 10 seconds
5617
+ * for a given database (tracked in `sessionStorage`): a reload that lands
5618
+ * straight back here warns once and the page keeps running in memory
5619
+ * instead of looping.
5620
+ *
5621
+ * `reason` is `'idb-deleted'` when this instance's IndexedDB database was
5622
+ * deleted under it (another tab's collector dropped it, or site data was
5623
+ * cleared); it is `undefined` for the other causes.
5396
5624
  */
5397
- onClientStateNotFound = reload;
5625
+ onClientStateNotFound = () => {
5626
+ if (allowClientStateNotFoundReload(this.idbName)) {
5627
+ reload();
5628
+ } else {
5629
+ this.#warnReloadSuppressed();
5630
+ }
5631
+ };
5398
5632
  /**
5399
5633
  * `onUpdateNeeded` is called when a code update is needed.
5400
5634
  *
@@ -5561,12 +5795,18 @@ var ReplicacheImpl = class {
5561
5795
  /**
5562
5796
  * Runs one IndexedDB step of open, retrying when IndexedDB aborted its
5563
5797
  * transaction. The browser aborts transactions on events this code never
5564
- * causes — a tab being frozen (this store's own `freeze` release aborts
5798
+ * causes: a tab being frozen (this store's own `freeze` release aborts
5565
5799
  * every live transaction), storage filling up, a sibling deleting the
5566
- * database — and every step retried here is atomic (a registry read or
5567
- * put, `initClientV6`'s single perdag write), so a retry starts from a
5568
- * clean transaction. The first retry is immediate: a frozen page resumes
5569
- * straight into it. Bounded, and never after close.
5800
+ * database. Every step retried here is atomic (a registry read or put,
5801
+ * `initClientV6`'s single perdag write, Zero's `init` read — see
5802
+ * {@link ZeroOption.init}), so a retry starts from a clean transaction.
5803
+ *
5804
+ * Each retry consumes one of the {@link OPEN_IDB_RETRY_DELAYS_MS} attempts
5805
+ * of its step (attempts are per step, not per open). Before retrying, the
5806
+ * step waits for the page to resume — at most
5807
+ * {@link FREEZE_RESUME_WAIT_CAP_MS}, so a `resume` that is never delivered
5808
+ * cannot hang open — then backs off 0 / 100 / 500 / 2000 ms. Bounded, and
5809
+ * never after close.
5570
5810
  */
5571
5811
  async #retryTransientIdbAbort(step, fn) {
5572
5812
  for (let attempt = 0; ; attempt++) {
@@ -5580,6 +5820,20 @@ var ReplicacheImpl = class {
5580
5820
  `IndexedDB aborted the ${step} transaction; retry ${attempt + 1}`,
5581
5821
  e
5582
5822
  );
5823
+ const { signal } = this.#closeAbortController;
5824
+ await new Promise((resolve) => {
5825
+ const capTimer = setTimeout(resolve, FREEZE_RESUME_WAIT_CAP_MS);
5826
+ const done = () => {
5827
+ clearTimeout(capTimer);
5828
+ signal.removeEventListener("abort", done);
5829
+ resolve();
5830
+ };
5831
+ void whenPageResumed().then(done);
5832
+ signal.addEventListener("abort", done, { once: true });
5833
+ });
5834
+ if (this.#closed) {
5835
+ throw e;
5836
+ }
5583
5837
  const delay = OPEN_IDB_RETRY_DELAYS_MS[attempt];
5584
5838
  if (delay > 0) {
5585
5839
  await sleep(delay, this.#closeAbortController.signal);
@@ -5617,7 +5871,13 @@ var ReplicacheImpl = class {
5617
5871
  this.memdag,
5618
5872
  (write) => write.setHead(DEFAULT_HEAD_NAME, headHash)
5619
5873
  );
5620
- await this.#zero?.init(headHash, this.memdag);
5874
+ const zero2 = this.#zero;
5875
+ if (zero2) {
5876
+ await this.#retryTransientIdbAbort(
5877
+ "Zero init",
5878
+ () => zero2.init(headHash, this.memdag)
5879
+ );
5880
+ }
5621
5881
  resolveReady();
5622
5882
  if (this.#enablePullAndPushInOpen) {
5623
5883
  this.pull().catch(noop2);
@@ -5627,8 +5887,12 @@ var ReplicacheImpl = class {
5627
5887
  startHeartbeats(
5628
5888
  clientID,
5629
5889
  this.perdag,
5630
- () => {
5631
- this.#clientStateNotFoundOnClient(clientID);
5890
+ (cause) => {
5891
+ if (cause) {
5892
+ this.#idbNotFound(cause);
5893
+ } else {
5894
+ this.#clientStateNotFoundOnClient(clientID);
5895
+ }
5632
5896
  },
5633
5897
  HEARTBEAT_INTERVAL,
5634
5898
  this.#lc,
@@ -5664,7 +5928,14 @@ var ReplicacheImpl = class {
5664
5928
  () => {
5665
5929
  this.#fireOnUpdateNeeded(updateNeededReasonNewClientGroup);
5666
5930
  },
5667
- this.perdag
5931
+ this.perdag,
5932
+ (e) => {
5933
+ if (isIDBNotFoundError(e)) {
5934
+ this.#idbNotFound(e);
5935
+ } else {
5936
+ this.#lc.error?.("Error handling a new-client message", e);
5937
+ }
5938
+ }
5668
5939
  );
5669
5940
  setIntervalWithSignal(
5670
5941
  () => this.recoverMutations(),
@@ -5684,7 +5955,15 @@ var ReplicacheImpl = class {
5684
5955
  if (getBrowserGlobal("document")?.visibilityState !== "visible") {
5685
5956
  return;
5686
5957
  }
5687
- await this.#checkForClientStateNotFoundAndCallHandler();
5958
+ try {
5959
+ await this.#checkForClientStateNotFoundAndCallHandler();
5960
+ } catch (e) {
5961
+ if (e instanceof IDBNotFoundError) {
5962
+ this.#idbNotFound(e);
5963
+ } else {
5964
+ this.#lc.error?.("Error checking client state on visibility change", e);
5965
+ }
5966
+ }
5688
5967
  };
5689
5968
  async #checkForClientStateNotFoundAndCallHandler() {
5690
5969
  const { clientID } = this;
@@ -5697,6 +5976,14 @@ var ReplicacheImpl = class {
5697
5976
  }
5698
5977
  return !hasClientState2;
5699
5978
  }
5979
+ /**
5980
+ * `#ready` itself: resolves when open has completed (after Zero's `init`,
5981
+ * when there is one); never, if open failed. For tests that measure boot,
5982
+ * which must not read anything themselves to find out.
5983
+ */
5984
+ get readyForTesting() {
5985
+ return this.#ready;
5986
+ }
5700
5987
  /**
5701
5988
  * The browser profile ID for this browser profile. Every instance of Replicache
5702
5989
  * browser-profile-wide shares the same profile ID.
@@ -6106,6 +6393,21 @@ var ReplicacheImpl = class {
6106
6393
  const { syncHead, httpRequestInfo } = beginPullResponse;
6107
6394
  return { requestID, syncHead, ok: httpRequestInfo.httpStatusCode === 200 };
6108
6395
  }
6396
+ /**
6397
+ * Writes the in-memory state to IndexedDB.
6398
+ *
6399
+ * Behaviour change: if this instance's IndexedDB database was deleted under
6400
+ * it (another tab's collector, or cleared site data), this no longer rejects
6401
+ * with `IDBNotFoundError`. It reports the loss once through
6402
+ * `onClientStateNotFound('idb-deleted')` and resolves; nothing was persisted.
6403
+ * `refresh()` behaves the same way. Callers that need to know the write did
6404
+ * not land must use `onClientStateNotFound`.
6405
+ */
6406
+ /** Consecutive `PersistBaseMovedError` reschedules. A moved base resolves
6407
+ * on the next attempt; one that keeps "moving" is not a race any more —
6408
+ * past the cap the error is rethrown so the host's persist-failure
6409
+ * recovery sees it instead of a silent reschedule loop. */
6410
+ #persistBaseMovedStreak = 0;
6109
6411
  persist() {
6110
6412
  return this.#persistLock.withLock(async () => {
6111
6413
  const { clientID } = this;
@@ -6124,10 +6426,14 @@ var ReplicacheImpl = class {
6124
6426
  Latest,
6125
6427
  this.#zero?.getTxData
6126
6428
  );
6429
+ this.#persistBaseMovedStreak = 0;
6127
6430
  } catch (e) {
6128
6431
  if (e instanceof ClientStateNotFoundError) {
6129
6432
  this.#clientStateNotFoundOnClient(clientID);
6130
- } else if (e instanceof PersistBaseMovedError) {
6433
+ } else if (e instanceof IDBNotFoundError) {
6434
+ this.#idbNotFound(e);
6435
+ return;
6436
+ } else if (e instanceof PersistBaseMovedError && ++this.#persistBaseMovedStreak <= 5) {
6131
6437
  this.#lc.debug?.("Persist base moved; rescheduling", e.message);
6132
6438
  void this.#schedulePersist();
6133
6439
  } else if (this.#closed) {
@@ -6141,6 +6447,11 @@ var ReplicacheImpl = class {
6141
6447
  this.#onPersist({ clientID, clientGroupID });
6142
6448
  });
6143
6449
  }
6450
+ /**
6451
+ * Pulls the latest persisted state from IndexedDB. Like `persist()`, a
6452
+ * deleted database reports `onClientStateNotFound('idb-deleted')` and
6453
+ * resolves instead of rejecting.
6454
+ */
6144
6455
  async refresh() {
6145
6456
  await this.#ready;
6146
6457
  const { clientID } = this;
@@ -6163,6 +6474,8 @@ var ReplicacheImpl = class {
6163
6474
  } catch (e) {
6164
6475
  if (e instanceof ClientStateNotFoundError) {
6165
6476
  this.#clientStateNotFoundOnClient(clientID);
6477
+ } else if (e instanceof IDBNotFoundError) {
6478
+ this.#idbNotFound(e);
6166
6479
  } else if (this.#closed) {
6167
6480
  this.#lc.debug?.("Exception refreshing during close", e);
6168
6481
  } else {
@@ -6173,8 +6486,48 @@ var ReplicacheImpl = class {
6173
6486
  await this.#subscriptions.fire(refreshResult.diffs);
6174
6487
  }
6175
6488
  }
6176
- #fireOnClientStateNotFound() {
6177
- this.onClientStateNotFound?.();
6489
+ #reloadSuppressedWarned = false;
6490
+ #warnReloadSuppressed() {
6491
+ if (this.#reloadSuppressedWarned) {
6492
+ return;
6493
+ }
6494
+ this.#reloadSuppressedWarned = true;
6495
+ this.#lc.warn?.(
6496
+ `Client state not found again within ${RELOAD_LOOP_WINDOW_MS / 1e3}s of the last reload; not reloading again. This page keeps running in memory until it is reloaded.`
6497
+ );
6498
+ }
6499
+ #fireOnClientStateNotFound(reason) {
6500
+ try {
6501
+ if (reason === void 0) {
6502
+ this.onClientStateNotFound?.();
6503
+ } else {
6504
+ this.onClientStateNotFound?.(reason);
6505
+ }
6506
+ } catch (e) {
6507
+ this.#lc.error?.("onClientStateNotFound threw", e);
6508
+ }
6509
+ }
6510
+ /**
6511
+ * This instance's IndexedDB database is gone under it: another tab's
6512
+ * collector deleted it (it looked abandoned), or site data was cleared.
6513
+ * The client's state went with it, so this is the client-state-not-found
6514
+ * path, taken once: one warning, one `onClientStateNotFound`. The
6515
+ * background processes stop on their own (see `initBgIntervalProcess`).
6516
+ */
6517
+ #idbNotFound(e) {
6518
+ if (this.#closed) {
6519
+ this.#lc.debug?.("IndexedDB gone after close; ignoring.", e.message);
6520
+ return;
6521
+ }
6522
+ if (this.#idbNotFoundReported) {
6523
+ return;
6524
+ }
6525
+ this.#idbNotFoundReported = true;
6526
+ this.#lc.warn?.(
6527
+ `IndexedDB database ${this.idbName} was deleted while this client was running (another tab collected it, or site data was cleared). Its state is gone: calling onClientStateNotFound('${CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED}'), which reloads the page by default.`
6528
+ );
6529
+ this.#lc.debug?.(e);
6530
+ this.#fireOnClientStateNotFound(CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED);
6178
6531
  }
6179
6532
  #clientStateNotFoundOnClient(clientID) {
6180
6533
  this.#lc.error?.(`Client state not found on client, clientID: ${clientID}`);
@@ -6533,7 +6886,9 @@ var ReplicacheImpl = class {
6533
6886
  return withRead(this.memdag, pendingMutationsForAPI);
6534
6887
  }
6535
6888
  };
6889
+ var CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED = "idb-deleted";
6536
6890
  var OPEN_IDB_RETRY_DELAYS_MS = [0, 100, 500, 2e3];
6891
+ var FREEZE_RESUME_WAIT_CAP_MS = 1e4;
6537
6892
  function isTransientIdbAbort(e) {
6538
6893
  return typeof DOMException !== "undefined" && e instanceof DOMException && (e.name === "AbortError" || e.name === "InvalidStateError" || e.name === "TransactionInactiveError");
6539
6894
  }
@@ -6544,6 +6899,19 @@ async function throwIfError(p) {
6544
6899
  throw res.error;
6545
6900
  }
6546
6901
  }
6902
+ var RELOAD_LOOP_WINDOW_MS = 1e4;
6903
+ function allowClientStateNotFoundReload(idbName, now = Date.now()) {
6904
+ try {
6905
+ const key = `replicache-client-state-not-found-reload:${idbName}`;
6906
+ const last = Number(sessionStorage.getItem(key));
6907
+ if (last > 0 && now - last >= 0 && now - last < RELOAD_LOOP_WINDOW_MS) {
6908
+ return false;
6909
+ }
6910
+ sessionStorage.setItem(key, String(now));
6911
+ } catch {
6912
+ }
6913
+ return true;
6914
+ }
6547
6915
  function reload() {
6548
6916
  if (typeof location !== "undefined") {
6549
6917
  location.reload();
@@ -15243,7 +15611,7 @@ function makeMessage(message, context, logLevel) {
15243
15611
  }
15244
15612
 
15245
15613
  // ../zero-client/src/client/version.ts
15246
- var version2 = "2.2.6";
15614
+ var version2 = "2.2.8";
15247
15615
 
15248
15616
  // ../zero-client/src/client/log-options.ts
15249
15617
  var LevelFilterLogSink = class {
@@ -16621,6 +16989,7 @@ var ZeroRep = class {
16621
16989
  #onLocalHydrationComplete;
16622
16990
  #store;
16623
16991
  #auth;
16992
+ #initialized = false;
16624
16993
  constructor(context, ivmMain, customMutatorsEnabled, mutationTracker, onLocalHydrationComplete) {
16625
16994
  this.#context = context;
16626
16995
  this.#ivmMain = ivmMain;
@@ -16635,7 +17004,16 @@ var ZeroRep = class {
16635
17004
  this.#auth = auth;
16636
17005
  }
16637
17006
  }
17007
+ /**
17008
+ * Safe to call again: Replicache retries it when IndexedDB aborts its read
17009
+ * (a tab frozen while it boots). A call that fails applies nothing (the
17010
+ * rows are applied only after the whole read); once one has applied its
17011
+ * result, later calls do nothing.
17012
+ */
16638
17013
  async init(hash, store) {
17014
+ if (this.#initialized) {
17015
+ return;
17016
+ }
16639
17017
  const t0 = nowMs();
16640
17018
  const ts = () => Math.round(nowMs() - t0);
16641
17019
  const diffs = [];
@@ -16692,21 +17070,34 @@ var ZeroRep = class {
16692
17070
  console.log(`[ZERO-INIT] scan: ${diffs.length} entities at +${ts()}ms`);
16693
17071
  }
16694
17072
  });
16695
- this.#store = store;
16696
- const ivmT0 = nowMs();
16697
- this.#context.processChanges(void 0, hash, diffs);
16698
- if (shouldLogColdIdb()) {
16699
- logColdIdbStage("init-processChanges", {
16700
- entities: diffs.length,
16701
- ms: Math.round(nowMs() - ivmT0),
16702
- atMs: ts()
16703
- });
16704
- logColdIdbStage("init-done", { ms: ts(), entities: diffs.length });
17073
+ if (this.#initialized) {
17074
+ return;
16705
17075
  }
16706
- if (shouldLogColdIdb()) {
16707
- console.log(`[ZERO-INIT] done at +${ts()}ms`);
17076
+ this.#store = store;
17077
+ try {
17078
+ const ivmT0 = nowMs();
17079
+ this.#context.processChanges(void 0, hash, diffs);
17080
+ if (shouldLogColdIdb()) {
17081
+ logColdIdbStage("init-processChanges", {
17082
+ entities: diffs.length,
17083
+ ms: Math.round(nowMs() - ivmT0),
17084
+ atMs: ts()
17085
+ });
17086
+ logColdIdbStage("init-done", { ms: ts(), entities: diffs.length });
17087
+ }
17088
+ if (shouldLogColdIdb()) {
17089
+ console.log(`[ZERO-INIT] done at +${ts()}ms`);
17090
+ }
17091
+ this.#onLocalHydrationComplete();
17092
+ this.#initialized = true;
17093
+ } catch (e) {
17094
+ if (typeof DOMException !== "undefined" && e instanceof DOMException) {
17095
+ throw new Error(`Zero init failed applying persisted rows: ${e.name}`, {
17096
+ cause: e
17097
+ });
17098
+ }
17099
+ throw e;
16708
17100
  }
16709
- this.#onLocalHydrationComplete();
16710
17101
  }
16711
17102
  getTxData = (desiredHead, readOptions) => {
16712
17103
  if (!this.#customMutatorsEnabled) {
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Zero
3
- } from "./chunk-BKP7XQAL.js";
3
+ } from "./chunk-H4HI57GK.js";
4
4
  import {
5
5
  DEFAULT_TTL_MS
6
6
  } from "./chunk-FVFX5V7B.js";
@@ -1,3 +1,9 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
- export declare function initBgIntervalProcess(processName: string, process: () => Promise<unknown>, delayMs: () => number, lc: LogContext, signal: AbortSignal): void;
2
+ /**
3
+ * Runs `process` every `delayMs()` until `signal` aborts. A failed run is
4
+ * logged as an error and the next one runs as usual — unless `stopOn(e)`
5
+ * says the failure is permanent for this process (e.g. its database is
6
+ * gone), in which case the process stops quietly (debug log).
7
+ */
8
+ export declare function initBgIntervalProcess(processName: string, process: () => Promise<unknown>, delayMs: () => number, lc: LogContext, signal: AbortSignal, stopOn?: (e: unknown) => boolean): void;
3
9
  //# sourceMappingURL=bg-interval.d.ts.map
@@ -7,6 +7,13 @@ export declare class IDBStore implements Store {
7
7
  close(): Promise<void>;
8
8
  get closed(): boolean;
9
9
  }
10
+ /**
11
+ * Resolves at once unless the page is frozen (a `freeze` event this store
12
+ * saw, with no `resume` since); then when it resumes. Work IndexedDB
13
+ * aborted because of a freeze waits on this before trying again, so it
14
+ * does not run inside the frozen window.
15
+ */
16
+ export declare function whenPageResumed(): Promise<void>;
10
17
  /**
11
18
  * This error is thrown when we detect that the IndexedDB has been removed. This
12
19
  * does not normally happen but can happen during development if the user has
@@ -15,4 +22,5 @@ export declare class IDBStore implements Store {
15
22
  export declare class IDBNotFoundError extends Error {
16
23
  name: string;
17
24
  }
25
+ export declare function isIDBNotFoundError(e: unknown): e is IDBNotFoundError;
18
26
  //# sourceMappingURL=idb-store.d.ts.map
@@ -2,5 +2,13 @@ import type { Store } from './dag/store.ts';
2
2
  declare function makeChannelNameV0(replicacheName: string): string;
3
3
  declare function makeChannelNameV1(replicacheName: string): string;
4
4
  export { makeChannelNameV0 as makeChannelNameV0ForTesting, makeChannelNameV1 as makeChannelNameV1ForTesting, };
5
- export declare function initNewClientChannel(replicacheName: string, idbName: string, signal: AbortSignal, clientGroupID: string, isNewClientGroup: boolean, onUpdateNeeded: () => void, perdag: Store): void;
5
+ export declare function initNewClientChannel(replicacheName: string, idbName: string, signal: AbortSignal, clientGroupID: string, isNewClientGroup: boolean, onUpdateNeeded: () => void, perdag: Store,
6
+ /**
7
+ * Called with anything a message handler throws (reading the perdag can
8
+ * fail, e.g. with IDBNotFoundError once the database is gone). The
9
+ * handler is an event listener: without this, the failure would be an
10
+ * unhandled rejection. Without an `onError` the failure is rethrown, as
11
+ * before.
12
+ */
13
+ onError?: (e: unknown) => void): void;
6
14
  //# sourceMappingURL=new-client-channel.d.ts.map
@@ -1,9 +1,15 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Store } from '../dag/store.ts';
3
+ import { IDBNotFoundError } from '../kv/idb-store.ts';
3
4
  import type { ClientID } from '../sync/ids.ts';
4
5
  import { type ClientMap } from './clients.ts';
5
6
  export declare const HEARTBEAT_INTERVAL: number;
6
7
  export declare let latestHeartbeatUpdate: Promise<ClientMap> | undefined;
7
- export declare function startHeartbeats(clientID: ClientID, dagStore: Store, onClientStateNotFound: () => void, heartbeatIntervalMs: number, lc: LogContext, signal: AbortSignal): void;
8
+ export declare function startHeartbeats(clientID: ClientID, dagStore: Store,
9
+ /**
10
+ * Called with no argument when this client's entry is gone, and with the
11
+ * error when the whole database is gone (this client's state with it).
12
+ */
13
+ onClientStateNotFound: (cause?: IDBNotFoundError) => void, heartbeatIntervalMs: number, lc: LogContext, signal: AbortSignal): void;
8
14
  export declare function writeHeartbeat(clientID: ClientID, dagStore: Store): Promise<ClientMap>;
9
15
  //# sourceMappingURL=heartbeat.d.ts.map
@@ -1,7 +1,7 @@
1
1
  import type { LogContext } from '@rocicorp/logger';
2
2
  import type { Enum } from '../../../shared/src/enum.ts';
3
3
  import type { LazyStore } from '../dag/lazy-store.ts';
4
- import type { Store } from '../dag/store.ts';
4
+ import { type Store } from '../dag/store.ts';
5
5
  import * as FormatVersion from '../format-version-enum.ts';
6
6
  import type { Hash } from '../hash.ts';
7
7
  import type { ClientID } from '../sync/ids.ts';
@@ -132,9 +132,16 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
132
132
  *
133
133
  * The default behavior is to reload the page (using `location.reload()`). Set
134
134
  * this to `null` or provide your own function to prevent the page from
135
- * reloading automatically.
135
+ * reloading automatically. The default reloads at most once per 10 seconds
136
+ * for a given database (tracked in `sessionStorage`): a reload that lands
137
+ * straight back here warns once and the page keeps running in memory
138
+ * instead of looping.
139
+ *
140
+ * `reason` is `'idb-deleted'` when this instance's IndexedDB database was
141
+ * deleted under it (another tab's collector dropped it, or site data was
142
+ * cleared); it is `undefined` for the other causes.
136
143
  */
137
- onClientStateNotFound: (() => void) | null;
144
+ onClientStateNotFound: ((reason?: string) => void) | null;
138
145
  /**
139
146
  * `onUpdateNeeded` is called when a code update is needed.
140
147
  *
@@ -165,6 +172,12 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
165
172
  onBeginPull: () => undefined;
166
173
  onRecoverMutations: (r: Promise<boolean>) => Promise<boolean>;
167
174
  constructor(options: ReplicacheOptions<MD>, implOptions?: ReplicacheImplOptions);
175
+ /**
176
+ * `#ready` itself: resolves when open has completed (after Zero's `init`,
177
+ * when there is one); never, if open failed. For tests that measure boot,
178
+ * which must not read anything themselves to find out.
179
+ */
180
+ get readyForTesting(): Promise<void>;
168
181
  /**
169
182
  * The browser profile ID for this browser profile. Every instance of Replicache
170
183
  * browser-profile-wide shares the same profile ID.
@@ -257,6 +270,11 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
257
270
  poke(poke: PokeInternal): Promise<void>;
258
271
  beginPull(): Promise<BeginPullResult>;
259
272
  persist(): Promise<void>;
273
+ /**
274
+ * Pulls the latest persisted state from IndexedDB. Like `persist()`, a
275
+ * deleted database reports `onClientStateNotFound('idb-deleted')` and
276
+ * resolves instead of rejecting.
277
+ */
260
278
  refresh(): Promise<void>;
261
279
  disableClientGroup(): Promise<void>;
262
280
  /**
@@ -370,6 +388,18 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
370
388
  */
371
389
  experimentalPendingMutations(): Promise<readonly PendingMutation[]>;
372
390
  }
391
+ /**
392
+ * The `reason` `onClientStateNotFound` is called with when this instance's
393
+ * IndexedDB database was deleted under it.
394
+ */
395
+ export declare const CLIENT_STATE_NOT_FOUND_REASON_IDB_DELETED = "idb-deleted";
396
+ /**
397
+ * The longest a retry waits for a `resume` after a freeze. `frozen` is
398
+ * module-global and set by any `freeze` event, so a `resume` that is missed
399
+ * (or a synthetic `freeze` from another tool) would otherwise park open
400
+ * forever. Past the cap the retry proceeds with its ordinary backoff.
401
+ */
402
+ export declare const FREEZE_RESUME_WAIT_CAP_MS = 10000;
373
403
  /**
374
404
  * The DOMExceptions an IndexedDB call raises when the browser ended its
375
405
  * transaction underneath it — a request in an aborted transaction
@@ -378,4 +408,12 @@ export declare class ReplicacheImpl<MD extends MutatorDefs = {}> {
378
408
  * a missing store, bad data, quota on a fresh transaction — is not retried.
379
409
  */
380
410
  export declare function isTransientIdbAbort(e: unknown): boolean;
411
+ /**
412
+ * Reload loop guard for the default `onClientStateNotFound`. Records the
413
+ * reload's timestamp under a per-database `sessionStorage` key (the value
414
+ * survives the reload, which is the point) and refuses a second reload inside
415
+ * RELOAD_LOOP_WINDOW_MS. `sessionStorage` unavailable or throwing (privacy
416
+ * modes, sandboxed frames) means no guard: allow the reload, as before.
417
+ */
418
+ export declare function allowClientStateNotFoundReload(idbName: string, now?: number): boolean;
381
419
  //# sourceMappingURL=replicache-impl.d.ts.map
@@ -256,6 +256,9 @@ export interface ZeroOption {
256
256
  auth: string;
257
257
  /**
258
258
  * Allow Zero to initialize its IVM state from the given hash and dag.
259
+ *
260
+ * Called again if IndexedDB aborts the read underneath it (a tab frozen
261
+ * while it boots): apply side effects only once the read has succeeded.
259
262
  */
260
263
  init(hash: Hash, store: Store): Promise<void>;
261
264
  /**
@@ -143,10 +143,14 @@ export interface ZeroOptions<S extends Schema, MD extends CustomMutatorDefs | un
143
143
  * - the zero-cache fails to find the server side synchronization state for
144
144
  * this client.
145
145
  *
146
+ * - the local IndexedDB database was deleted while this client was running
147
+ * (another tab's collector dropped it, or site data was cleared); then
148
+ * `reason` is `'idb-deleted'`.
149
+ *
146
150
  * The default behavior is to reload the page (using `location.reload()`).
147
151
  * Provide your own function to prevent the page from reloading automatically.
148
152
  */
149
- onClientStateNotFound?: (() => void) | undefined;
153
+ onClientStateNotFound?: ((reason?: string) => void) | undefined;
150
154
  /**
151
155
  * The number of milliseconds to wait before disconnecting a Zero
152
156
  * instance whose tab has become hidden.
@@ -13,6 +13,12 @@ export declare class ZeroRep implements ZeroOption {
13
13
  #private;
14
14
  constructor(context: ZeroContext, ivmMain: IVMSourceBranch, customMutatorsEnabled: boolean, mutationTracker: MutationTracker, onLocalHydrationComplete: () => void);
15
15
  set auth(auth: string);
16
+ /**
17
+ * Safe to call again: Replicache retries it when IndexedDB aborts its read
18
+ * (a tab frozen while it boots). A call that fails applies nothing (the
19
+ * rows are applied only after the whole read); once one has applied its
20
+ * result, later calls do nothing.
21
+ */
16
22
  init(hash: Hash, store: LazyStore): Promise<void>;
17
23
  getTxData: (desiredHead: Hash, readOptions?: ZeroReadOptions | undefined) => Promise<TxData> | undefined;
18
24
  advance: (expectedHash: Hash, newHash: Hash, diffs: InternalDiff) => void;
package/dist/zero.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  number,
7
7
  string,
8
8
  table
9
- } from "./chunk-BKP7XQAL.js";
9
+ } from "./chunk-H4HI57GK.js";
10
10
  import "./chunk-FVFX5V7B.js";
11
11
 
12
12
  // src/adapters/convex.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ahmed-rivet-convex",
3
- "version": "2.2.6",
3
+ "version": "2.2.8",
4
4
  "description": "Client-only local-first data runtime for the browser: reactive queries over IndexedDB with optimistic writes.",
5
5
  "author": "Ahmed Banihani",
6
6
  "license": "Apache-2.0",