tsdf 17.0.0-alpha.12 → 17.0.0-alpha.14

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 { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-CYxABChu.js";
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-C1ouzZYD.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CSzvgl3s.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-B1kF0Ojl.js";
2
2
  export { createAsyncStorageAdapter };
@@ -333,7 +333,10 @@ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBy
333
333
  }
334
334
  if (unprotectedBytes <= maxBytes) {
335
335
  for (const entry of entries) keptKeys.add(getKey(entry));
336
- return keptKeys;
336
+ return {
337
+ keptKeys,
338
+ unprotectedBytes
339
+ };
337
340
  }
338
341
  const sortedEntries = [...entries].sort((a, b) => {
339
342
  const aProtected = isProtected(a);
@@ -364,7 +367,10 @@ function keepEntriesWithinByteBudget(entries, getKey, getLastAccessAt, getSizeBy
364
367
  keptUnprotectedBytes += sizeBytes;
365
368
  }
366
369
  }
367
- return keptKeys;
370
+ return {
371
+ keptKeys,
372
+ unprotectedBytes
373
+ };
368
374
  }
369
375
  //#endregion
370
376
  //#region src/persistentStorage/persistentStorageDefaults.ts
@@ -397,6 +403,57 @@ function getDefaultMaxBytesForScope(adapter, scopeKind) {
397
403
  return getDefaultMaxBytesForAdapter(adapter, getDefaultMaxBytesKindForScope(scopeKind));
398
404
  }
399
405
  //#endregion
406
+ //#region src/debug.ts
407
+ function defaultConsoleDebugLogger(entry) {
408
+ const consoleForLevel = globalThis.console[entry.level];
409
+ if (typeof consoleForLevel !== "function") return;
410
+ const details = entry.details ? {
411
+ operation: entry.operation,
412
+ ...entry.details
413
+ } : { operation: entry.operation };
414
+ consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
415
+ }
416
+ function resolveTSDFLogger(logger) {
417
+ if (logger === void 0 || logger === false) return void 0;
418
+ if (logger === true) return defaultConsoleDebugLogger;
419
+ return logger;
420
+ }
421
+ function emitTSDFDebugLog(logger, entry) {
422
+ if (!logger) return;
423
+ try {
424
+ logger(entry);
425
+ } catch (error) {
426
+ globalThis.console.error("[tsdf:debug] Debug logger failed", error);
427
+ }
428
+ }
429
+ function getTSDFDebugTimingMs() {
430
+ if (!import.meta.env.DEV) return 0;
431
+ return Date.now();
432
+ }
433
+ //#endregion
434
+ //#region src/persistentStorage/quotaDebug.ts
435
+ function logPersistentStorageQuotaCleanup(args) {
436
+ emitTSDFDebugLog(args.prodLogger, {
437
+ area: "persistent-storage",
438
+ details: {
439
+ adapter: args.adapter,
440
+ evictedEntries: args.evictedEntries,
441
+ keptEntries: args.keptEntries,
442
+ maxBytes: args.maxBytes,
443
+ namespaceKind: args.namespaceKind,
444
+ phase: args.phase,
445
+ quota: args.quota,
446
+ status: "success",
447
+ storeName: args.storeName,
448
+ totalEntries: args.totalEntries,
449
+ unprotectedBytes: args.unprotectedBytes
450
+ },
451
+ level: "log",
452
+ message: "persistent storage quota-cleanup success",
453
+ operation: "quota-cleanup"
454
+ });
455
+ }
456
+ //#endregion
400
457
  //#region src/persistentStorage/types.ts
