tsdf 17.0.0-beta.2 → 17.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CGfnsd9m.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CsFvYNBT.js";
2
2
  export { createAsyncStorageAdapter };
@@ -336,6 +336,14 @@ function createShouldIgnoreItemPredicate(ignoreItems, resolveItemKey) {
336
336
  function getSerializedStringSize(value) {
337
337
  return value.length;
338
338
  }
339
+ /**
340
+ * Detects browser storage quota errors thrown by `localStorage.setItem` and
341
+ * IndexedDB writes, covering the standard `QuotaExceededError` name plus the
342
+ * legacy Firefox name.
343
+ */
344
+ function isQuotaExceededError(error) {
345
+ return error instanceof DOMException && (error.name === "QuotaExceededError" || error.name === "NS_ERROR_DOM_QUOTA_REACHED");
346
+ }
339
347
  function serializeJsonForStorage(value) {
340
348
  const rawValue = JSON.stringify(value);
341
349
  return {
@@ -1425,7 +1433,11 @@ var ManagedAsyncStorageAdapter = class {
1425
1433
  }
1426
1434
  }
1427
1435
  #writeMaintenanceState(state) {
1428
- localStorage.setItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY, JSON.stringify({ lca: state.lastSuccessfulCleanupAt }));
1436
+ try {
1437
+ localStorage.setItem(ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY, JSON.stringify({ lca: state.lastSuccessfulCleanupAt }));
1438
+ } catch (error) {
1439
+ if (!isQuotaExceededError(error)) throw error;
1440
+ }
1429
1441
  }
1430
1442
  clearAllCachedReads() {
1431
1443
  this.#readCacheGeneration += 1;
@@ -1549,7 +1561,7 @@ var ManagedAsyncStorageAdapter = class {
1549
1561
  if (pending.cancelFlush !== null || pending.flushPromise !== null) return;
1550
1562
  const timeoutId = setTimeout(() => {
1551
1563
  pending.cancelFlush = null;
1552
- this.flushPendingNamespaceCommit(pending.scope);
1564
+ this.flushPendingNamespaceCommit(pending.scope).catch(() => {});
1553
1565
  }, 40);
1554
1566
  pending.cancelFlush = () => clearTimeout(timeoutId);
1555
1567
  }
@@ -1942,4 +1954,4 @@ function serializeProtectedRef(ref) {
1942
1954
  return serializeProtectedRef$1(ref);
1943
1955
  }
1944
1956
  //#endregion
1945
- export { offlineResolutionRecordSchema as A, getNamespaceId as B, OfflineResolutionConflictParseError as C, isModeEffectivelyActive as D, getIsOfflineModeFromStatus as E, warnIfNavigatorLockUnavailable as F, parsePersistedAsyncNamespaceKind as G, getPersistedNamespaceId as H, createCompactLocalStorageEntry as I, scheduleIdleCleanup as J, serializeProtectedRef$1 as K, parseCompactLocalStorageEntry as L, getSessionProtectedKeysSnapshot as M, setSessionProtectedKeysSnapshot as N, isOfflineModeStatusValue as O, getNavigatorLockManager as P, compareMetadata as R, serializeJsonForStorage as S, defaultOfflineRuntimeConfig as T, normalizeStaticPolicy as U, getPayloadRecordKey as V, parseAsyncStorageRecordKey as W, getDefaultMaxBytesForScope as _, estimateManagedAsyncStorageEntrySizeBytes as a, getSerializedStringSize as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, resolveTSDFLogger as g, getTSDFDebugTimingMs as h, createAsyncStorageAdapter as i, clearSessionProtectedKeysSnapshot as j, offlineItemEntityRefSchema as k, registerAsyncStartupStoreCleanup as l, emitTSDFDebugLog as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, logPersistentStorageQuotaCleanup as p, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS as q, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, createShouldIgnoreItemPredicate as v, compactOfflineStatusSnapshotSchema as w, keepEntriesWithinByteBudget as x, createTimedKeySet as y, encodePersistedAsyncNamespaceKind as z };
1957
+ export { offlineItemEntityRefSchema as A, encodePersistedAsyncNamespaceKind as B, serializeJsonForStorage as C, getIsOfflineModeFromStatus as D, defaultOfflineRuntimeConfig as E, getNavigatorLockManager as F, parseAsyncStorageRecordKey as G, getPayloadRecordKey as H, warnIfNavigatorLockUnavailable as I, INITIAL_MAINTENANCE_CLEANUP_DELAY_MS as J, parsePersistedAsyncNamespaceKind as K, createCompactLocalStorageEntry as L, clearSessionProtectedKeysSnapshot as M, getSessionProtectedKeysSnapshot as N, isModeEffectivelyActive as O, setSessionProtectedKeysSnapshot as P, parseCompactLocalStorageEntry as R, keepEntriesWithinByteBudget as S, compactOfflineStatusSnapshotSchema as T, getPersistedNamespaceId as U, getNamespaceId as V, normalizeStaticPolicy as W, scheduleIdleCleanup as Y, getDefaultMaxBytesForScope as _, estimateManagedAsyncStorageEntrySizeBytes as a, getSerializedStringSize as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, resolveTSDFLogger as g, getTSDFDebugTimingMs as h, createAsyncStorageAdapter as i, offlineResolutionRecordSchema as j, isOfflineModeStatusValue as k, registerAsyncStartupStoreCleanup as l, emitTSDFDebugLog as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, logPersistentStorageQuotaCleanup as p, serializeProtectedRef$1 as q, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, createShouldIgnoreItemPredicate as v, OfflineResolutionConflictParseError as w, isQuotaExceededError as x, createTimedKeySet as y, compareMetadata as z };
@@ -1,3 +1,3 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DqJXzF7M.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DC9GsYHH.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-413IafdY.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-IOCYNcQS.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-DC9GsYHH.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-IOCYNcQS.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { B as getNamespaceId, G as parsePersistedAsyncNamespaceKind, H as getPersistedNamespaceId, K as serializeProtectedRef, R as compareMetadata, S as serializeJsonForStorage, U as normalizeStaticPolicy, V as getPayloadRecordKey, W as parseAsyncStorageRecordKey, a as estimateManagedAsyncStorageEntrySizeBytes, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, z as encodePersistedAsyncNamespaceKind } from "./asyncStorageAdapter-CGfnsd9m.js";
1
+ import { B as encodePersistedAsyncNamespaceKind, C as serializeJsonForStorage, G as parseAsyncStorageRecordKey, H as getPayloadRecordKey, K as parsePersistedAsyncNamespaceKind, U as getPersistedNamespaceId, V as getNamespaceId, W as normalizeStaticPolicy, a as estimateManagedAsyncStorageEntrySizeBytes, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, q as serializeProtectedRef, z as compareMetadata } from "./asyncStorageAdapter-CsFvYNBT.js";
2
2
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
3
3
  import { isObject } from "@ls-stack/utils/typeGuards";
4
4
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as offlineResolutionRecordSchema, C as OfflineResolutionConflictParseError, D as isModeEffectivelyActive, E as getIsOfflineModeFromStatus, F as warnIfNavigatorLockUnavailable, G as parsePersistedAsyncNamespaceKind, I as createCompactLocalStorageEntry, J as scheduleIdleCleanup, K as serializeProtectedRef, L as parseCompactLocalStorageEntry, M as getSessionProtectedKeysSnapshot, N as setSessionProtectedKeysSnapshot, O as isOfflineModeStatusValue, P as getNavigatorLockManager, S as serializeJsonForStorage, T as defaultOfflineRuntimeConfig, V as getPayloadRecordKey, _ as getDefaultMaxBytesForScope, a as estimateManagedAsyncStorageEntrySizeBytes, b as getSerializedStringSize, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as resolveTSDFLogger, h as getTSDFDebugTimingMs, j as clearSessionProtectedKeysSnapshot, k as offlineItemEntityRefSchema, l as registerAsyncStartupStoreCleanup, m as emitTSDFDebugLog, o as getProtectedKeysFromMetadata, p as logPersistentStorageQuotaCleanup, q as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as createShouldIgnoreItemPredicate, w as compactOfflineStatusSnapshotSchema, x as keepEntriesWithinByteBudget, y as createTimedKeySet } from "./asyncStorageAdapter-CGfnsd9m.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-DqJXzF7M.js";
1
+ import { A as offlineItemEntityRefSchema, C as serializeJsonForStorage, D as getIsOfflineModeFromStatus, E as defaultOfflineRuntimeConfig, F as getNavigatorLockManager, H as getPayloadRecordKey, I as warnIfNavigatorLockUnavailable, J as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, K as parsePersistedAsyncNamespaceKind, L as createCompactLocalStorageEntry, M as clearSessionProtectedKeysSnapshot, N as getSessionProtectedKeysSnapshot, O as isModeEffectivelyActive, P as setSessionProtectedKeysSnapshot, R as parseCompactLocalStorageEntry, S as keepEntriesWithinByteBudget, T as compactOfflineStatusSnapshotSchema, Y as scheduleIdleCleanup, _ as getDefaultMaxBytesForScope, a as estimateManagedAsyncStorageEntrySizeBytes, b as getSerializedStringSize, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as resolveTSDFLogger, h as getTSDFDebugTimingMs, j as offlineResolutionRecordSchema, k as isOfflineModeStatusValue, l as registerAsyncStartupStoreCleanup, m as emitTSDFDebugLog, o as getProtectedKeysFromMetadata, p as logPersistentStorageQuotaCleanup, q as serializeProtectedRef, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as createShouldIgnoreItemPredicate, w as OfflineResolutionConflictParseError, x as isQuotaExceededError, y as createTimedKeySet } from "./asyncStorageAdapter-CsFvYNBT.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-413IafdY.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
@@ -270,7 +270,7 @@ const directManagedLocalStorageIo = {
270
270
  return localStorage.getItem(key);
271
271
  },
