tsdf 17.0.0-beta.4 → 17.0.0-beta.6

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),
@@ -8520,8 +8692,8 @@ function useMultipleItems$1(items, { selector, returnIdleStatus: allItemsReturnI
8520
8692
  if (isOffScreen) continue;
8521
8693
  if (itemId) {
8522
8694
  const itemState = getItemState(payload);
8523
- const fetchType = itemState?.refetchOnMount || "lowPriority";
8524
8695
  const requiredFetch = !itemState?.wasLoaded;
8696
+ const fetchType = itemState?.refetchOnMount && requiredFetch ? "highPriority" : itemState?.refetchOnMount || "lowPriority";
8525
8697
  if (itemState === null) continue;
8526
8698
  const shouldFetch = requiredFetch || !!itemState.refetchOnMount;
8527
8699
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemId)) continue;
@@ -14345,6 +14517,19 @@ function useMultipleItems(items, { selector, loadFromStateOnly, returnIdleStatus
14345
14517
  }
14346
14518
  }
14347
14519
  }
14520
+ if (itemState?.refetchOnMount && fetchType !== "highPriority") {
14521
+ let hasMissingRequestedData = requiredFetch;
14522
+ if (!hasMissingRequestedData && partialResources) {
14523
+ const loadedFields = store.state.itemLoadedFields[itemKey];
14524
+ const item = store.state.items[itemKey];
14525
+ if (Array.isArray(fields) && fields.length > 0) hasMissingRequestedData = getGenuinelyMissingRequestedFields(itemKey, {
14526
+ item,
14527
+ loadedFields
14528
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0;
14529
+ else if (fields === "*") hasMissingRequestedData = !(itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) && !!item) && !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields);
14530
+ }
14531
+ if (hasMissingRequestedData) fetchType = "highPriority";
14532
+ }
14348
14533
  if (!shouldFetch && ignoreItemsInRefetchOnMount.has(itemKey)) continue;
14349
14534
  ignoreItemsInRefetchOnMount.add(itemKey);
14350
14535
  if (shouldScheduleAutomaticFetch(itemState?.wasLoaded, shouldFetch, disableRefetches, disableRefetchOnMount, !!partialResources) && tryClaimAutomaticFetchSlot(automaticRetryState, retrySignature, itemState?.status)) scheduleAutomaticItemFetch(fetchType, payload, { fields: fieldsToFetch });
@@ -14947,6 +15132,28 @@ function useMultipleListQueries(queries, { itemSelector, returnIdleStatus: allIt
14947
15132
  }
14948
15133
  }
14949
15134
  }
15135
+ if (queryState?.refetchOnMount && fetchType !== "highPriority") {
15136
+ let hasMissingRequestedData = requiredFetch;
15137
+ if (!hasMissingRequestedData && partialResources && effectiveQueryState) {
15138
+ if (Array.isArray(fields) && fields.length > 0) {
15139
+ for (const itemKey of effectiveQueryState.items) if (getGenuinelyMissingRequestedFields(itemKey, {
15140
+ item: store.state.items[itemKey],
15141
+ loadedFields: store.state.itemLoadedFields[itemKey]
15142
+ }, fields, partialResources.inferFields, itemsPendingFullInvalidation, getUnresolvedPendingInvalidationFields(itemKey)).length > 0) {
15143
+ hasMissingRequestedData = true;
15144
+ break;
15145
+ }
15146
+ } else if (fields === "*") for (const itemKey of effectiveQueryState.items) {
15147
+ const item = store.state.items[itemKey];
15148
+ const loadedFields = store.state.itemLoadedFields[itemKey];
15149
+ if (!(itemsPendingFullInvalidation.has(itemKey) && !hasFullyLoadedFields(loadedFields) && !!item) && !snapshotIsFullyLoaded(loadedFields, item, partialResources.inferFields)) {
15150
+ hasMissingRequestedData = true;
15151
+ break;
15152
+ }
15153
+ }
15154
+ }
15155
+ if (hasMissingRequestedData) fetchType = "highPriority";
15156
+ }
14950
15157
  const offScreenInvalidationPriority = pendingOffScreenQueryInvalidations.get(queryId);
14951
15158
  if (offScreenInvalidationPriority !== void 0) {
14952
15159
  pendingOffScreenQueryInvalidations.delete(queryId);
@@ -15650,9 +15857,9 @@ function createListQueryStore(storeOptions) {
15650
15857
  }
15651
15858
  function isStandaloneItemProtectedFromEviction(itemKey, itemQuery) {
15652
15859
  if (itemCacheRuntime.isActive(itemKey)) return true;
15653
- const scheduler = getOrCreateItemScheduler(itemKey, itemQuery.payload);
15654
- if (itemQuery.status === "loading" || itemQuery.status === "refetching" || scheduler.getFetchIsInProgress()) return true;
15655
- return scheduler.isMutationInProgress(itemKey);
15860
+ const scheduler = getKnownItemScheduler(itemKey);
15861
+ if (itemQuery.status === "loading" || itemQuery.status === "refetching" || scheduler?.getFetchIsInProgress()) return true;
15862
+ return scheduler?.isMutationInProgress(itemKey) ?? false;
15656
15863
  }
15657
15864
  function mergeIncomingItemSnapshot(currentItem, incomingItem) {
15658
15865
  if (!partialResources || incomingItem === null) return incomingItem;
@@ -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.4",
3
+ "version": "17.0.0-beta.6",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",