401
458
  function parseAsyncStorageNamespaceKind(value) {
402
459
  switch (value) {
@@ -830,6 +887,8 @@ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
830
887
  var ManagedAsyncStorageAdapter = class {
831
888
  kind = "async";
832
889
  #driver;
890
+ #debugLogger;
891
+ #prodLogger;
833
892
  #cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
834
893
  #cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
835
894
  #namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
@@ -842,6 +901,20 @@ var ManagedAsyncStorageAdapter = class {
842
901
  this.#driver = driver;
843
902
  registerAsyncStorageReadCacheParticipant(this);
844
903
  }
904
+ get debugLogger() {
905
+ return this.#debugLogger;
906
+ }
907
+ set debugLogger(debugLogger) {
908
+ this.#debugLogger = debugLogger;
909
+ this.#driver.debugLogger = debugLogger;
910
+ }
911
+ get prodLogger() {
912
+ return this.#prodLogger;
913
+ }
914
+ set prodLogger(prodLogger) {
915
+ this.#prodLogger = prodLogger;
916
+ this.#driver.prodLogger = prodLogger;
917
+ }
845
918
  async #runWithSessionWriterLock(sessionKey, callback) {
846
919
  return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
847
920
  }
@@ -1757,7 +1830,25 @@ var ManagedAsyncStorageAdapter = class {
1757
1830
  for (const payloadKey of payloadKeys) if (!indexState.entries.has(payloadKey)) payloadRecordKeysToRemove.add(getPayloadRecordKey(payloadKey));
1758
1831
  if (effectiveStaticPolicy?.maxBytes !== void 0) {
1759
1832
  const pinnedKeys = new Set(effectiveStaticPolicy.pinnedKeys ?? []);
1760
- const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1833
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
1834
+ const prodLogger = args.driver.prodLogger;
1835
+ const evictedEntries = candidateEntries.length - keptKeys.size;
1836
+ if (prodLogger && evictedEntries > 0) {
1837
+ const scopeKind = args.scope.kind;
1838
+ logPersistentStorageQuotaCleanup({
1839
+ adapter: "async",
1840
+ prodLogger,
1841
+ evictedEntries,
1842
+ keptEntries: keptKeys.size,
1843
+ maxBytes: effectiveStaticPolicy.maxBytes,
1844
+ namespaceKind: scopeKind,
1845
+ phase: "startup-cleanup",
1846
+ quota: scopeKind === "listQuery.item" ? "maxItemBytes" : scopeKind === "listQuery.query" ? "maxQueryBytes" : "maxBytes",
1847
+ storeName: args.scope.storeName,
1848
+ totalEntries: candidateEntries.length,
1849
+ unprotectedBytes
1850
+ });
1851
+ }
1761
1852
  for (const { itemKey } of candidateEntries) {
1762
1853
  if (keptKeys.has(itemKey)) continue;
1763
1854
  payloadRecordKeysToRemove.add(getPayloadRecordKey(itemKey));
@@ -1828,4 +1919,4 @@ function serializeProtectedRef(ref) {
1828
1919
  return serializeProtectedRef$1(ref);
1829
1920
  }
1830
1921
  //#endregion
1831
- export { getNavigatorLockManager as A, parseAsyncStorageRecordKey as B, isModeEffectivelyActive as C, clearSessionProtectedKeysSnapshot as D, offlineResolutionRecordSchema as E, encodePersistedAsyncNamespaceKind as F, serializeProtectedRef$1 as H, getNamespaceId as I, getPayloadRecordKey as L, createCompactLocalStorageEntry as M, parseCompactLocalStorageEntry as N, getSessionProtectedKeysSnapshot as O, compareMetadata as P, getPersistedNamespaceId as R, getIsOfflineModeFromStatus as S, offlineItemEntityRefSchema as T, scheduleIdleCleanup as U, parsePersistedAsyncNamespaceKind as V, keepEntriesWithinByteBudget as _, estimateManagedAsyncStorageEntrySizeBytes as a, compactOfflineStatusSnapshotSchema as b, readAsyncStorageNamespaceIndexStateUsingDriver as c, unregisterAsyncStartupStoreCleanup as d, parseAsyncStorageNamespaceKind as f, getSerializedStringSize as g, createTimedKeySet as h, createAsyncStorageAdapter as i, warnIfNavigatorLockUnavailable as j, setSessionProtectedKeysSnapshot as k, registerAsyncStartupStoreCleanup as l, createShouldIgnoreItemPredicate as m, ASYNC_STORAGE_MAX_AGE_MS as n, getProtectedKeysFromMetadata as o, getDefaultMaxBytesForScope as p, buildPersistedStaticPolicy as r, mergeManagedAsyncStorageCustomMetadata as s, ASYNC_MAINTENANCE_LOCAL_STORAGE_KEY as t, serializeProtectedRef as u, serializeJsonForStorage as v, isOfflineModeStatusValue as w, defaultOfflineRuntimeConfig as x, OfflineResolutionConflictParseError as y, normalizeStaticPolicy as z };
1922
+ 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, 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, scheduleIdleCleanup 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 };
@@ -1,4 +1,4 @@
1
- import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-DqUm_Sv7.js";
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-hwf0jXKv.js";
2
2
 
3
3
  //#region src/persistentStorage/asyncStorageAdapter.d.ts
4
4
  declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
@@ -1,3 +1,3 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-3c1zSDZi.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DtWquUOj.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DcODOOJk.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-BMgsTNPP.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-DqUm_Sv7.js";
1
+ import { t as AsyncStorageAdapter } from "./types-hwf0jXKv.js";
2
2
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
3
3
  /** Options for creating the IndexedDB persistent storage adapter. */
4
4
  type IndexedDbPersistentStorageOptions$1 = {
@@ -1,2 +1,2 @@
1
- import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-DtWquUOj.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-BMgsTNPP.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, H as serializeProtectedRef, I as getNamespaceId, L as getPayloadRecordKey, P as compareMetadata, R as getPersistedNamespaceId, V as parsePersistedAsyncNamespaceKind, a as estimateManagedAsyncStorageEntrySizeBytes, i as createAsyncStorageAdapter, v as serializeJsonForStorage, z as normalizeStaticPolicy } from "./asyncStorageAdapter-CSzvgl3s.js";
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-B1kF0Ojl.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
@@ -244,6 +244,7 @@ async function setMaintenanceState(database, value) {
244
244
  await transactionDone(transaction);
245
245
  }
246
246
  var IndexedDbAsyncStorageDriver = class {
247
+ debugLogger;
247
248
  __tsdfManagedStorage = {
248
249
  applyManagedCommit: this.applyManagedCommit.bind(this),
249
250
  clearManagedNamespace: this.clearManagedNamespace.bind(this),
@@ -315,6 +316,7 @@ var IndexedDbAsyncStorageDriver = class {
315
316
  }
316
317
  }
317
318
  async removeMany(scope, keys) {
319
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
318
320
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
319
321
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
320
322
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -339,6 +341,10 @@ var IndexedDbAsyncStorageDriver = class {
339
341
  };
340
342
  }
341
343
  await transactionDone(transaction);
344
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-records", startTime, {
345
+ keyCount: keys.length,
346
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE]
347
+ });
342
348
  this.#instrumentation?.onRemoveMany?.(scope, keys);
343
349
  this.#instrumentation?.record({
344
350
  keys: [...keys].sort((left, right) => left.localeCompare(right)),
@@ -361,6 +367,7 @@ var IndexedDbAsyncStorageDriver = class {
361
367
  return (await this.listScopesWithKnownRecordKeys(sessionKey)).map(({ scope }) => scope);
362
368
  }
363
369
  async listScopesWithKnownRecordKeys(sessionKey) {
370
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
364
371
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
365
372
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
366
373
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -380,6 +387,11 @@ var IndexedDbAsyncStorageDriver = class {
380
387
  });
381
388
  });
382
389
  await transactionDone(transaction);
390
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(void 0, "list-scopes", startTime, {
391
+ count: discoveredScopes.length,
392
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
393
+ ...sessionKey !== void 0 ? { sessionKey } : {}
394
+ });
383
395
  discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
384
396
  this.#instrumentation?.record({
385
397
  scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
@@ -390,6 +402,7 @@ var IndexedDbAsyncStorageDriver = class {
390
402
  return discoveredScopes;
391
403
  }
392
404
  async readManagedEntries(scope, keys) {
405
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
393
406
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
394
407
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
395
408
  const uniqueKeys = [...new Set(keys)];
@@ -407,6 +420,11 @@ var IndexedDbAsyncStorageDriver = class {
407
420
  });
408
421
  }));
409
422
  await transactionDone(transaction);
423
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "read-records", startTime, {
424
+ hitCount: [...result.values()].filter((value) => value !== null).length,
425
+ keyCount: uniqueKeys.length,
426
+ objectStores: [INDEXED_DB_ENTRY_STORE]
427
+ });
410
428
  this.#instrumentation?.record({
411
429
  keys: uniqueKeys,
412
430
  resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
@@ -417,6 +435,7 @@ var IndexedDbAsyncStorageDriver = class {
417
435
  return result;
418
436
  }
419
437
  async listManagedMetadata(scope, args = {}) {
438
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
420
439
  const order = args.order ?? "key";
421
440
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
422
441
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
@@ -448,6 +467,12 @@ var IndexedDbAsyncStorageDriver = class {
448
467
  const filter = args.filter;
449
468
  const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
450
469
  if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
470
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-record-metadata", startTime, {
471
+ count: filteredEntries.length,
472
+ objectStores: [INDEXED_DB_ENTRY_STORE],
473
+ order,
474
+ usedIndex
475
+ });
451
476
  this.#instrumentation?.record({
452
477
  order,
453
478
  resultKeys: filteredEntries.map((entry) => entry.key),
@@ -462,6 +487,7 @@ var IndexedDbAsyncStorageDriver = class {
462
487
  return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
463
488
  }
464
489
  async clearManagedNamespace(scope) {
490
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
465
491
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
466
492
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
467
493
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -470,6 +496,7 @@ var IndexedDbAsyncStorageDriver = class {
470
496
  });
471
497
  policyStore.delete(createScopePolicyKey(scope));
472
498
  await transactionDone(transaction);
499
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "clear-records", startTime, { objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE] });
473
500
  this.#instrumentation?.onClearManagedNamespace?.(scope);
474
501
  this.#instrumentation?.record({
475
502
  scope,
@@ -478,6 +505,7 @@ var IndexedDbAsyncStorageDriver = class {
478
505
  });
479
506
  }
480
507
  async applyManagedCommit(scope, args, helpers) {
508
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
481
509
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
482
510
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
483
511
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -544,6 +572,12 @@ var IndexedDbAsyncStorageDriver = class {
544
572
  s: scope.sessionKey
545
573
  }, createScopePolicyKey(scope)));
546
574
  await transactionDone(transaction);
575
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-records", startTime, {
576
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
577
+ removes: removes.length,
578
+ touches: touches.length,
579
+ upserts: upserts.length
580
+ });
547
581
  this.#instrumentation?.onApplyManagedCommit?.(scope, args);