272
272
  setItem(key, value) {
273
- localStorage.setItem(key, value);
273
+ setManagedLocalStorageItemWithQuotaRecovery(key, value, directManagedLocalStorageIo);
274
274
  },
275
275
  removeItem(key) {
276
276
  localStorage.removeItem(key);
@@ -284,6 +284,163 @@ const directManagedLocalStorageIo = {
284
284
  return keys;
285
285
  }
286
286
  };
287
+ let managedLocalStorageQuotaWritesDisabled = false;
288
+ let managedLocalStorageQuotaRecoveryActive = false;
289
+ /**
290
+ * True after a `QuotaExceededError` recovery failed even with all unprotected
291
+ * TSDF entries evicted. Persistence writes are silently dropped for the rest
292
+ * of the page lifetime so a full origin quota does not produce an error on
293
+ * every subsequent flush.
294
+ */
295
+ function isLocalStorageQuotaWritesDisabled() {
296
+ return managedLocalStorageQuotaWritesDisabled;
297
+ }
298
+ /**
299
+ * Writes to `localStorage`, recovering from `QuotaExceededError` by evicting
300
+ * TSDF-managed entries: first the least recently used half of the evictable
301
+ * bytes, then everything unprotected. If the write still fails, persistence
302
+ * writes are disabled for the rest of the page lifetime and a descriptive
303
+ * error is thrown once so it reaches `onPersistentStorageError`.
304
+ *
305
+ * Returns whether the value was written (false when writes are disabled).
306
+ */
307
+ function setManagedLocalStorageItemWithQuotaRecovery(key, value, io) {
308
+ if (managedLocalStorageQuotaWritesDisabled) return false;
309
+ try {
310
+ localStorage.setItem(key, value);
311
+ return true;
312
+ } catch (error) {
313
+ if (!isQuotaExceededError(error) || managedLocalStorageQuotaRecoveryActive) throw error;
314
+ managedLocalStorageQuotaRecoveryActive = true;
315
+ try {
316
+ for (const evictAllUnprotected of [false, true]) {
317
+ runManagedLocalStorageQuotaEviction(io, evictAllUnprotected);
318
+ try {
319
+ localStorage.setItem(key, value);
320
+ return true;
321
+ } catch (retryError) {
322
+ if (!isQuotaExceededError(retryError)) throw retryError;
323
+ }
324
+ }
325
+ managedLocalStorageQuotaWritesDisabled = true;
326
+ throw new Error("[TSDF] localStorage quota exceeded and evicting stored entries did not free enough space; persistence writes are disabled until the next page load", { cause: error });
327
+ } finally {
328
+ managedLocalStorageQuotaRecoveryActive = false;
329
+ }
330
+ }
331
+ }
332
+ function getRawSizeBytes(key, io) {
333
+ const raw = io.getItem(key);
334
+ return raw === null ? 0 : getSerializedStringSize(raw);
335
+ }
336
+ /**
337
+ * Emergency cleanup for browser quota errors. Unlike the per-store `maxBytes`
338
+ * budgets (which only bound TSDF's own usage), this runs when the shared
339
+ * origin quota is exhausted, so it evicts across every TSDF session and store
340
+ * at once. Offline queue/upload data and offline-protected entries are never
341
+ * touched, and non-TSDF keys are left alone.
342
+ */
343
+ function runManagedLocalStorageQuotaEviction(io, evictAllUnprotected) {
344
+ const allKeys = io.listKeys();
345
+ const candidates = [];
346
+ const manifestOwnedPayloadKeys = /* @__PURE__ */ new Set();
347
+ const compactListQueryKeys = [];
348
+ const manifestBackedPayloadKeys = [];
349
+ for (const key of allKeys) {
350
+ const classification = classifyTsdfLocalStorageKey(key);
351
+ if (classification === null) continue;
352
+ switch (classification.kind) {
353
+ case "manifest": {
354
+ const manifestLocation = classification.manifestLocation;
355
+ const manifest = readParsedManifest(key, io);
356
+ if (!manifest) break;
357
+ const isOfflineOwned = isOfflineOwnedManifestLocation(manifestLocation);
358
+ for (const entry of manifest.entries.values()) {
359
+ const payloadKey = getPayloadKeyForManifestEntry(manifestLocation, entry.entryKey);
360
+ if (payloadKey === null) continue;
361
+ manifestOwnedPayloadKeys.add(payloadKey);
362
+ if (isOfflineOwned || isOfflineRelatedPayloadKey(payloadKey)) continue;
363
+ if (isManagedLocalStorageEntryOfflineProtected(entry.meta)) continue;
364
+ candidates.push({
365
+ payloadKey,
366
+ lastAccessAt: entry.lastAccessAt,
367
+ sizeBytes: entry.sizeBytes ?? getRawSizeBytes(payloadKey, io),
368
+ manifestKey: key,
369
+ entryKey: entry.entryKey
370
+ });
371
+ }
372
+ break;
373
+ }
374
+ case "compact-list-query":
375
+ compactListQueryKeys.push(key);
376
+ break;
377
+ case "manifest-backed-payload":
378
+ manifestBackedPayloadKeys.push(key);
379
+ break;
380
+ default: break;
381
+ }
382
+ }
383
+ for (const key of compactListQueryKeys) {
384
+ if (manifestOwnedPayloadKeys.has(key) || isOfflineRelatedPayloadKey(key)) continue;
385
+ const entry = readCompactListQueryEntry(key, io);
386
+ if (entry?.offlineProtected === true) continue;
387
+ candidates.push({
388
+ payloadKey: key,
389
+ lastAccessAt: entry?.lastAccessAt ?? 0,
390
+ sizeBytes: getRawSizeBytes(key, io),
391
+ manifestKey: null,
392
+ entryKey: void 0
393
+ });
394
+ }
395
+ for (const key of manifestBackedPayloadKeys) {
396
+ if (manifestOwnedPayloadKeys.has(key) || isOfflineRelatedPayloadKey(key)) continue;
397
+ candidates.push({
398
+ payloadKey: key,
399
+ lastAccessAt: 0,
400
+ sizeBytes: getRawSizeBytes(key, io),
401
+ manifestKey: null,
402
+ entryKey: void 0
403
+ });
404
+ }
405
+ if (candidates.length === 0) return;
406
+ candidates.sort((a, b) => a.lastAccessAt - b.lastAccessAt);
407
+ let totalBytes = 0;
408
+ for (const candidate of candidates) totalBytes += candidate.sizeBytes;
409
+ const targetBytes = evictAllUnprotected ? totalBytes : totalBytes / 2;
410
+ const removedEntryKeysByManifest = /* @__PURE__ */ new Map();
411
+ let freedBytes = 0;
412
+ for (const candidate of candidates) {
413
+ if (!evictAllUnprotected && freedBytes >= targetBytes) break;
414
+ io.removeItem(candidate.payloadKey);
415
+ freedBytes += candidate.sizeBytes;
416
+ if (candidate.manifestKey !== null) {
417
+ let removedEntryKeys = removedEntryKeysByManifest.get(candidate.manifestKey);
418
+ if (!removedEntryKeys) {
419
+ removedEntryKeys = /* @__PURE__ */ new Set();
420
+ removedEntryKeysByManifest.set(candidate.manifestKey, removedEntryKeys);
421
+ }
422
+ removedEntryKeys.add(candidate.entryKey);
423
+ }
424
+ }
425
+ for (const [manifestKey, removedEntryKeys] of removedEntryKeysByManifest) {
426
+ const manifest = readParsedManifest(manifestKey, io);
427
+ if (!manifest) continue;
428
+ const nextEntries = new Map(manifest.entries);
429
+ for (const entryKey of removedEntryKeys) nextEntries.delete(entryKey);
430
+ try {
431
+ writeManifest(manifestKey, { entries: nextEntries }, io);
432
+ } catch (error) {
433
+ if (!isQuotaExceededError(error)) throw error;
434
+ }
435
+ }
436
+ }
437
+ function isOfflineOwnedManifestLocation(manifestLocation) {
438
+ if (manifestLocation.kind === "single") return manifestLocation.payloadKey.includes("._o_.");
439
+ return manifestLocation.storagePrefix.endsWith(".oq.") || manifestLocation.storagePrefix.endsWith(".oc.") || manifestLocation.storagePrefix.endsWith(".oe.");
440
+ }
441
+ function isOfflineRelatedPayloadKey(payloadKey) {
442
+ return payloadKey.includes("._o_.");
443
+ }
287
444
  function getManagedLocalStorageRuntimeConfig() {
288
445
  return managedLocalStorageRuntimeConfig;
289
446
  }
@@ -1006,7 +1163,11 @@ function createCachedManagedLocalStorageIo() {
1006
1163
  }
1007
1164
  if (pendingManifestWrites.size === 0) return;
1008
1165
  for (const [key, value] of pendingManifestWrites) if (value === null) localStorage.removeItem(key);
1009
- else localStorage.setItem(key, value);
1166
+ else try {
1167
+ setManagedLocalStorageItemWithQuotaRecovery(key, value, io);
1168
+ } catch (error) {
1169
+ console.error(error);
1170
+ }
1010
1171
  pendingManifestWrites.clear();
1011
1172
  }
1012
1173
  function schedulePendingManifestFlush() {
@@ -1016,49 +1177,49 @@ function createCachedManagedLocalStorageIo() {
1016
1177
  flushPendingManifestWrites();
1017
1178
  });
1018
1179
  }