548
582
  this.#instrumentation?.record({
549
583
  removes,
@@ -883,6 +917,32 @@ var IndexedDbAsyncStorageDriver = class {
883
917
  });
884
918
  return this.#databasePromise;
885
919
  }
920
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
921
+ if (!import.meta.env.DEV) return;
922
+ if (startTime === null) return;
923
+ if (!this.debugLogger) return;
924
+ const status = typeof details.status === "string" ? details.status : "success";
925
+ emitTSDFDebugLog(this.debugLogger, {
926
+ area: "persistent-storage",
927
+ level: "log",
928
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
929
+ operation: "adapter-operation",
930
+ details: {
931
+ adapter: "async",
932
+ adapterName: "indexeddb",
933
+ adapterOperation,
934
+ databaseName: this.databaseName,
935
+ durationMs: getTSDFDebugTimingMs() - startTime,
936
+ status,
937
+ ...scope !== void 0 ? {
938
+ namespaceKind: scope.kind,
939
+ sessionKey: scope.sessionKey,
940
+ storeName: scope.storeName
941
+ } : {},
942
+ ...details
943
+ }
944
+ });
945
+ }
886
946
  };
887
947
  function createIndexedDbPersistentStorage$1(options = {}) {
888
948
  return createAsyncStorageAdapter(new IndexedDbAsyncStorageDriver(options.databaseName));
package/dist/main.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFDebugOptions, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, Zt as TSDFFocusDebugOperation, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-DqUm_Sv7.js";
1
+ import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFFocusDebugOperation, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, Zt as TSDFLoggerOptions, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-hwf0jXKv.js";
2
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
3
3
  import { Emitter } from "evtmitter";
4
4
  import { Context } from "react";
@@ -74,7 +74,8 @@ type StoreManagerOfflineApi<TUploadRef extends ValidPayload = ValidPayload> = {
74
74
  /** Shared coordinator passed to every TSDF store instance in an app/session. */
75
75
  type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
76
76
  /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync, focus lifecycle, and persistent storage internals. */
77
- debugLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
77
+ debugLogger?: TSDFDebugLogger; /** Shared logger for low-volume production signals. */
78
+ prodLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
78
79
  errorNormalizer: (exception: Error) => StoreError; /** Global fallback for persistent storage failures in attached stores. */
79
80
  onPersistentStorageError: PersistentStorageErrorHandler | undefined; /** Global fallback for mutation failures in attached stores. */
80
81
  onMutationError: StoreManagerMutationErrorHandler | undefined; /** Shared defaults used by attached stores unless a store-level override exists. */
@@ -99,12 +100,9 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
99
100
  blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
100
101
  onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
101
102
  onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
102
- revalidateOnWindowFocus?: boolean | (() => boolean);
103
- /**
104
- * Enables debug logs for browser-tab sync, focus revalidation, and persistent storage operations.
105
- * Pass `true` to use console logging, or pass a logger function.
106
- */
107
- debug?: TSDFDebugOptions; /** Optional shared offline session config for every attached store. */
103
+ revalidateOnWindowFocus?: boolean | (() => boolean); /** Enables verbose development-only logs. Pass `true` to use console logging, or pass a logger function. */
104
+ debugLogger?: TSDFLoggerOptions; /** Enables low-volume production-safe logs. Pass `true` to use console logging, or pass a logger function. */
105
+ prodLogger?: TSDFLoggerOptions; /** Optional shared offline session config for every attached store. */
108
106
  offlineSession?: OfflineSessionConfig<TUploadRef>;
109
107
  };
110
108
  declare function createStoreManager<TUploadRef extends ValidPayload = ValidPayload>(options: CreateStoreManagerOptions<TUploadRef>): StoreManager<TUploadRef>;
@@ -773,7 +771,13 @@ type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload ex
773
771
  type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
774
772
  /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
775
773
  filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
776
- appendNewTo?: 'start' | 'end'; /** Whether affected queries should still refetch after the optimistic list update. */
774
+ appendNewTo?: 'start' | 'end';
775
+ /**
776
+ * Schedules a background refetch of queries this rule mutated. Leave off
777
+ * unless the optimistic update can't represent the final server state —
778
+ * e.g. server-assigned sort fields (`updatedAt`, computed scores), server-
779
+ * only membership data (permissions), or cursor pagination shifts.
780
+ */
777
781
  invalidateQueries?: boolean; /** Sort order to maintain inside affected query pages. */
778
782
  sort?: {
779
783
  /** Selects sortable values from an item. */sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[]; /** Sort direction for each `sortBy` value. */
@@ -1513,4 +1517,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
1513
1517
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
1514
1518
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
1515
1519
  //#endregion
1516
- export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFDebugOptions, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
1520
+ export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFLoggerOptions, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as getNavigatorLockManager, C as isModeEffectivelyActive, D as clearSessionProtectedKeysSnapshot, E as offlineResolutionRecordSchema, H as serializeProtectedRef, L as getPayloadRecordKey, M as createCompactLocalStorageEntry, N as parseCompactLocalStorageEntry, O as getSessionProtectedKeysSnapshot, S as getIsOfflineModeFromStatus, T as offlineItemEntityRefSchema, U as scheduleIdleCleanup, V as parsePersistedAsyncNamespaceKind, _ as keepEntriesWithinByteBudget, a as estimateManagedAsyncStorageEntrySizeBytes, b as compactOfflineStatusSnapshotSchema, c as readAsyncStorageNamespaceIndexStateUsingDriver, d as unregisterAsyncStartupStoreCleanup, f as parseAsyncStorageNamespaceKind, g as getSerializedStringSize, h as createTimedKeySet, j as warnIfNavigatorLockUnavailable, k as setSessionProtectedKeysSnapshot, l as registerAsyncStartupStoreCleanup, m as createShouldIgnoreItemPredicate, o as getProtectedKeysFromMetadata, p as getDefaultMaxBytesForScope, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as serializeJsonForStorage, w as isOfflineModeStatusValue, x as defaultOfflineRuntimeConfig, y as OfflineResolutionConflictParseError } from "./asyncStorageAdapter-CSzvgl3s.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-3c1zSDZi.js";
1
+ import { A as offlineResolutionRecordSchema, C as OfflineResolutionConflictParseError, D as isModeEffectivelyActive, E as getIsOfflineModeFromStatus, F as warnIfNavigatorLockUnavailable, G as parsePersistedAsyncNamespaceKind, I as createCompactLocalStorageEntry, 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 scheduleIdleCleanup, r as buildPersistedStaticPolicy, s as mergeManagedAsyncStorageCustomMetadata, u as serializeProtectedRef$1, v as createShouldIgnoreItemPredicate, w as compactOfflineStatusSnapshotSchema, x as keepEntriesWithinByteBudget, y as createTimedKeySet } from "./asyncStorageAdapter-B1kF0Ojl.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-DcODOOJk.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";
@@ -964,39 +964,6 @@ function parsePersistedListQueryData(value, payloadSchema) {
964
964
  };
965
965
  }
966
966
  //#endregion