1180
+ const io = {
1181
+ getItem(key) {
1182
+ if (!active) return localStorage.getItem(key);
1183
+ if (cache.has(key)) {
1184
+ const cachedValue = cache.get(key);
1185
+ if (cachedValue !== VALUE_NOT_LOADED) return cachedValue ?? null;
1186
+ }
1187
+ const raw = localStorage.getItem(key);
1188
+ cache.set(key, raw);
1189
+ return raw;
1190
+ },
1191
+ setItem(key, value) {
1192
+ if (setManagedLocalStorageItemWithQuotaRecovery(key, value, io) && active) cache.set(key, value);
1193
+ },
1194
+ removeItem(key) {
1195
+ if (active) cache.set(key, null);
1196
+ localStorage.removeItem(key);
1197
+ },
1198
+ listKeys() {
1199
+ if (!active) return directManagedLocalStorageIo.listKeys();
1200
+ loadAllKeys();
1201
+ const keys = [];
1202
+ for (const [key, value] of cache.entries()) if (value !== null) keys.push(key);
1203
+ return keys;
1204
+ },
1205
+ queueManifestWrite(key, value) {
1206
+ if (!active) {
1207
+ if (value === null) localStorage.removeItem(key);
1208
+ else setManagedLocalStorageItemWithQuotaRecovery(key, value, directManagedLocalStorageIo);
1209
+ return;
1210
+ }
1211
+ cache.set(key, value);
1212
+ pendingManifestWrites.set(key, value);
1213
+ schedulePendingManifestFlush();
1214
+ }
1215
+ };
1019
1216
  return {
1020
1217
  deactivate() {
1021
1218
  flushPendingManifestWrites();
1022
1219
  active = false;
1023
1220
  cache.clear();
1024
1221
  },
1025
- io: {
1026
- getItem(key) {
1027
- if (!active) return localStorage.getItem(key);
1028
- if (cache.has(key)) {
1029
- const cachedValue = cache.get(key);
1030
- if (cachedValue !== VALUE_NOT_LOADED) return cachedValue ?? null;
1031
- }
1032
- const raw = localStorage.getItem(key);
1033
- cache.set(key, raw);
1034
- return raw;
1035
- },
1036
- setItem(key, value) {
1037
- if (active) cache.set(key, value);
1038
- localStorage.setItem(key, value);
1039
- },
1040
- removeItem(key) {
1041
- if (active) cache.set(key, null);
1042
- localStorage.removeItem(key);
1043
- },
1044
- listKeys() {
1045
- if (!active) return directManagedLocalStorageIo.listKeys();
1046
- loadAllKeys();
1047
- const keys = [];
1048
- for (const [key, value] of cache.entries()) if (value !== null) keys.push(key);
1049
- return keys;
1050
- },
1051
- queueManifestWrite(key, value) {
1052
- if (!active) {
1053
- if (value === null) localStorage.removeItem(key);
1054
- else localStorage.setItem(key, value);
1055
- return;
1056
- }
1057
- cache.set(key, value);
1058
- pendingManifestWrites.set(key, value);
1059
- schedulePendingManifestFlush();
1060
- }
1061
- }
1222
+ io
1062
1223
  };
1063
1224
  }
1064
1225
  async function withManagedLocalStorageIoCache(callback) {
@@ -1495,6 +1656,10 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1495
1656
  if (import.meta.env.DEV) logPersistentStorageOperation(withPersistentStorageDebugKey(debugContext, key), "write", "skipped", startTime, { reason: "inactive-session" });
1496
1657
  return;
1497
1658
  }
1659
+ if (isLocalStorageQuotaWritesDisabled()) {
1660
+ if (import.meta.env.DEV) logPersistentStorageOperation(withPersistentStorageDebugKey(debugContext, key), "write", "skipped", startTime, { reason: "quota-writes-disabled" });
1661
+ return;
1662
+ }
1498
1663
  const timestamp = Date.now();
1499
1664
  const entry = createCompactLocalStorageEntry(localCodec.serialize(data), version);
1500
1665
  await runLocalStorageMutation(() => {
@@ -1658,6 +1823,13 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
1658
1823
  });
1659
1824
  return;
1660
1825
  }
1826
+ if (isLocalStorageQuotaWritesDisabled()) {
1827
+ if (import.meta.env.DEV) logPersistentStorageOperation(debugContext, "commit", "skipped", startTime, {
1828
+ ...operationDetails,
1829
+ reason: "quota-writes-disabled"
1830
+ });
1831
+ return;
1832
+ }
1661
1833
  const now = Date.now();
1662
1834
  const touchTimestamps = new Map((args.touches ?? []).map((touch) => [touch.key, touch.lastAccessAt]));
1663
1835
  await runLocalStorageMutation(() => {
@@ -2176,7 +2348,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2176
2348
  }
2177
2349
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2178
2350
  async function clearAllSessionStorage(sessionKey) {
2179
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-BpfM2_Y6.js");
2351
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Bz2Ni2XW.js");
2180
2352
  await Promise.all([
2181
2353
  clearSessionStorage(sessionKey, "local-sync"),
2182
2354
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -7427,9 +7599,7 @@ var RequestScheduler = class {
7427
7599
  if (existing) clearTimeout(existing.timeoutId);
7428
7600
  this.#state.pending.rtuDelayed.set(requestId, {
7429
7601
  timeoutId: setTimeout(() => {
7430
- this.#state.pending.rtuDelayed.delete(requestId);
7431
- this.#onEvent?.("scheduled-rt-fetch-started");
7432
- this.#scheduleRequest(requestId, "highPriority", payload, void 0, remoteStartCancelable);
7602
+ this.#executeDelayedRTUFetch(requestId);
7433
7603
  }, delay),
7434
7604
  requestId,
7435
7605
  payload,
@@ -7441,6 +7611,16 @@ var RequestScheduler = class {
7441
7611
  this.#onEvent?.("rt-fetch-scheduled", { delayMs: delay });
7442
7612
  return true;
7443
7613
  }
7614
+ /** Executes from the current delayed entry, not from the args captured when
7615
+ * the timeout was created — realtime updates arriving during the delay
7616
+ * coalesce their payloads into the entry. */
7617
+ #executeDelayedRTUFetch(requestId) {
7618
+ const delayedRequest = this.#state.pending.rtuDelayed.get(requestId);
7619
+ if (!delayedRequest) return;
7620
+ this.#state.pending.rtuDelayed.delete(requestId);
7621
+ this.#onEvent?.("scheduled-rt-fetch-started");
7622
+ this.#scheduleRequest(requestId, "highPriority", delayedRequest.payload, void 0, delayedRequest.remoteStartCancelable);
7623
+ }
7444
7624
  #handleMediumPriority(requestId, payload, startTime, customDelayMs, remoteStartCancelable) {
7445
7625
  const delayMs = customDelayMs ?? this.#mediumPriorityDelayMs;
7446
7626
  if (delayMs === void 0) throw new Error("[tsdf] mediumPriorityDelayMs must be configured to use mediumPriority fetch type");
@@ -11966,6 +12146,24 @@ function getFallbackMissingRequestedFields(fallbackItemState, requestedFields, i
11966
12146
  return missingLoadedFields.filter((field) => !inferredFields.includes(field));
11967
12147
  }
11968
12148
  /**
12149
+ * Fields from `requestedFields` that are genuinely absent from the snapshot —
12150
+ * not tracked as loaded, not vouched by `inferFields`, and not merely stale
12151
+ * (awaiting an invalidation re-fetch). Stale fields were loaded when their
12152
+ * invalidation was recorded, so their stale data is still present and may stay
12153
+ * visible while the re-fetch runs; only genuinely absent fields have no data
12154
+ * to show. Staleness is proven either by the field being in the unresolved
12155
+ * pending invalidation list, or — for an item with data still present — by the
12156
+ * unresolved full ('*') invalidation marker, which means the snapshot was
12157
+ * complete when invalidated.
12158
+ */
12159
+ function getGenuinelyMissingRequestedFields(itemKey, fallbackItemState, requestedFields, inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields) {
12160
+ const fallbackMissingFields = getFallbackMissingRequestedFields(fallbackItemState, requestedFields, inferFields);
12161
+ if (fallbackMissingFields.length === 0) return fallbackMissingFields;
12162
+ if (itemsPendingFullInvalidation.has(itemKey) && fallbackItemState?.item) return [];
12163
+ if (unresolvedPendingInvalidationFields.length === 0) return fallbackMissingFields;
12164
+ return fallbackMissingFields.filter((field) => !unresolvedPendingInvalidationFields.includes(field));
12165
+ }
12166
+ /**
11969
12167
  * Returns the fields from `requestedFields` that are not yet present in
11970
12168
  * `loadedFields`. When either argument is `undefined` or empty, returns `[]`.
11971
12169
  */
@@ -13059,7 +13257,7 @@ const GET_ALL = () => true;
13059
13257
  //#endregion
13060
13258
  //#region src/listQueryStore/createMutationApi.ts
13061
13259
  /** @internal */
13062
- function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation) {
13260
+ function createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, onMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, emitInvalidateQuery, emitInvalidateItem, blockWindowClose, offlineController, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, onOfflineTimelineEvent, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations) {
13063
13261
  const storeEvents = evtmitter();
13064
13262
  const deferredOptimisticQueryInvalidationsStack = [];
13065
13263
  const optimisticMutationQueryContextStack = [];
@@ -13119,6 +13317,25 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13119
13317
  const queryInvalidationWasTriggered = /* @__PURE__ */ new Set();
13120
13318
  const itemInvalidationWasTriggered = /* @__PURE__ */ new Set();
13121
13319
  const itemFieldInvalidationPriorities = /* @__PURE__ */ new Map();
13320
+ /**
13321
+ * The staleness baseline for invalidations: a field is invalidatable
13322
+ * exactly when it is displayable, and hooks display the UNION of the
13323
+ * tracked `itemLoadedFields` metadata and whatever `inferFields` currently
13324
+ * vouches for (e.g. fields a mutation wrote beyond the tracked metadata).
13325
+ * Collapses to '*' when either side is '*' — the displayable set is then
13326
+ * not enumerable.
13327
+ */
13328
+ function getInvalidationBaselineFields(itemKey) {
13329
+ const trackedLoadedFields = store.state.itemLoadedFields[itemKey];
13330
+ if (trackedLoadedFields === "*") return "*";
13331
+ if (!partialResources) return trackedLoadedFields;
13332
+ const itemState = store.state.items[itemKey];
13333
+ if (!itemState) return trackedLoadedFields;
13334
+ const inferredFields = partialResources.inferFields(itemState);
13335
+ if (inferredFields === "*") return "*";
13336
+ if (!trackedLoadedFields || trackedLoadedFields.length === 0) return inferredFields;
13337
+ return Array.from(new Set([...trackedLoadedFields, ...inferredFields]));
13338
+ }
13122
13339
  function invalidateQueryAndItems(args) {
13123
13340
  const itemPayload = args.all ? GET_ALL : args.itemPayload;
13124
13341
  const queryPayload = args.all ? GET_ALL : args.queryPayload;
@@ -13146,29 +13363,49 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13146
13363
  const itemsKey = getItemsKeyArray(itemPayload);
13147
13364
  const nextInvalidationPriorityByItemKey = /* @__PURE__ */ new Map();
13148
13365
  const nextPendingInvalidationFieldsByItemKey = /* @__PURE__ */ new Map();
13366
+ const staleInvalidateFieldsByItemKey = /* @__PURE__ */ new Map();
13149
13367
  for (const { itemKey } of itemsKey) {
13368
+ const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
13369
+ const staleInvalidateFields = effectiveLoadedFields === "*" ? invalidateFields : invalidateFields.filter((field) => effectiveLoadedFields?.includes(field) ?? false);
13370
+ if (staleInvalidateFields.length < invalidateFields.length) {
13371
+ let droppedForItem = itemDroppedFieldInvalidations.get(itemKey);
13372
+ for (const field of invalidateFields) {
13373
+ if (staleInvalidateFields.includes(field)) continue;
13374
+ if (!droppedForItem) {
13375
+ droppedForItem = /* @__PURE__ */ new Map();
13376
+ itemDroppedFieldInvalidations.set(itemKey, droppedForItem);
13377
+ }
13378
+ const existingDropped = droppedForItem.get(field);
13379
+ droppedForItem.set(field, {
13380
+ invalidatedAt: Date.now(),
13381
+ priority: existingDropped && fetchTypePriority[existingDropped.priority] > fetchTypePriority[priority] ? existingDropped.priority : priority
13382
+ });
13383
+ }
13384
+ }
13385
+ if (staleInvalidateFields.length === 0) continue;
13386
+ staleInvalidateFieldsByItemKey.set(itemKey, staleInvalidateFields);
13150
13387
  const existingPriority = itemFieldInvalidationPriorities.get(itemKey);
13151
13388
  const existingPendingFields = itemPendingInvalidationFields.get(itemKey) ?? [];
13152
- nextPendingInvalidationFieldsByItemKey.set(itemKey, Array.from(new Set([...existingPendingFields, ...invalidateFields])).sort());
13389
+ nextPendingInvalidationFieldsByItemKey.set(itemKey, Array.from(new Set([...existingPendingFields, ...staleInvalidateFields])).sort());
13153
13390
  nextInvalidationPriorityByItemKey.set(itemKey, existingPriority && fetchTypePriority[existingPriority] > fetchTypePriority[priority] ? existingPriority : priority);
13154
13391
  }
13155
13392
  for (const [itemKey, itemPriority] of nextInvalidationPriorityByItemKey) itemFieldInvalidationPriorities.set(itemKey, itemPriority);
13156
13393
  for (const [itemKey, invalidationFields] of nextPendingInvalidationFieldsByItemKey) itemPendingInvalidationFields.set(itemKey, invalidationFields);
13157
13394
  store.produceState((draft) => {
13158
- for (const { itemKey } of itemsKey) {
13395
+ for (const [itemKey, staleInvalidateFields] of staleInvalidateFieldsByItemKey) {
13159
13396
  const loadedFields = draft.itemLoadedFields[itemKey];
13160
13397
  if (!loadedFields) continue;
13161
- if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !invalidateFields.includes(f));
13398
+ if (loadedFields !== "*") draft.itemLoadedFields[itemKey] = loadedFields.filter((f) => !staleInvalidateFields.includes(f));
13162
13399
  const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13163
- draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...invalidateFields])).sort();
13400
+ draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...staleInvalidateFields])).sort();
13164
13401
  }
13165
13402
  }, { action: "invalidate-item-fields" });