967
- //#region src/debug.ts
968
- function defaultConsoleDebugLogger(entry) {
969
- if (import.meta.env.DEV) {
970
- const consoleForLevel = globalThis.console[entry.level];
971
- if (typeof consoleForLevel !== "function") return;
972
- const details = entry.details ? {
973
- operation: entry.operation,
974
- ...entry.details
975
- } : { operation: entry.operation };
976
- consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
977
- }
978
- }
979
- function resolveTSDFDebugLogger(debug) {
980
- if (!import.meta.env.DEV) return void 0;
981
- if (debug === void 0 || debug === false) return void 0;
982
- if (debug === true) return defaultConsoleDebugLogger;
983
- return debug;
984
- }
985
- function emitTSDFDebugLog(logger, entry) {
986
- if (import.meta.env.DEV) {
987
- if (!logger) return;
988
- try {
989
- logger(entry);
990
- } catch (error) {
991
- globalThis.console.error("[tsdf:debug] Debug logger failed", error);
992
- }
993
- }
994
- }
995
- function getTSDFDebugTimingMs() {
996
- if (!import.meta.env.DEV) return 0;
997
- return Date.now();
998
- }
999
- //#endregion
1000
967
  //#region src/persistentStorage/offlineUploadRegistry.ts
1001
968
  const uploadAdaptersBySession = /* @__PURE__ */ new Map();
1002
969
  function registerOfflineUploadAdapterForSession(sessionKey, adapter) {
@@ -1242,14 +1209,12 @@ function createPersistentStorageDebugContext(adapter, storeName, debugLogger, en
1242
1209
  };
1243
1210
  }
1244
1211
  function startPersistentStorageDebugTiming(context) {
1245
- if (!import.meta.env.DEV) return null;
1246
- if (!context?.debugLogger) return null;
1247
- return context.adapterKind === "async" ? getTSDFDebugTimingMs() : null;
1212
+ return null;
1248
1213
  }
1249
1214
  function logPersistentStorageOperation(context, operation, status, startTime, details, error) {
1250
1215
  if (!import.meta.env.DEV) return;
1251
1216
  if (!context?.debugLogger) return;
1252
- const durationMs = startTime === null ? void 0 : getTSDFDebugTimingMs() - startTime;
1217
+ const durationMs = startTime === null ? void 0 : Date.now() - startTime;
1253
1218
  const logDetails = {
1254
1219
  adapter: context.adapterKind,
1255
1220
  storeName: context.storeName,
@@ -1421,6 +1386,8 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1421
1386
  if (asyncAdapter === null) return null;
1422
1387
  const sessionKey = config.getSessionKey();
1423
1388
  if (sessionKey === false) return null;
1389
+ asyncAdapter.debugLogger = config.debugLogger;
1390
+ asyncAdapter.prodLogger = config.prodLogger;
1424
1391
  return asyncAdapter.openNamespace({
1425
1392
  sessionKey,
1426
1393
  storeName: asyncNamespace?.storeName ?? config.storeName,
@@ -1625,6 +1592,8 @@ function createPersistentStorageNamespaceHandle(config, { asyncValueCodec, getMa
1625
1592
  if (asyncAdapter === null) return null;
1626
1593
  const sessionKey = config.getSessionKey();
1627
1594
  if (sessionKey === false) return null;
1595
+ asyncAdapter.debugLogger = config.debugLogger;
1596
+ asyncAdapter.prodLogger = config.prodLogger;
1628
1597
  return asyncAdapter.openNamespace({
1629
1598
  sessionKey,
1630
1599
  storeName: config.storeName,
@@ -2205,7 +2174,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2205
2174
  }
2206
2175
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2207
2176
  async function clearAllSessionStorage(sessionKey) {
2208
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-W8bChTBu.js");
2177
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CxkAFJbY.js");
2209
2178
  await Promise.all([
2210
2179
  clearSessionStorage(sessionKey, "local-sync"),
2211
2180
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -2332,6 +2301,26 @@ function setupCollectionPersistence(config, options = {}) {
2332
2301
  getManifestMeta: (data) => ({ p: data.payload }),
2333
2302
  valueCodec: itemStorageValueCodec
2334
2303
  });
2304
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
2305
+ function logByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
2306
+ const prodLogger = config.prodLogger;
2307
+ if (!prodLogger) return;
2308
+ const evictedEntries = totalEntries - keptKeys.size;
2309
+ if (evictedEntries === 0) return;
2310
+ logPersistentStorageQuotaCleanup({
2311
+ adapter: quotaCleanupAdapter,
2312
+ prodLogger,
2313
+ evictedEntries,
2314
+ keptEntries: keptKeys.size,
2315
+ maxBytes,
2316
+ namespaceKind: "collection.item",
2317
+ phase,
2318
+ quota: "maxBytes",
2319
+ storeName: config.storeName,
2320
+ totalEntries,
2321
+ unprotectedBytes
2322
+ });
2323
+ }
2335
2324
  function getAsyncNamespaceScope() {
2336
2325
  if (asyncStorageAdapter === null) return null;
2337
2326
  const sessionKey = config.getSessionKey();
@@ -2421,7 +2410,8 @@ function setupCollectionPersistence(config, options = {}) {
2421
2410
  protected: protectedItemKeys.has(itemKey),
2422
2411
  sizeBytes: rememberPersistedMetadataSize(itemKey, metadata.sizeBytes)
2423
2412
  }));
2424
- const keptKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2413
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, effectiveStaticPolicy.maxBytes);
2414
+ logByteBudgetCleanup("startup-cleanup", candidateEntries.length, keptKeys, unprotectedBytes);
2425
2415
  for (const { itemKey } of candidateEntries) {
2426
2416
  if (keptKeys.has(itemKey)) continue;
2427
2417
  deleteKeys.add(getPayloadRecordKey(itemKey));
@@ -2686,7 +2676,8 @@ function setupCollectionPersistence(config, options = {}) {
2686
2676
  await Promise.all(ignoredEntries.map(({ itemKey }) => namespace.remove(itemKey)));
2687
2677
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2688
2678
  }
2689
- const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2679
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2680
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2690
2681
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2691
2682
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2692
2683
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2714,7 +2705,8 @@ function setupCollectionPersistence(config, options = {}) {
2714
2705
  for (const { itemKey } of ignoredEntries) forgetPersistedItem(itemKey);
2715
2706
  }
2716
2707
  const filteredEntries = validEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
2717
- const keptKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2708
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxBytes);
2709
+ logByteBudgetCleanup("maintenance", filteredEntries.length, keptKeys, unprotectedBytes);
2718
2710
  await Promise.all(filteredEntries.filter(({ itemKey }) => !keptKeys.has(itemKey)).map(({ itemKey }) => namespace.remove(itemKey)));
2719
2711
  for (const { itemKey } of filteredEntries) if (!keptKeys.has(itemKey)) forgetPersistedItem(itemKey);
2720
2712
  knownPersistedKeys = new Set(filteredEntries.filter(({ itemKey }) => keptKeys.has(itemKey)).map(({ itemKey }) => itemKey));
@@ -2837,7 +2829,8 @@ function setupCollectionPersistence(config, options = {}) {
2837
2829
  if (metadataByKey.has(entry.itemKey)) pendingRemoves.add(entry.itemKey);
2838
2830
  }
2839
2831
  const remainingCandidates = candidateEntries.filter(({ itemKey }) => !pendingRemoves.has(itemKey));
2840
- const keptKeys = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2832
+ const { keptKeys, unprotectedBytes } = keepEntriesWithinByteBudget(remainingCandidates, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.protected, maxBytes);
2833
+ logByteBudgetCleanup("flush", remainingCandidates.length, keptKeys, unprotectedBytes);
2841
2834
  if (keptKeys.size !== remainingCandidates.length) {
2842
2835
  for (const { itemKey } of remainingCandidates) {
2843
2836
  if (keptKeys.has(itemKey)) continue;
@@ -7555,7 +7548,8 @@ function createDisabledStoreManagerOfflineApi(getSessionKey) {
7555
7548
  };
7556
7549
  }
7557
7550
  function createStoreManager(options) {
7558
- const debugLogger = import.meta.env.DEV ? resolveTSDFDebugLogger(options.debug) : void 0;
7551
+ const debugLogger = import.meta.env.DEV ? resolveTSDFLogger(options.debugLogger) : void 0;
7552
+ const prodLogger = resolveTSDFLogger(options.prodLogger);
7559
7553
  let resolvedOfflineSession;
7560
7554
  if (options.offlineSession) {
7561
7555
  const createOfflineSessionOptions = {
@@ -7620,7 +7614,8 @@ function createStoreManager(options) {
7620
7614
  },
7621
7615
  ...offlineApi
7622
7616
  };
7623
- if (debugLogger !== void 0) storeManager.debugLogger = debugLogger;
7617
+ storeManager.debugLogger = debugLogger;
7618
+ storeManager.prodLogger = prodLogger;
7624
7619
  storeManagerRegistry.set(storeManager, registry);
7625
7620
  storeManagerOfflineSessionRegistry.set(storeManager, resolvedOfflineSession);
7626
7621
  return storeManager;
@@ -8533,7 +8528,8 @@ function createCollectionStore(storeOptions) {
8533
8528
  ...persistentStorageConfig.offline,
8534
8529
  session: resolvedOfflineSessionForPersistentStorage
8535
8530
  } : void 0,
8536
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
8531
+ debugLogger: storeManager.debugLogger,
8532
+ prodLogger: storeManager.prodLogger,
8537
8533
  getSessionKey: getSessionKeyForRuntime,
8538
8534
  storeName: id
8539
8535
  }) : null;
@@ -9620,7 +9616,8 @@ function createDocumentStore(storeOptions) {
9620
9616
  ...persistentStorageConfig.offline,
9621
9617
  session: resolvedOfflineSessionForPersistentStorage
9622
9618
  } : void 0,
9623
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
9619
+ debugLogger: storeManager.debugLogger,
9620
+ prodLogger: storeManager.prodLogger,
9624
9621
  getSessionKey: getSessionKeyForRuntime,
9625
9622
  storeName: id
9626
9623
  }) : null;
@@ -10302,6 +10299,45 @@ function setupListQueryPersistence(config, options = {}) {
10302
10299
  p: data.payload
10303
10300
  })
10304
10301
  });
10302
+ const quotaCleanupAdapter = localStorageAdapter === null ? "async" : "local-sync";
10303
+ function logQueryByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10304
+ const prodLogger = config.prodLogger;
10305
+ if (!prodLogger) return;
10306
+ const evictedEntries = totalEntries - keptKeys.size;
10307
+ if (evictedEntries === 0) return;
10308
+ logPersistentStorageQuotaCleanup({
10309
+ adapter: quotaCleanupAdapter,
10310
+ prodLogger,
10311
+ evictedEntries,
10312
+ keptEntries: keptKeys.size,
10313
+ maxBytes: maxQueryBytes,
10314
+ namespaceKind: "listQuery.query",
10315
+ phase,
10316
+ quota: "maxQueryBytes",
10317
+ storeName: config.storeName,
10318
+ totalEntries,
10319
+ unprotectedBytes
10320
+ });
10321
+ }
10322
+ function logItemByteBudgetCleanup(phase, totalEntries, keptKeys, unprotectedBytes) {
10323
+ const prodLogger = config.prodLogger;
10324
+ if (!prodLogger) return;
10325
+ const evictedEntries = totalEntries - keptKeys.size;
10326
+ if (evictedEntries === 0) return;
10327
+ logPersistentStorageQuotaCleanup({
10328
+ adapter: quotaCleanupAdapter,
10329
+ prodLogger,
10330
+ evictedEntries,
10331
+ keptEntries: keptKeys.size,
10332
+ maxBytes: maxItemBytes,
10333
+ namespaceKind: "listQuery.item",
10334
+ phase,
10335
+ quota: "maxItemBytes",
10336
+ storeName: config.storeName,
10337
+ totalEntries,
10338
+ unprotectedBytes
10339
+ });
10340
+ }
10305
10341
  function getAsyncItemNamespaceScope() {
10306
10342
  if (asyncStorageAdapter === null) return null;
10307
10343
  const sessionKey = config.getSessionKey();
@@ -11087,7 +11123,8 @@ function setupListQueryPersistence(config, options = {}) {
11087
11123
  };
11088
11124
  });