13166
- for (const { itemKey } of itemsKey) {
13403
+ for (const [itemKey, staleInvalidateFields] of staleInvalidateFieldsByItemKey) {
13167
13404
  itemInvalidationWasTriggered.delete(itemKey);
13168
13405
  emitInvalidateItem({
13169
13406
  priority: nextInvalidationPriorityByItemKey.get(itemKey) ?? priority,
13170
13407
  itemKey,
13171
- invalidateFields
13408
+ invalidateFields: staleInvalidateFields
13172
13409
  });
13173
13410
  }
13174
13411
  } else invalidateItem(itemPayload, priority);
@@ -13179,11 +13416,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13179
13416
  for (const { itemKey, payload } of itemsKey) {
13180
13417
  const item = store.state.itemQueries[itemKey];
13181
13418
  if (!item) continue;
13182
- let effectiveLoadedFields = store.state.itemLoadedFields[itemKey];
13183
- if (partialResources && effectiveLoadedFields === void 0) {
13184
- const itemState = store.state.items[itemKey];
13185
- if (itemState) effectiveLoadedFields = partialResources.inferFields(itemState);
13186
- }
13419
+ const effectiveLoadedFields = getInvalidationBaselineFields(itemKey);
13187
13420
  const itemWasFullyLoaded = partialResources && effectiveLoadedFields === "*";
13188
13421
  const trackedInvalidationFields = partialResources && !itemWasFullyLoaded ? Array.from(new Set([...effectiveLoadedFields === "*" ? [] : effectiveLoadedFields ?? [], ...itemPendingInvalidationFields.get(itemKey) ?? []])).sort() : [];
13189
13422
  const trackedInvalidationPriority = trackedInvalidationFields.length > 0 || itemsPendingFullInvalidation.has(itemKey) ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
@@ -13224,6 +13457,55 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13224
13457
  }
13225
13458
  }
13226
13459
  }
13460
+ /**
13461
+ * Called when a fetch settles for `itemKeys` (item fetches and list fetches
13462
+ * that committed the items). Per-field invalidations of never-loaded fields
13463
+ * are dropped at invalidation time (see `invalidateQueryAndItems`) — but a
13464
+ * fetch that STARTED BEFORE such an invalidation commits a response
13465
+ * produced before it, so the just-loaded value may already be stale.
13466
+ * Re-announce those invalidations as a regular per-field invalidation (the
13467
+ * field now has a displayable value). Fields loaded by a fetch started
13468
+ * after the invalidation are fresh relative to it — their record is simply
13469
+ * discarded.
13470
+ */
13471
+ function reannounceInvalidationsDroppedDuringFetch(itemKeys, fetchStartedAt) {
13472
+ for (const itemKey of itemKeys) {
13473
+ const droppedForItem = itemDroppedFieldInvalidations.get(itemKey);
13474
+ if (!droppedForItem) continue;
13475
+ const loadedFields = store.state.itemLoadedFields[itemKey];
13476
+ let staleFields;
13477
+ let stalePriority;
13478
+ for (const [field, dropped] of droppedForItem) {
13479
+ if (!(loadedFields === "*" || (loadedFields?.includes(field) ?? false))) continue;
13480
+ droppedForItem.delete(field);
13481
+ if (dropped.invalidatedAt > fetchStartedAt) {
13482
+ (staleFields ??= []).push(field);
13483
+ if (!stalePriority || fetchTypePriority[dropped.priority] > fetchTypePriority[stalePriority]) stalePriority = dropped.priority;
13484
+ }
13485
+ }
13486
+ if (droppedForItem.size === 0) itemDroppedFieldInvalidations.delete(itemKey);
13487
+ if (!staleFields || !stalePriority) continue;
13488
+ const existingPriority = itemFieldInvalidationPriorities.get(itemKey);
13489
+ const mergedPriority = existingPriority && fetchTypePriority[existingPriority] > fetchTypePriority[stalePriority] ? existingPriority : stalePriority;
13490
+ const existingPendingFields = itemPendingInvalidationFields.get(itemKey) ?? [];
13491
+ itemPendingInvalidationFields.set(itemKey, Array.from(new Set([...existingPendingFields, ...staleFields])).sort());
13492
+ itemFieldInvalidationPriorities.set(itemKey, mergedPriority);
13493
+ const staleFieldsToApply = staleFields;
13494
+ store.produceState((draft) => {
13495
+ const draftLoadedFields = draft.itemLoadedFields[itemKey];
13496
+ if (!draftLoadedFields) return;
13497
+ if (draftLoadedFields !== "*") draft.itemLoadedFields[itemKey] = draftLoadedFields.filter((f) => !staleFieldsToApply.includes(f));
13498
+ const existingInvalidationFields = draft.itemFieldInvalidationFields[itemKey] ?? [];
13499
+ draft.itemFieldInvalidationFields[itemKey] = Array.from(new Set([...existingInvalidationFields, ...staleFieldsToApply])).sort();
13500
+ }, { action: "invalidate-item-fields" });
13501
+ itemInvalidationWasTriggered.delete(itemKey);
13502
+ emitInvalidateItem({
13503
+ priority: mergedPriority,
13504
+ itemKey,
13505
+ invalidateFields: staleFields
13506
+ });
13507
+ }
13508
+ }
13227
13509
  function startItemMutation(itemId) {
13228
13510
  const itemsKey = getItemsKeyArray(itemId);
13229
13511
  const endMutations = [];
@@ -13428,6 +13710,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13428
13710
  itemFieldInvalidationPriorities.delete(itemKey);
13429
13711
  itemPendingInvalidationFields.delete(itemKey);
13430
13712
  itemsPendingFullInvalidation.delete(itemKey);
13713
+ itemDroppedFieldInvalidations.delete(itemKey);
13431
13714
  itemInvalidationWasTriggered.delete(itemKey);
13432
13715
  publishItemSnapshot(itemKey);
13433
13716
  }