11089
11125
  if (invalidPayloadQueryKeys.length > 0) await Promise.all(invalidPayloadQueryKeys.map((queryKey) => removeLocalStorageQueryEntry(queryKey)));
11090
- const keptQueryKeys = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11126
+ const { keptKeys: keptQueryKeys, unprotectedBytes } = keepEntriesWithinByteBudget(filteredEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11127
+ logQueryByteBudgetCleanup("maintenance", filteredEntries.length, keptQueryKeys, unprotectedBytes);
11091
11128
  await Promise.all(filteredEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => removeLocalStorageQueryEntry(queryKey)));
11092
11129
  for (const { queryKey } of filteredEntries) if (!keptQueryKeys.has(queryKey)) forgetPersistedQuery(queryKey);
11093
11130
  knownPersistedQueryKeys = keptQueryKeys;
@@ -11111,7 +11148,8 @@ function setupListQueryPersistence(config, options = {}) {
11111
11148
  });
11112
11149
  }
11113
11150
  if (invalidQueryKeys.length > 0) await Promise.all(invalidQueryKeys.map((queryKey) => queryNamespace.remove(queryKey)));
11114
- const keptQueryKeys = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11151
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(validEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => protectedQueryKeys.has(entry.queryKey), maxQueryBytes);
11152
+ logQueryByteBudgetCleanup("maintenance", validEntries.length, keptQueryKeys, queryUnprotectedBytes);
11115
11153
  await Promise.all(validEntries.filter(({ queryKey }) => !keptQueryKeys.has(queryKey)).map(({ queryKey }) => queryNamespace.remove(queryKey)));
11116
11154
  for (const entry of validEntries) {
11117
11155
  const { queryKey } = entry;
@@ -11150,7 +11188,8 @@ function setupListQueryPersistence(config, options = {}) {
11150
11188
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11151
11189
  }
11152
11190
  const persistedItemEntries = hydratedItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11153
- const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11191
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11192
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11154
11193
  const evictedItemKeys = /* @__PURE__ */ new Set();
11155
11194
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => {
11156
11195
  evictedItemKeys.add(itemKey);
@@ -11200,7 +11239,8 @@ function setupListQueryPersistence(config, options = {}) {
11200
11239
  for (const { itemKey } of ignoredItemEntries) forgetPersistedItem(itemKey);
11201
11240
  }
11202
11241
  const persistedItemEntries = validItemEntries.filter(({ payload }) => !shouldIgnoreItem(payload));
11203
- const keptItemKeys = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11242
+ const { keptKeys: keptItemKeys, unprotectedBytes } = keepEntriesWithinByteBudget(persistedItemEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => protectedItemKeys.has(entry.itemKey), maxItemBytes);
11243
+ logItemByteBudgetCleanup("maintenance", persistedItemEntries.length, keptItemKeys, unprotectedBytes);
11204
11244
  await Promise.all(persistedItemEntries.filter(({ itemKey }) => !keptItemKeys.has(itemKey)).map(({ itemKey }) => itemNamespace.remove(itemKey)));
11205
11245
  for (const { itemKey } of persistedItemEntries) if (!keptItemKeys.has(itemKey)) forgetPersistedItem(itemKey);
11206
11246
  knownPersistedItemKeys = keptItemKeys;
@@ -11464,7 +11504,8 @@ function setupListQueryPersistence(config, options = {}) {
11464
11504
  sizeBytes
11465
11505
  });
11466
11506
  }
11467
- const keptQueryKeys = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11507
+ const { keptKeys: keptQueryKeys, unprotectedBytes: queryUnprotectedBytes } = keepEntriesWithinByteBudget(candidateEntries, (entry) => entry.queryKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedQueryKeys.has(entry.queryKey), (entry) => entry.offlineProtected, maxQueryBytes);
11508
+ logQueryByteBudgetCleanup("flush", candidateEntries.length, keptQueryKeys, queryUnprotectedBytes);
11468
11509
  finalPersistedQueryKeys.clear();
11469
11510
  for (const queryKey of keptQueryKeys) finalPersistedQueryKeys.add(queryKey);
11470
11511
  const evictedQueryKeys = [];
@@ -11556,7 +11597,8 @@ function setupListQueryPersistence(config, options = {}) {
11556
11597
  sizeBytes
11557
11598
  });
11558
11599
  }
11559
- const keptItemKeys = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11600
+ const { keptKeys: keptItemKeys, unprotectedBytes: itemUnprotectedBytes } = keepEntriesWithinByteBudget(itemCandidateEntries, (entry) => entry.itemKey, (entry) => entry.lastAccessAt, (entry) => entry.sizeBytes, (entry) => pinnedItemKeys.has(entry.itemKey), (entry) => entry.offlineProtected, maxItemBytes);
11601
+ logItemByteBudgetCleanup("flush", itemCandidateEntries.length, keptItemKeys, itemUnprotectedBytes);
11560
11602
  finalPersistedItemKeys.clear();
11561
11603
  for (const itemKey of keptItemKeys) finalPersistedItemKeys.add(itemKey);
11562
11604
  const evictedItemKeys = [];
@@ -14667,7 +14709,8 @@ function createListQueryStore(storeOptions) {
14667
14709
  ...persistentStorageConfig.offline,
14668
14710
  session: resolvedOfflineSessionForPersistentStorage
14669
14711
  } : void 0,
14670
- ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
14712
+ debugLogger: storeManager.debugLogger,
14713
+ prodLogger: storeManager.prodLogger,
14671
14714
  getSessionKey: getSessionKeyForRuntime,
14672
14715
  storeName: id
14673
14716
  }) : null;
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-C6KKLdos.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-B0QmznAg.js";
2
2
  export { opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-3c1zSDZi.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DcODOOJk.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-DqUm_Sv7.js";
1
+ import { t as AsyncStorageAdapter } from "./types-hwf0jXKv.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -1,4 +1,4 @@
1
- import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, I as getNamespaceId, L as getPayloadRecordKey, V as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter } from "./asyncStorageAdapter-CSzvgl3s.js";
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-B1kF0Ojl.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";
@@ -134,6 +134,7 @@ async function getFileHandleIfExists(parent, name) {
134
134
  const OPFS_DIR_HANDLE_CACHE_MAX_SIZE = 500;
135
135
  const OPFS_FILE_HANDLE_CACHE_MAX_SIZE = 1e4;
136
136
  var OpfsAsyncStorageDriver = class {
137
+ debugLogger;
137
138
  #rootDirPromise = null;
138
139
  #mainCacheContext = {
139
140
  cleanupKnowledge: null,
@@ -247,7 +248,15 @@ var OpfsAsyncStorageDriver = class {
247
248
  storeDir
248
249
  });
249
250
  if (fileHandle === null) return null;
250
- return this.#readJsonFile(this.#getFilePath(scope, key), fileHandle, cacheContext);
251
+ const filePath = this.#getFilePath(scope, key);
252
+ if (!import.meta.env.DEV || !this.debugLogger) return this.#readJsonFile(filePath, fileHandle, cacheContext);
253
+ const startTime = getTSDFDebugTimingMs();
254
+ return this.#readJsonFile(filePath, fileHandle, cacheContext).finally(() => {
255
+ this.#logAdapterOperation(scope, "read-file", startTime, {
256
+ filePath,
257
+ key
258
+ });
259
+ });
251
260
  }));
252
261
  }
253
262
  async #setManyWithContext(scope, entries, cacheContext) {
@@ -265,10 +274,20 @@ var OpfsAsyncStorageDriver = class {
265
274
  if (await this.#removeWholeStoreDirIfAllKnownEntriesAreBeingRemoved(scope, uniqueKeys, cacheContext)) return;
266
275
  const removeResults = await Promise.all(uniqueKeys.map(async (key) => {
267
276
  const fileName = buildFileName(scope, key);
277
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
268
278
  try {
269
279
  await storeDir.removeEntry(fileName);
280
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
281
+ fileName,
282
+ key
283
+ });
270
284
  return true;
271
285
  } catch {
286
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
287
+ fileName,
288
+ key,
289
+ status: "miss"
290
+ });
272
291
  return false;
273
292
  } finally {
274
293
  this.#invalidateFileHandle(scope, key, cacheContext);
@@ -279,8 +298,14 @@ var OpfsAsyncStorageDriver = class {
279
298
  await this.#pruneEmptyDirectories(scope, cacheContext);
280
299
  }
281
300
  async #listKeysWithContext(scope, cacheContext) {
301
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
282
302
  const { resolvedEntries } = await this.#listScopedFiles(scope, cacheContext);
283
- return resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
303
+ const keys = resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
304
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-directory", startTime, {
305
+ count: keys.length,
306
+ storeDirPath: this.#getStoreDirPath(scope)
307
+ });
308
+ return keys;
284
309
  }
285
310
  async #clearWithContext(scope, cacheContext) {
286
311
  const storeDir = await this.#getStoreDir(scope, {
@@ -633,11 +658,17 @@ var OpfsAsyncStorageDriver = class {
633
658
  if (fileHandle === null) throw new Error("[TSDF] Failed to open OPFS file handle.");
634
659
  const writable = await fileHandle.createWritable();
635
660
  const rawValue = entry.serializedValue ?? JSON.stringify(entry.value);
661
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
636
662
  try {
637
663
  await writable.write(rawValue);
638
664
  } finally {
639
665
  await writable.close();
640
666
  }
667
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-file", startTime, {
668
+ filePath: this.#getFilePath(scope, entry.key),
669
+ key: entry.key,
670
+ sizeBytes: rawValue.length
671
+ });
641
672
  cacheContext.readValueCache?.set(this.#getFilePath(scope, entry.key), entry.value);
642
673
  return;
643
674
  } catch (error) {
@@ -648,6 +679,29 @@ var OpfsAsyncStorageDriver = class {
648
679
  this.#invalidateDirectory(this.#getSessionDirPath(scope.sessionKey), cacheContext);
649
680
  }
650
681
  }