@@ -13440,6 +13723,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13440
13723
  itemFieldInvalidationPriorities.clear();
13441
13724
  itemPendingInvalidationFields.clear();
13442
13725
  itemsPendingFullInvalidation.clear();
13726
+ itemDroppedFieldInvalidations.clear();
13443
13727
  }
13444
13728
  async function performMutation(payload, { optimisticUpdate, mutation, silentErrors, revalidateOnSuccess, onSuccess, onError, debounce, offline, upload }) {
13445
13729
  const payloadToUse = payload === null ? [] : payload;
@@ -13521,6 +13805,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
13521
13805
  itemFieldInvalidationPriorities,
13522
13806
  invalidateQueryAndItems,
13523
13807
  invalidateItem,
13808
+ reannounceInvalidationsDroppedDuringFetch,
13524
13809
  startItemMutation,
13525
13810
  updateItemState,
13526
13811
  addItemToState,
@@ -13922,10 +14207,10 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13922
14207
  const fetchQueriesWithId = shouldDebounceFetchQueries ? debouncedFetchQueriesWithId : queriesWithId;
13923
14208
  const offlineEntitiesByKey = useMemo(() => createOfflineEntityLookup(offlineEntities), [offlineEntities]);
13924
14209
  const activeOfflineOverlays = useMemo(() => filterActiveOfflineOverlays(offlineEntitiesByKey, offlineOverlays), [offlineEntitiesByKey, offlineOverlays]);
13925
- const getUnresolvedPendingInvalidationFields = useCallback((itemKey) => {
13926
- const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
14210
+ const getUnresolvedPendingInvalidationFields = useCallback((itemKey, state) => {
14211
+ const stateInvalidationFields = (state ? state.itemFieldInvalidationFields : store.state.itemFieldInvalidationFields)[itemKey];
13927
14212
  if (stateInvalidationFields && stateInvalidationFields.length > 0) return stateInvalidationFields;
13928
- return excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
14213
+ return excludeLoadedFields((state ? state.itemLoadedFields : store.state.itemLoadedFields)[itemKey], itemPendingInvalidationFields.get(itemKey));
13929
14214
  }, [itemPendingInvalidationFields, store]);
13930
14215
  const resultSelector = useCallback((state) => {
13931
14216
  return queriesWithId.map(({ itemKey, payload, fields, returnIdleStatus, returnRefetchingStatus, showPartialAsRefetching, queryMetadata }) => {
@@ -13988,10 +14273,10 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
13988
14273
  let status = itemQuery.status;
13989
14274
  const itemFieldInvalidationFields = state.itemFieldInvalidationFields[itemKey];
13990
14275
  if (partialResources && Array.isArray(fields) && fields.length > 0 && (status === "success" || status === "refetching")) {
13991
- if (getFallbackMissingRequestedFields({
14276
+ if (getGenuinelyMissingRequestedFields(itemKey, {
13992
14277
  item: rawItemState,
13993
14278
  loadedFields
13994
- }, fields, partialResources.inferFields).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
14279
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0) status = hasCachedDataInState && showPartialAsRefetching ? "refetching" : "loading";
13995
14280
  } else if (partialResources && fields === "*" && (status === "success" || status === "refetching")) {
13996
14281
  const isIncomplete = !snapshotIsFullyLoaded(loadedFields, rawItemState, partialResources.inferFields) && !(itemsPendingFullInvalidation.has(itemKey) && hasCachedDataInState);
13997
14282
  const isStale = !isIncomplete && !snapshotIsFullyLoadedAndFresh(itemKey, loadedFields, rawItemState, partialResources.inferFields, itemsPendingFullInvalidation);
@@ -14000,7 +14285,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14000
14285
  }
14001
14286
  if (partialResources && showPartialAsRefetching) {
14002
14287
  if (Array.isArray(fields) && fields.length > 0) {
14003
- const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey));
14288
+ const pendingRequestedFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, rawItemState, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state));
14004
14289
  if (pendingRequestedFields.length > 0) loadingFields = pendingRequestedFields;
14005
14290
  } else if (fields === "*") {
14006
14291
  if (hasFullyLoadedFields(loadedFields) && itemFieldInvalidationFields && itemFieldInvalidationFields.length > 0) loadingFields = itemFieldInvalidationFields;
@@ -14035,7 +14320,7 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14035
14320
  return queriesWithId.map(({ itemKey, fields }) => {
14036
14321
  const itemQuery = state.itemQueries[itemKey];
14037
14322
  const loadedFields = state.itemLoadedFields[itemKey] ?? [];
14038
- const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).sort() : [];
14323
+ const missingRequestedFields = partialResources && Array.isArray(fields) && fields.length > 0 ? getStaleOrMissingRequestedFields(itemKey, state.itemLoadedFields[itemKey], state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).sort() : [];
14039
14324
  const needsFullFetch = partialResources && fields === "*" ? !snapshotIsFullyLoaded(loadedFields, state.items[itemKey], partialResources.inferFields) || itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) : false;
14040
14325
  return {
14041
14326
  status: itemQuery?.status ?? null,
@@ -14123,23 +14408,42 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14123
14408
  store,
14124
14409
  visibleStoreState
14125
14410
  ]);
14411
+ const ignoreItemsInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
14126
14412
  useOnEvtmitterEvent(events, "invalidateItem", ({ payload: event }) => {
14127
14413
  if (loadFromStateOnly || !fetchItemFn) return;
14128
- const matchingQueries = fetchQueriesWithId.filter(({ itemKey, isOffScreen }) => !isOffScreen && itemKey === event.itemKey);
14414
+ const queriesForItem = fetchQueriesWithId.filter(({ itemKey }) => itemKey === event.itemKey);
14415
+ let fieldsToFetch;
14416
+ if (event.invalidateFields && event.invalidateFields.length > 0) fieldsToFetch = Array.from(new Set(event.invalidateFields)).sort();
14417
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(event.itemKey);
14418
+ const loadedFields = store.state.itemLoadedFields[event.itemKey];
14419
+ const owedStaleFields = new Set([...store.state.itemFieldInvalidationFields[event.itemKey] ?? [], ...excludeLoadedFields(loadedFields, itemPendingInvalidationFields.get(event.itemKey))]);
14420
+ const affectedQueries = fieldsToFetch ? queriesForItem.filter(({ fields }) => {
14421
+ if (fields === "*") return true;
14422
+ if (!fields || fields.length === 0) return true;
14423
+ if (fields.some((field) => event.invalidateFields?.includes(field))) return true;
14424
+ return hasUnresolvedFullInvalidation ? excludeLoadedFields(loadedFields, fields).length > 0 : fields.some((field) => owedStaleFields.has(field));
14425
+ }) : queriesForItem;
14426
+ if (affectedQueries.length === 0) return;
14427
+ ignoreItemsInRefetchOnMount.delete(event.itemKey);
14428
+ const matchingQueries = affectedQueries.filter(({ isOffScreen }) => !isOffScreen);
14129
14429
  if (matchingQueries.length === 0) return;
14130
- if (itemInvalidationWasTriggered.has(event.itemKey)) return;
14131
14430
  if (matchingQueries.every((q) => q.disableRefetches) && store.state.itemQueries[event.itemKey]?.wasLoaded) return;
14132
- let fieldsToFetch;
14133
- if (event.invalidateFields && event.invalidateFields.length > 0) {
14134
- fieldsToFetch = Array.from(new Set(event.invalidateFields)).sort();
14135
- if (!matchingQueries.some(({ fields }) => {
14136
- if (fields === "*") return true;
14137
- if (!fields || fields.length === 0) return true;
14138
- return fields.some((field) => event.invalidateFields?.includes(field));
14139
- })) return;
14140
- }
14141
14431
  const firstQuery = matchingQueries[0];
14142
14432
  if (!firstQuery) return;
14433
+ const hookFields = firstQuery.fields;
14434
+ const isUnboundedHook = !hookFields || hookFields === "*" || hookFields.length === 0;
14435
+ if (itemInvalidationWasTriggered.has(event.itemKey)) {
14436
+ if (!fieldsToFetch) return;
14437
+ const contributionFields = hasUnresolvedFullInvalidation ? isUnboundedHook ? void 0 : excludeLoadedFields(loadedFields, hookFields) : isUnboundedHook ? Array.from(owedStaleFields) : hookFields.filter((field) => owedStaleFields.has(field));
14438
+ if (contributionFields && contributionFields.length === 0) return;
14439
+ scheduleAutomaticItemFetch(event.priority, firstQuery.payload, { fields: contributionFields });
14440
+ return;
14441
+ }
14442
+ if (fieldsToFetch) if (hasUnresolvedFullInvalidation) fieldsToFetch = isUnboundedHook ? void 0 : Array.from(new Set([...fieldsToFetch, ...excludeLoadedFields(loadedFields, hookFields)])).sort();
14443
+ else {
14444
+ const rideAlongFields = isUnboundedHook ? Array.from(owedStaleFields) : hookFields.filter((field) => owedStaleFields.has(field));
14445
+ fieldsToFetch = Array.from(new Set([...fieldsToFetch, ...rideAlongFields])).sort();
14446
+ }
14143
14447
  store.produceState((draft) => {
14144
14448
  const query = draft.itemQueries[event.itemKey];
14145
14449
  if (!query?.refetchOnMount) return;
@@ -14148,7 +14452,6 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14148
14452
  scheduleAutomaticItemFetch(event.priority, firstQuery.payload, { fields: fieldsToFetch ?? firstQuery.fields });
14149
14453
  itemInvalidationWasTriggered.add(event.itemKey);
14150
14454
  });
14151
- const ignoreItemsInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
14152
14455
  useLayoutEffect(() => {
14153
14456
  if (loadFromStateOnly || !preloadItemsBeforePaint || !preloadItems || fetchQueriesWithId.length < 1) return;
14154
14457
  preloadItems(fetchQueriesWithId.map(({ payload }) => payload));
@@ -14185,28 +14488,32 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14185
14488
  const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
14186
14489
  const invalidationPriority = unresolvedPendingInvalidationFields.length > 0 || hasUnresolvedFullInvalidation ? itemFieldInvalidationPriorities.get(itemKey) : void 0;
14187
14490
  if (Array.isArray(fields) && fields.length > 0) {
14188
- const affectedInvalidationFields = fields.filter((field) => unresolvedPendingInvalidationFields.includes(field));
14189
14491
  const staleOrMissingFields = getStaleOrMissingRequestedFields(itemKey, loadedFields, item, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14190
- const missingFields = loadedFields === "*" ? [] : staleOrMissingFields.filter((field) => !loadedFields.includes(field));
14492
+ const missingFields = getGenuinelyMissingRequestedFields(itemKey, {
14493
+ item,
14494
+ loadedFields
14495
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedPendingInvalidationFields);
14496
+ const staleInvalidatedFields = staleOrMissingFields.filter((field) => !missingFields.includes(field));
14191
14497
  const hasMissingFields = missingFields.length > 0;
14192
- const hasAffectedFieldInvalidation = affectedInvalidationFields.length > 0;
14193
- const shouldFetchForInvalidation = hasAffectedFieldInvalidation && !ignoreItemsInRefetchOnMount.has(itemKey);
14498
+ const hasStaleInvalidatedFields = staleInvalidatedFields.length > 0;
14499
+ const shouldFetchForInvalidation = hasStaleInvalidatedFields && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
14194
14500
  if ((hasMissingFields || shouldFetchForInvalidation) && !itemFetchIsActive) {
14195
14501
  shouldFetch = true;
14196
14502
  requiredFetch = true;
14197
- fieldsToFetch = Array.from(new Set([...missingFields, ...affectedInvalidationFields]));
14198
- if (fetchType === "lowPriority") fetchType = "highPriority";
14503
+ fieldsToFetch = Array.from(new Set([...missingFields, ...staleInvalidatedFields]));
14504
+ if ((hasMissingFields || !invalidationPriority) && fetchType === "lowPriority") fetchType = "highPriority";
14199
14505
  }
14200
- if (hasAffectedFieldInvalidation && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14506
+ if (hasStaleInvalidatedFields && !hasMissingFields && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14201
14507
  } else if (fields === "*") {
14202
- const missingFullItem = !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation;
14203
- const shouldFetchForInvalidation = !missingFullItem && unresolvedPendingInvalidationFields.length > 0 && !ignoreItemsInRefetchOnMount.has(itemKey);
14508
+ const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
14509
+ const missingFullItem = !hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation);
14510
+ const shouldFetchForInvalidation = !missingFullItem && (unresolvedPendingInvalidationFields.length > 0 || hasStaleFullInvalidation) && (!invalidationPriority || !ignoreItemsInRefetchOnMount.has(itemKey));
14204
14511
  if ((missingFullItem || shouldFetchForInvalidation) && !itemFetchIsActive) {
14205
14512
  shouldFetch = true;
14206
14513
  requiredFetch = true;
14207
- fieldsToFetch = missingFullItem ? "*" : unresolvedPendingInvalidationFields;
14208
- if (fetchType === "lowPriority") fetchType = "highPriority";
14209
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14514
+ fieldsToFetch = missingFullItem || hasStaleFullInvalidation ? "*" : unresolvedPendingInvalidationFields;
14515
+ if ((missingFullItem || !invalidationPriority) && fetchType === "lowPriority") fetchType = "highPriority";
14516
+ if (!missingFullItem && invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14210
14517
  }
14211
14518
  }
14212
14519
  }
@@ -14357,14 +14664,20 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14357
14664
  let highestPriority;
14358
14665
  for (const itemKey of itemKeys) {
14359
14666
  const unresolvedInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14360
- if (unresolvedInvalidationFields.length === 0) continue;
14361
- if (requestedFields && !requestedFields.some((field) => unresolvedInvalidationFields.includes(field))) continue;
14667
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(store.state.itemLoadedFields[itemKey]);
14668
+ if (unresolvedInvalidationFields.length === 0 && !hasUnresolvedFullInvalidation) continue;
14669
+ if (!hasUnresolvedFullInvalidation && requestedFields && !requestedFields.some((field) => unresolvedInvalidationFields.includes(field))) continue;
14362
14670
  const itemPriority = itemFieldInvalidationPriorities.get(itemKey);
14363
14671
  if (!itemPriority) continue;
14364
14672
  if (!highestPriority || fetchTypePriority[itemPriority] > fetchTypePriority[highestPriority]) highestPriority = itemPriority;
14365
14673
  }
14366
14674
  return highestPriority;
14367
- }, [getUnresolvedPendingInvalidationFields, itemFieldInvalidationPriorities]);
14675
+ }, [
14676
+ getUnresolvedPendingInvalidationFields,
14677
+ itemFieldInvalidationPriorities,
14678
+ itemsPendingFullInvalidation,
14679
+ store
14680
+ ]);
14368
14681
  const getVisibleQueryItemKeys = useCallback((queryKey, itemKeys) => {
14369
14682
  const missingOverlayItems = overlayItemsByQueryKey.get(queryKey);
14370
14683
  const hasDeletions = deletedOverlayItemKeys.size > 0;
@@ -14513,10 +14826,10 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14513
14826
  }
14514
14827
  }
14515
14828
  if (partialResources && Array.isArray(fields) && statusCanBeOverridden && staleOrMissingRequestedFields && staleOrMissingRequestedFields.size > 0) {
14516
- const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getFallbackMissingRequestedFields({
14829
+ const someItemMissingFieldDataInState = effectiveQuery.query.items.some((itemKey) => getGenuinelyMissingRequestedFields(itemKey, {
14517
14830
  item: state.items[itemKey],
14518
14831
  loadedFields: state.itemLoadedFields[itemKey]
14519
- }, fields, partialResources.inferFields).length > 0);
14832
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey, state)).length > 0);
14520
14833
  if (!hasCachedItemsInState) status = "loading";
14521
14834
  else if (someItemMissingFieldDataInState) status = showPartialAsRefetching ? "refetching" : "loading";
14522
14835
  else status = "refetching";
@@ -14686,9 +14999,9 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14686
14999
  store,
14687
15000
  visibleStoreState
14688
15001
  ]);
15002
+ const pendingOffScreenQueryInvalidations = useConst(() => /* @__PURE__ */ new Map());
14689
15003
  useOnEvtmitterEvent(events, "invalidateQuery", ({ payload: event }) => {
14690
15004
  for (const { key, payload, fields, loadSize, isOffScreen, disableRefetches } of fetchQueriesWithId) {
14691
- if (isOffScreen) continue;
14692
15005
  if (key !== event.queryKey) continue;
14693
15006
  const resolvedQuery = resolveEffectiveQuery(store.state, {
14694
15007
  key,
@@ -14696,6 +15009,11 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14696
15009
  fields
14697
15010
  });
14698
15011
  if (disableRefetches && resolvedQuery?.query.wasLoaded) continue;
15012
+ if (isOffScreen) {
15013
+ const existingPriority = pendingOffScreenQueryInvalidations.get(key);
15014
+ if (!existingPriority || fetchTypePriority[event.priority] > fetchTypePriority[existingPriority]) pendingOffScreenQueryInvalidations.set(key, event.priority);
15015
+ continue;
15016
+ }
14699
15017
  if (!queryInvalidationWasTriggered.has(key)) {
14700
15018
  stickyDerivedQueryKeys.delete(key);
14701
15019
  store.produceState((draft) => {
@@ -14703,9 +15021,9 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14703
15021
  if (!query?.refetchOnMount) return;
14704
15022
  query.refetchOnMount = false;
14705
15023
  });
14706
- scheduleAutomaticListQueryFetch(event.priority, payload, loadSize, { fields });
14707
15024
  queryInvalidationWasTriggered.add(key);
14708
15025
  }
15026
+ scheduleAutomaticListQueryFetch(event.priority, payload, loadSize, { fields });
14709
15027
  }
14710
15028
  });
14711
15029
  const ignoreQueriesInRefetchOnMount = useConst(() => /* @__PURE__ */ new Set());
@@ -14754,35 +15072,59 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14754
15072
  if (partialResources && !shouldFetch && effectiveQueryState) {
14755
15073
  const isQueryFetchInFlight = effectiveQueryState.status === "loading" || effectiveQueryState.status === "refetching" || effectiveQueryState.status === "loadingMore";
14756
15074
  if (Array.isArray(fields) && fields.length > 0) {
14757
- if (effectiveQueryState.items.some((itemKey) => getStaleOrMissingRequestedFields(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0) && !isQueryFetchInFlight) {
14758
- shouldFetch = true;
14759
- requiredFetch = true;
14760
- fieldsToFetch = fields;
14761
- if (fetchType === "lowPriority") fetchType = "highPriority";
15075
+ let hasStaleOrMissingRequestedFields = false;
15076
+ let hasGenuinelyMissingFields = false;
15077
+ for (const itemKey of effectiveQueryState.items) {
15078
+ const unresolvedInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
15079
+ if (getStaleOrMissingRequestedFields(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedInvalidationFields).length === 0) continue;
15080
+ hasStaleOrMissingRequestedFields = true;
15081
+ if (getGenuinelyMissingRequestedFields(itemKey, {
15082
+ item: store.state.items[itemKey],
15083
+ loadedFields: store.state.itemLoadedFields[itemKey]
15084
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, unresolvedInvalidationFields).length > 0) {
15085
+ hasGenuinelyMissingFields = true;
15086
+ break;
15087
+ }
14762
15088
  }
14763
- if (effectiveQueryState.items.some((itemKey) => {
14764
- const itemFieldInvalidationFields = getUnresolvedPendingInvalidationFields(itemKey);
14765
- return itemFieldInvalidationFields.length > 0 && fields.some((f) => itemFieldInvalidationFields.includes(f));
14766
- }) && !isQueryFetchInFlight) {
15089
+ if (hasStaleOrMissingRequestedFields && !isQueryFetchInFlight) {
14767
15090
  shouldFetch = true;
14768
15091
  requiredFetch = true;
14769
15092
  fieldsToFetch = fields;
14770
- const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, fields);
14771
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
15093
+ const invalidationPriority = hasGenuinelyMissingFields ? void 0 : getHighestPendingInvalidationPriority(effectiveQueryState.items, fields);
15094
+ if (!invalidationPriority) {
15095
+ if (fetchType === "lowPriority") fetchType = "highPriority";
15096
+ } else if (fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14772
15097
  }
14773
15098
  } else if (fields === "*") {
14774
- const hasAnyPartialItem = effectiveQueryState.items.some((itemKey) => !snapshotIsFullyLoadedAndFresh(itemKey, store.state.itemLoadedFields[itemKey], store.state.items[itemKey], partialResources.inferFields, itemsPendingFullInvalidation));
14775
- const hasAnyFieldInvalidation = effectiveQueryState.items.some((itemKey) => {
14776
- return getUnresolvedPendingInvalidationFields(itemKey).length > 0;
14777
- });
14778
- if ((hasAnyPartialItem || hasAnyFieldInvalidation) && !isQueryFetchInFlight) {
15099
+ let hasStaleItemData = false;
15100
+ let hasGenuinelyMissingItemData = false;
15101
+ for (const itemKey of effectiveQueryState.items) {
15102
+ const item = store.state.items[itemKey];
15103
+ const loadedFields = store.state.itemLoadedFields[itemKey];
15104
+ const hasUnresolvedFullInvalidation = itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields);
15105
+ const hasStaleFullInvalidation = hasUnresolvedFullInvalidation && !!item;
15106
+ if (!hasStaleFullInvalidation && (!snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields) || hasUnresolvedFullInvalidation)) {
15107
+ hasGenuinelyMissingItemData = true;
15108
+ break;
15109
+ }
15110
+ if (hasStaleFullInvalidation || getUnresolvedPendingInvalidationFields(itemKey).length > 0) hasStaleItemData = true;
15111
+ }
15112
+ if ((hasGenuinelyMissingItemData || hasStaleItemData) && !isQueryFetchInFlight) {
14779
15113
  shouldFetch = true;
14780
15114
  requiredFetch = true;
14781
- const invalidationPriority = getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
14782
- if (invalidationPriority && fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
15115
+ const invalidationPriority = hasGenuinelyMissingItemData ? void 0 : getHighestPendingInvalidationPriority(effectiveQueryState.items, void 0);
15116
+ if (!invalidationPriority) {
15117
+ if (fetchType === "lowPriority") fetchType = "highPriority";
15118
+ } else if (fetchTypePriority[invalidationPriority] > fetchTypePriority[fetchType]) fetchType = invalidationPriority;
14783
15119
  }
14784
15120
  }
14785
15121
  }
15122
+ const offScreenInvalidationPriority = pendingOffScreenQueryInvalidations.get(queryId);
15123
+ if (offScreenInvalidationPriority !== void 0) {
15124
+ pendingOffScreenQueryInvalidations.delete(queryId);
15125
+ shouldFetch = true;
15126
+ if (fetchTypePriority[offScreenInvalidationPriority] > fetchTypePriority[fetchType]) fetchType = offScreenInvalidationPriority;
15127
+ }
14786
15128
  if (!shouldFetch && ignoreQueriesInRefetchOnMount.has(queryId)) continue;
14787
15129
  ignoreQueriesInRefetchOnMount.add(queryId);
14788
15130
  if (shouldScheduleAutomaticFetch(effectiveQueryState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, effectiveQueryState?.status)) {
@@ -14799,6 +15141,7 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14799
15141
  getQueryState,
14800
15142
  getDerivedPreloadPayloads,
14801
15143
  ignoreQueriesInRefetchOnMount,
15144
+ pendingOffScreenQueryInvalidations,
14802
15145
  preloadDerivedQueryItems,
14803
15146
  preloadQueries,
14804
15147
  preloadQueriesBeforePaint,
@@ -15221,6 +15564,7 @@ function createListQueryStore(storeOptions) {
15221
15564
  }
15222
15565
  const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
15223
15566
  const itemsPendingFullInvalidation = /* @__PURE__ */ new Set();
15567
+ const itemDroppedFieldInvalidations = /* @__PURE__ */ new Map();
15224
15568
  const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers, reevaluateDelayedRTUs } = createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, wrappedDynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, !!persistence && !persistence.hasAsyncPreload, persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0, persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0, persistence, testOptions?.initialLastFetchStartTime, (requests, startedAt) => {
15225
15569
  const queryKey = requests[0]?.requestId;
15226
15570
  if (!queryKey) return;
@@ -15234,8 +15578,10 @@ function createListQueryStore(storeOptions) {
15234
15578
  pruneItemInvalidationTracking();
15235
15579
  const successfulQueryKeys = requests.filter(({ requestId }) => results.get(requestId) === true).map(({ requestId }) => requestId);
15236
15580
  if (successfulQueryKeys.length > 0) {
15581
+ const committedItemKeys = successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []);
15237
15582
  touchQueries(successfulQueryKeys);
15238
- touchItems(successfulQueryKeys.flatMap((queryKey) => store.state.queries[queryKey]?.items ?? []));
15583
+ touchItems(committedItemKeys);
15584
+ reannounceInvalidationsDroppedDuringFetch(committedItemKeys, startedAt);
15239
15585
  if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15240
15586
  }
15241
15587
  const firstQueryKey = successfulQueryKeys[0];
@@ -15265,7 +15611,9 @@ function createListQueryStore(storeOptions) {
15265
15611
  pruneItemInvalidationTracking();
15266
15612
  const successfulItems = requests.filter(({ requestId }) => results.get(requestId) === true).map((request) => ({ itemKey: request.requestId }));
15267
15613
  if (successfulItems.length > 0) {
15268
- touchItems(successfulItems.map(({ itemKey }) => itemKey));
15614
+ const committedItemKeys = successfulItems.map(({ itemKey }) => itemKey);
15615
+ touchItems(committedItemKeys);
15616
+ reannounceInvalidationsDroppedDuringFetch(committedItemKeys, startedAt);
15269
15617
  if (shouldScheduleCacheLimitEnforcement()) scheduleCacheLimitEnforcement();
15270
15618
  }
15271
15619
  const firstSuccessfulItem = successfulItems[0];
@@ -15283,11 +15631,11 @@ function createListQueryStore(storeOptions) {
15283
15631
  for (const { itemKey } of successfulItems) publishItemSnapshot(itemKey, "confirmed");
15284
15632
  }
15285
15633
  }, offlineFetchController, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15286
- const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, invalidateQueryAndItems, invalidateItem, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
15634
+ const { storeEvents, queryInvalidationWasTriggered, itemInvalidationWasTriggered, itemFieldInvalidationPriorities, invalidateQueryAndItems, invalidateItem, reannounceInvalidationsDroppedDuringFetch, startItemMutation, updateItemState: updateItemStateBase, addItemToState: addItemToStateBase, deleteItemState: deleteItemStateBase, resetInvalidationTracking, performMutation: performMutationBase } = createMutationApi(store, fetchItemFn, partialResources, optimisticListUpdates, onInvalidateQuery, onInvalidateItem, resolvedOnMutationError, errorNormalizer, getItemKey, getQueriesKeyArray, getQueriesRelatedToItem, getItemsKeyArray, getOrCreateItemScheduler, getOrCreateQueryScheduler, deleteItemFetchResources, (event) => {
15287
15635
  events.emit("invalidateQuery", event);
15288
15636
  }, (event) => {
15289
15637
  events.emit("invalidateItem", event);
15290
- }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation);
15638
+ }, blockWindowClose, resolvedOfflineConfig ? offlineMutationController : null, runWithBroadcastConsistency, publishQuerySnapshot, publishItemSnapshot, void 0, itemPendingInvalidationFields, itemsPendingFullInvalidation, itemDroppedFieldInvalidations);
15291
15639
  if (resolvedPersistentStorageConfig && resolvedOfflineConfig) offlineController = createOfflineStoreController(id, "listQuery", getSessionKeyForRuntime, resolvedPersistentStorageConfig.onPersistentStorageError, import.meta.env.DEV ? storeManager.debugLogger : void 0, resolvedPersistentStorageConfig.adapter, {
15292
15640
  normalizeEntityRefs: (entityRefs) => entityRefs.map((ref) => {
15293
15641
  const normalizedRef = offlineItemEntityRefSchema.parse(ref).unwrapOrNull();
@@ -15370,6 +15718,37 @@ function createListQueryStore(storeOptions) {
15370
15718
  if (remainingFields.length > 0) draft.itemFieldInvalidationFields[itemKey] = remainingFields;
15371
15719
  else delete draft.itemFieldInvalidationFields[itemKey];
15372
15720
  }
15721
+ /**
15722
+ * A confirmed remote snapshot cancels the pending local fetches it
15723
+ * satisfies, but the sender may have refetched only a subset of the
15724
+ * invalidated fields (it fetches only its own hooks' fields). Any fields
15725
+ * still owed after applying the snapshot are re-announced so mounted hooks
15726
+ * re-schedule refetches of their own remaining stale fields — without
15727
+ * this, the cancelled local refetch would leave them stale forever.
15728
+ *
15729
+ * Only called when the snapshot actually cancelled a pending local fetch:
15730
+ * that cancellation is the refetch obligation being destroyed, and gating
15731
+ * on it also guarantees the cross-tab re-announce ping-pong terminates —
15732
+ * a repeat cycle requires a new pending fetch at snapshot arrival.
15733
+ */
15734
+ function emitRemainingInvalidationFieldsAfterSnapshot(itemKey) {
15735
+ const priority = itemFieldInvalidationPriorities.get(itemKey) ?? "highPriority";
15736
+ if (itemsPendingFullInvalidation.has(itemKey)) {
15737
+ events.emit("invalidateItem", {
15738
+ priority,
15739
+ itemKey
15740
+ });
15741
+ return;
15742
+ }
15743
+ const stateInvalidationFields = store.state.itemFieldInvalidationFields[itemKey];
15744
+ const remainingFields = stateInvalidationFields && stateInvalidationFields.length > 0 ? stateInvalidationFields : excludeLoadedFields(store.state.itemLoadedFields[itemKey], itemPendingInvalidationFields.get(itemKey));
15745
+ if (remainingFields.length === 0) return;
15746
+ events.emit("invalidateItem", {
15747
+ priority,
15748
+ itemKey,
15749
+ invalidateFields: remainingFields
15750
+ });
15751
+ }
15373
15752
  function pruneItemInvalidationTracking() {
15374
15753
  for (const [itemKey, pendingFields] of itemPendingInvalidationFields) {
15375
15754
  const remainingFields = excludeLoadedFields(store.state.itemLoadedFields[itemKey], pendingFields);
@@ -15394,6 +15773,7 @@ function createListQueryStore(storeOptions) {
15394
15773
  itemFieldInvalidationPriorities.delete(itemKey);
15395
15774
  itemPendingInvalidationFields.delete(itemKey);
15396
15775
  itemsPendingFullInvalidation.delete(itemKey);
15776
+ itemDroppedFieldInvalidations.delete(itemKey);
15397
15777
  itemInvalidationWasTriggered.delete(itemKey);
15398
15778
  itemCacheRuntime.clear(itemKey);
15399
15779
  }
@@ -15442,9 +15822,9 @@ function createListQueryStore(storeOptions) {
15442
15822
  }
15443
15823
  function isStandaloneItemProtectedFromEviction(itemKey, itemQuery) {
15444
15824
  if (itemCacheRuntime.isActive(itemKey)) return true;
15445
- const scheduler = getOrCreateItemScheduler(itemKey, itemQuery.payload);
15446
- if (itemQuery.status === "loading" || itemQuery.status === "refetching" || scheduler.getFetchIsInProgress()) return true;
15447
- return scheduler.isMutationInProgress(itemKey);
15825
+ const scheduler = getKnownItemScheduler(itemKey);
15826
+ if (itemQuery.status === "loading" || itemQuery.status === "refetching" || scheduler?.getFetchIsInProgress()) return true;
15827
+ return scheduler?.isMutationInProgress(itemKey) ?? false;
15448
15828
  }
15449
15829
  function mergeIncomingItemSnapshot(currentItem, incomingItem) {
15450
15830
  if (!partialResources || incomingItem === null) return incomingItem;
@@ -15490,10 +15870,12 @@ function createListQueryStore(storeOptions) {
15490
15870
  }
15491
15871
  }, { action: "browser-tabs-list-item-snapshot" });
15492
15872
  });
15493
- if (message.consistency === "confirmed") itemScheduler?.cancelPendingRequests([message.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(message.item, message.loadedFields, payload.fields));
15873
+ let cancelledPendingItemFetch = false;
15874
+ if (message.consistency === "confirmed" && itemScheduler) cancelledPendingItemFetch = itemScheduler.cancelPendingRequests([message.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(message.item, message.loadedFields, payload.fields));
15494
15875
  itemInvalidationWasTriggered.delete(message.itemKey);
15495
15876
  if (message.item === null && message.itemQuery === null) cleanupItemStateMetadata(message.itemKey);
15496
15877
  pruneItemInvalidationTracking();
15878
+ if (cancelledPendingItemFetch) emitRemainingInvalidationFieldsAfterSnapshot(message.itemKey);
15497
15879
  if (message.item === null && message.itemQuery === null) {
15498
15880
  if (payloadToCleanup) deleteItemFetchResources([{
15499
15881
  itemKey: message.itemKey,
@@ -15505,10 +15887,12 @@ function createListQueryStore(storeOptions) {
15505
15887
  }
15506
15888
  }
15507
15889
  function applyRemoteQuerySnapshot(message) {
15890
+ let cancelledPendingQueryFetch = false;
15891
+ const itemKeysWithCancelledFetch = /* @__PURE__ */ new Set();
15508
15892
  if (message.consistency === "confirmed") {
15509
15893
  const snapshotItemsByKey = new Map(message.items.map((item) => [item.itemKey, item]));
15510
- getOrCreateQueryScheduler(message.queryKey).cancelPendingRequests([message.queryKey], (request) => querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request));
15511
- for (const item of message.items) getKnownItemScheduler(item.itemKey)?.cancelPendingRequests([item.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, payload.fields));
15894
+ cancelledPendingQueryFetch = getOrCreateQueryScheduler(message.queryKey).cancelPendingRequests([message.queryKey], (request) => querySnapshotSatisfiesPendingQueryFetch(message, snapshotItemsByKey, request));
15895
+ for (const item of message.items) if (getKnownItemScheduler(item.itemKey)?.cancelPendingRequests([item.itemKey], ({ payload }) => itemSnapshotSatisfiesRequestedFields(item.item, item.loadedFields, payload.fields))) itemKeysWithCancelledFetch.add(item.itemKey);
15512
15896
  }
15513
15897
  runWithoutBroadcast(() => {
15514
15898
  store.produceState((draft) => {
@@ -15536,6 +15920,7 @@ function createListQueryStore(storeOptions) {
15536
15920
  for (const item of message.items) {
15537
15921
  itemInvalidationWasTriggered.delete(item.itemKey);
15538
15922
  lastItemSyncVersions.set(item.itemKey, toBrowserTabsSyncVersion(message, message.consistency));
15923
+ if (cancelledPendingQueryFetch || itemKeysWithCancelledFetch.has(item.itemKey)) emitRemainingInvalidationFieldsAfterSnapshot(item.itemKey);
15539
15924
  }
15540
15925
  touchQueries([message.queryKey]);
15541
15926
  touchItems(message.items.map(({ itemKey }) => itemKey));
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DqJXzF7M.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-413IafdY.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { B as getNamespaceId, G as parsePersistedAsyncNamespaceKind, V as getPayloadRecordKey, W as parseAsyncStorageRecordKey, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, z as encodePersistedAsyncNamespaceKind } from "./asyncStorageAdapter-CGfnsd9m.js";
1
+ import { B as encodePersistedAsyncNamespaceKind, G as parseAsyncStorageRecordKey, H as getPayloadRecordKey, K as parsePersistedAsyncNamespaceKind, V as getNamespaceId, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog } from "./asyncStorageAdapter-CsFvYNBT.js";
2
2
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
3
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
4
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -136,7 +136,8 @@ TSDF does not choose a persistence adapter automatically. Pass one of the built-
136
136
  - Uses managed `localStorage` entries.
137
137
  - Can hydrate synchronously during initial state creation for `DocumentStore`.
138
138
  - `CollectionStore` and `ListQueryStore` use lazy hydration for unknown entries from initial keys scan.
139
- - Writes are debounced and may be dropped if serialization or quota errors occur.
139
+ - Writes are debounced and may be dropped if serialization errors occur.
140
+ - When a write hits the browser `QuotaExceededError` (the shared origin quota is full, e.g. because other parts of the app filled `localStorage`), TSDF automatically evicts its own least recently used entries — across all TSDF stores and sessions — and retries, escalating to all non-offline-protected entries if needed. Offline data and non-TSDF keys are never touched. If even that cannot free enough space, a single descriptive error is reported through `onPersistentStorageError` and persistence writes are silently skipped until the next page load.
140
141
 
141
142
  Use it with:
142
143
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "17.0.0-beta.2",
3
+ "version": "17.0.0-beta.5",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",