682
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
683
+ if (!import.meta.env.DEV) return;
684
+ if (startTime === null) return;
685
+ if (!this.debugLogger) return;
686
+ const status = typeof details.status === "string" ? details.status : "success";
687
+ emitTSDFDebugLog(this.debugLogger, {
688
+ area: "persistent-storage",
689
+ level: "log",
690
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
691
+ operation: "adapter-operation",
692
+ details: {
693
+ adapter: "async",
694
+ adapterName: "opfs",
695
+ adapterOperation,
696
+ durationMs: getTSDFDebugTimingMs() - startTime,
697
+ namespaceKind: scope.kind,
698
+ sessionKey: scope.sessionKey,
699
+ status,
700
+ storeName: scope.storeName,
701
+ ...details
702
+ }
703
+ });
704
+ }
651
705
  async #cleanupRemoveKnownRecordsWithContext(scope, keys, cacheContext) {
652
706
  if (keys.length === 0) return [];
653
707
  const storeDir = await this.#getStoreDir(scope, {
@@ -11,7 +11,7 @@ type TSDFDebugLogArea = 'browser-tabs' | 'focus' | 'persistent-storage';
11
11
  /** Operations emitted by focus lifecycle handling. */
12
12
  type TSDFFocusDebugOperation = 'window-focus-revalidate';
13
13
  /** Operations emitted by the persistent storage subsystem. */
14
- type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
14
+ type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'adapter-operation' | 'quota-cleanup' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
15
15
  /** Operations emitted by the browser-tab sync subsystem. */
16
16
  type TSDFBrowserTabsDebugOperation = 'leader-change' | 'publish' | 'publish-skipped' | 'receive' | 'receive-skipped' | 'session-change' | 'transport-close' | 'transport-open' | 'transport-unavailable';
17
17
  /** Structured debug log entry emitted by TSDF internals. */
@@ -24,8 +24,8 @@ type TSDFDebugLogEntry = {
24
24
  };
25
25
  /** Custom debug logger invoked for each emitted TSDF debug entry. */
26
26
  type TSDFDebugLogger = (entry: TSDFDebugLogEntry) => void;
27
- /** Enables manager-wide debug logging for browser-tab sync and persistence. */
28
- type TSDFDebugOptions = boolean | TSDFDebugLogger;
27
+ /** Logger option used by manager-wide debug and production-signal logging. */
28
+ type TSDFLoggerOptions = boolean | TSDFDebugLogger;
29
29
  //#endregion
30
30
  //#region src/requestScheduler.d.ts
31
31
  type RequestSchedulerEvents = 'scheduled-fetch-started' | 'rt-fetch-scheduled' | 'rt-fetch-cancelled' | 'scheduled-rt-fetch-started' | 'medium-priority-scheduled' | 'medium-priority-fetch-started' | 'medium-priority-cancelled' | 'batch-size-triggered';
@@ -1314,7 +1314,9 @@ type AsyncStorageDiscoveredScope = {
1314
1314
  };
1315
1315
  /** Low-level async backend contract implemented by custom storage drivers. */
1316
1316
  type AsyncStorageDriver = {
1317
- /** Read a single raw record from a logical namespace. */get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1317
+ /** Mutable debug logger used by concrete adapters to emit operation timings. */debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1318
+ prodLogger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
1319
+ get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1318
1320
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
1319
1321
  remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
1320
1322
  listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
@@ -1345,7 +1347,9 @@ type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string,
1345
1347
  };
1346
1348
  /** Managed async adapter consumed by TSDF persistence internals. */
1347
1349
  type AsyncStorageAdapter = {
1348
- /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
1350
+ /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Mutable debug logger used by concrete adapters to emit operation timings. */
1351
+ debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1352
+ prodLogger?: TSDFDebugLogger; /** Open a logical namespace with managed batching and touch guarantees. */
1349
1353
  openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
1350
1354
  readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
1351
1355
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
@@ -1474,4 +1478,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
1474
1478
  /** Persistent storage config for ListQueryStore. */
1475
1479
  type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
1476
1480
  //#endregion
1477
- export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, PayloadDebounce as At, OfflineEntityMutationKind as B, mutationSkipped as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, TSDFStatus as Ft, OfflineMutationQueueingPolicy as G, ScheduleFetchResults as Gt, OfflineMutationInput as H, RequestSchedulerEventData as Ht, ListQueryOfflineOperationDefinition as I, UnwrapTSDFResult as It, OfflineReplayRetryConfig as J, TSDFDebugLogLevel as Jt, OfflineOperationKind as K, TSDFDebugLogArea as Kt, OfflineAccumulationConfig as L, ValidPayload as Lt, DocumentOfflineOperationDefinition as M, StoreFetchError as Mt, GlobalOfflineEntity as N, StoreMutationError as Nt, DefineCollectionOfflineOperations as O, MaybeTSDFResult as Ot, GlobalOfflineStatus as P, StoreMutationErrorOptions as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, ValidStoreState as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, RequestSchedulerEvents as Ut, OfflineMutationDescriptor as V, FetchType as Vt, OfflineMutationQueueingConfig as W, ScheduleFetchOptions as Wt, OfflineResolutionActionForOperation as X, TSDFDebugOptions as Xt, OfflineResolutionAction as Y, TSDFDebugLogger as Yt, OfflineResolutionConflictParseError as Z, TSDFFocusDebugOperation as Zt, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreError as jt, DefineDocumentOfflineOperations as k, MutationSkipped as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, TSDFDebugLogEntry as qt, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, fetchTypePriority as zt };
1481
+ export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, PayloadDebounce as At, OfflineEntityMutationKind as B, mutationSkipped as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, TSDFStatus as Ft, OfflineMutationQueueingPolicy as G, ScheduleFetchResults as Gt, OfflineMutationInput as H, RequestSchedulerEventData as Ht, ListQueryOfflineOperationDefinition as I, UnwrapTSDFResult as It, OfflineReplayRetryConfig as J, TSDFDebugLogLevel as Jt, OfflineOperationKind as K, TSDFDebugLogArea as Kt, OfflineAccumulationConfig as L, ValidPayload as Lt, DocumentOfflineOperationDefinition as M, StoreFetchError as Mt, GlobalOfflineEntity as N, StoreMutationError as Nt, DefineCollectionOfflineOperations as O, MaybeTSDFResult as Ot, GlobalOfflineStatus as P, StoreMutationErrorOptions as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, ValidStoreState as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, RequestSchedulerEvents as Ut, OfflineMutationDescriptor as V, FetchType as Vt, OfflineMutationQueueingConfig as W, ScheduleFetchOptions as Wt, OfflineResolutionActionForOperation as X, TSDFFocusDebugOperation as Xt, OfflineResolutionAction as Y, TSDFDebugLogger as Yt, OfflineResolutionConflictParseError as Z, TSDFLoggerOptions as Zt, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreError as jt, DefineDocumentOfflineOperations as k, MutationSkipped as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, TSDFDebugLogEntry as qt, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, fetchTypePriority as zt };
@@ -35,7 +35,7 @@ Tabs use a versioned message model so later snapshots do not overwrite fresher r
35
35
  - When `sessionKey` changes (for example, login/logout), sync state is refreshed for the new session.
36
36
  - If transport is unavailable, sync becomes inactive silently.
37
37
 
38
- Enable `createStoreManager({ debug: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debug` to route those entries to your own observability tool.
38
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes in development. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debugLogger` to route those entries to your own tooling.
39
39
 
40
40
  ## Required options
41
41
 
@@ -30,9 +30,6 @@ const taskStore = createListQueryStore<Task, TaskFilter, string>({
30
30
 
31
31
  // Where to add new items
32
32
  appendNewTo: 'start',
33
-
34
- // Trigger background revalidation when items are moved
35
- invalidateQueries: true,
36
33
  },
37
34
  {
38
35
  // Sort a specific query by priority
@@ -112,7 +109,9 @@ Sorting is applied only to queries that contain the updated item.
112
109
 
113
110
  ### invalidateQueries
114
111
 
115
- When `true`, queries affected by the optimistic update are invalidated in the background. This ensures the server's actual ordering/filtering is fetched eventually.
112
+ Schedules a background refetch of queries this rule mutated.
113
+
114
+ **Leave off by default.** Only enable when the optimistic update can't represent the final server state — e.g. sort depends on a server-assigned field (`updatedAt`, computed score), membership depends on server-only data (permissions, full-text match), or cursor pagination shifts the page window. If `filterItem` and `sort` already match the server, the extra refetch is just noise.
116
115
 
117
116
  ```ts
118
117
  invalidateQueries: true;
@@ -149,31 +148,28 @@ const taskStore = createListQueryStore<Task, { status: string }, string>({
149
148
  fetchItemFn: (id, { signal }) => api.getTask(id, signal),
150
149
 
151
150
  optimisticListUpdates: [
152
- {
153
- // Move tasks between status columns
154
- queries: (q) => true,
155
- filterItem: (item) => item.status === 'todo',
156
- // Only applies to queries where status matches
157
- },
151
+ // Membership follows status — the optimistic change is final.
158
152
  {
159
153
  queries: { status: 'todo' },
160
154
  filterItem: (item) => item.status === 'todo',
161
155
  appendNewTo: 'start',
162
- invalidateQueries: true,
163
156
  },
164
157
  {
165
158
  queries: { status: 'done' },
166
159
  filterItem: (item) => item.status === 'done',
167
160
  appendNewTo: 'end',
161
+ },
162
+ // Server sorts by `updatedAt`, which it assigns — refetch to settle order.
163
+ {
164
+ queries: (q) => true,
165
+ sort: { sortBy: (item) => item.updatedAt, order: 'desc' },
168
166
  invalidateQueries: true,
169
167
  },
170
168
  ],
171
169
  });
172
170
 
173
- // When a task is moved to "done", it's automatically:
174
- // 1. Removed from the "todo" query
175
- // 2. Added to the "done" query
176
- // 3. Both queries are revalidated in the background
171
+ // Moving "task-1" to done removes it from the todo query and adds it to the
172
+ // done query. Only the sort rule triggers a background refetch.
177
173
  taskStore.updateItemState('task-1', (draft) => {
178
174
  draft.status = 'done';
179
175
  });
@@ -64,7 +64,7 @@ Store-specific options:
64
64
 
65
65
  > `persistentStorage` automatically reuses the store's existing `id` for its storage namespace and the store manager's `getSessionKey` for session scoping. When `getSessionKey` returns `false`, no persistence operations run.
66
66
 
67
- Enable `createStoreManager({ debug: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations. Async adapters include `durationMs` on debug entries so OPFS, IndexedDB, or custom driver performance can be inspected.
67
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations in development. Enable `createStoreManager({ prodLogger: true, ... })` to receive production-safe quota cleanup logs; they include the affected quota, configured byte budget, total unprotected bytes, and kept/evicted entry counts. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work in development.
68
68
 
69
69
  ## Converted Data Schemas
70
70
 
@@ -29,7 +29,8 @@ const storeManager = createStoreManager({
29
29
  onPersistentStorageError: (error) => {
30
30
  console.error('TSDF persistence failed', error);
31
31
  },
32
- debug: true,
32
+ debugLogger: true,
33
+ prodLogger: true,
33
34
  });
34
35
  ```
35
36
 
@@ -47,7 +48,8 @@ Options:
47
48
  | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
48
49
  | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
49
50
  | `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
50
- | `debug` | No | Enables browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
51
+ | `debugLogger` | No | Enables verbose development-only browser-tab sync, focus revalidation, and persistent-storage debug logs. Pass `true` or a logger function. |
52
+ | `prodLogger` | No | Enables low-volume production-safe logs such as persistent-storage quota cleanup. Pass `true` or a logger function. |
51
53
  | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
52
54
 
53
55
  The session key is used by browser-tab sync, persistent storage, and offline state. Stores with the same `id` but different session keys are isolated.
@@ -58,13 +60,18 @@ Store-level options can explicitly disable inherited defaults when the option su
58
60
 
59
61
  ## Debug Logging
60
62
 
61
- Pass `debug: true` to log browser-tab sync operations, focus revalidation decisions, and persistent-storage operations through `console.log`, `console.warn`, and `console.error`. Browser-tab sync logs include lifecycle, leader changes, publish/receive events, and skipped messages. Focus revalidation logs report when `revalidateOnWindowFocus` triggers, is dynamically disabled, or is skipped because real-time updates own freshness. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Async persistent storage logs include `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
63
+ Pass `debugLogger: true` to log browser-tab sync operations, focus revalidation decisions, and persistent-storage operations through `console.log`, `console.warn`, and `console.error` in development. Browser-tab sync logs include lifecycle, leader changes, publish/receive events, and skipped messages. Focus revalidation logs report when `revalidateOnWindowFocus` triggers, is dynamically disabled, or is skipped because real-time updates own freshness. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Async persistent storage adapters emit timed `adapter-operation` entries with `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
64
+
65
+ Pass `prodLogger: true` to log low-volume production-safe signals. Today this includes persistent-storage `quota-cleanup` entries.
62
66
 
63
67
  ```ts
64
68
  const storeManager = createStoreManager({
65
69
  getSessionKey: () => currentTenantId ?? false,
66
70
  errorNormalizer: normalizeError,
67
- debug: ({ level, message, details }) => {
71
+ debugLogger: ({ level, message, details }) => {
72
+ observability[level](message, details);
73
+ },
74
+ prodLogger: ({ level, message, details }) => {
68
75
  observability[level](message, details);
69
76
  },
70
77
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "17.0.0-alpha.12",
3
+ "version": "17.0.0-alpha.14",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",
@@ -98,7 +98,7 @@
98
98
  "format": "oxfmt src/ tests/ apps/playground/src/",
99
99
  "tsc": "tsgo -p tsconfig.prod.json && tsgo -p tsconfig.playwright-fixture.json",
100
100
  "tsc:isolated": "tsgo -p tsconfig.isolated.json",
101
- "playground": "pnpm --filter @tsdf/playground dev",
101
+ "dev": "pnpm --filter @tsdf/playground dev",
102
102
  "playground:build": "pnpm --filter @tsdf/playground build",
103
103
  "build": "pnpm lint && pnpm test:all && pnpm build:no-test",
104
104
  "build:no-test": "tsdown",