tsdf 17.0.0-alpha.11 → 17.0.0-alpha.13

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-BMYAF6rt.js";
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-JtfdnFhk.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-BaojFC2B.js";
2
2
  export { createAsyncStorageAdapter };
@@ -830,6 +830,7 @@ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
830
830
  var ManagedAsyncStorageAdapter = class {
831
831
  kind = "async";
832
832
  #driver;
833
+ #debugLogger;
833
834
  #cachedNamespaceIndexReads = createCache({ maxCacheSize: ASYNC_STORAGE_NAMESPACE_INDEX_CACHE_MAX_SIZE });
834
835
  #cachedPayloadReads = createCache({ maxCacheSize: ASYNC_STORAGE_PAYLOAD_CACHE_MAX_SIZE });
835
836
  #namespaceReadCacheGenerations = /* @__PURE__ */ new Map();
@@ -842,6 +843,13 @@ var ManagedAsyncStorageAdapter = class {
842
843
  this.#driver = driver;
843
844
  registerAsyncStorageReadCacheParticipant(this);
844
845
  }
846
+ get debugLogger() {
847
+ return this.#debugLogger;
848
+ }
849
+ set debugLogger(debugLogger) {
850
+ this.#debugLogger = debugLogger;
851
+ this.#driver.debugLogger = debugLogger;
852
+ }
845
853
  async #runWithSessionWriterLock(sessionKey, callback) {
846
854
  return runWithNavigatorLock(`${ASYNC_STORAGE_WRITER_LOCK_NAME_PREFIX}${sessionKey}`, ASYNC_STORAGE_WRITER_LOCK_WARNING, callback);
847
855
  }
@@ -1,4 +1,4 @@
1
- import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-2zQlbxtw.js";
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-CNuCgLRs.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-5jUV7H9_.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-DqBAsrTX.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -0,0 +1,34 @@
1
+ //#region src/debug.ts
2
+ function defaultConsoleDebugLogger(entry) {
3
+ if (import.meta.env.DEV) {
4
+ const consoleForLevel = globalThis.console[entry.level];
5
+ if (typeof consoleForLevel !== "function") return;
6
+ const details = entry.details ? {
7
+ operation: entry.operation,
8
+ ...entry.details
9
+ } : { operation: entry.operation };
10
+ consoleForLevel(`[tsdf:${entry.area}] ${entry.message}`, details);
11
+ }
12
+ }
13
+ function resolveTSDFDebugLogger(debug) {
14
+ if (!import.meta.env.DEV) return void 0;
15
+ if (debug === void 0 || debug === false) return void 0;
16
+ if (debug === true) return defaultConsoleDebugLogger;
17
+ return debug;
18
+ }
19
+ function emitTSDFDebugLog(logger, entry) {
20
+ if (import.meta.env.DEV) {
21
+ if (!logger) return;
22
+ try {
23
+ logger(entry);
24
+ } catch (error) {
25
+ globalThis.console.error("[tsdf:debug] Debug logger failed", error);
26
+ }
27
+ }
28
+ }
29
+ function getTSDFDebugTimingMs() {
30
+ if (!import.meta.env.DEV) return 0;
31
+ return Date.now();
32
+ }
33
+ //#endregion
34
+ export { getTSDFDebugTimingMs as n, resolveTSDFDebugLogger as r, emitTSDFDebugLog as t };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-2zQlbxtw.js";
1
+ import { t as AsyncStorageAdapter } from "./types-CNuCgLRs.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-DqBAsrTX.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +1,5 @@
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 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-BaojFC2B.js";
2
+ import { n as getTSDFDebugTimingMs, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
2
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
3
4
  import { isObject } from "@ls-stack/utils/typeGuards";
4
5
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
@@ -244,6 +245,7 @@ async function setMaintenanceState(database, value) {
244
245
  await transactionDone(transaction);
245
246
  }
246
247
  var IndexedDbAsyncStorageDriver = class {
248
+ debugLogger;
247
249
  __tsdfManagedStorage = {
248
250
  applyManagedCommit: this.applyManagedCommit.bind(this),
249
251
  clearManagedNamespace: this.clearManagedNamespace.bind(this),
@@ -315,6 +317,7 @@ var IndexedDbAsyncStorageDriver = class {
315
317
  }
316
318
  }
317
319
  async removeMany(scope, keys) {
320
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
318
321
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
319
322
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
320
323
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -339,6 +342,10 @@ var IndexedDbAsyncStorageDriver = class {
339
342
  };
340
343
  }
341
344
  await transactionDone(transaction);
345
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-records", startTime, {
346
+ keyCount: keys.length,
347
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE]
348
+ });
342
349
  this.#instrumentation?.onRemoveMany?.(scope, keys);
343
350
  this.#instrumentation?.record({
344
351
  keys: [...keys].sort((left, right) => left.localeCompare(right)),
@@ -361,6 +368,7 @@ var IndexedDbAsyncStorageDriver = class {
361
368
  return (await this.listScopesWithKnownRecordKeys(sessionKey)).map(({ scope }) => scope);
362
369
  }
363
370
  async listScopesWithKnownRecordKeys(sessionKey) {
371
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
364
372
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readonly");
365
373
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
366
374
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -380,6 +388,11 @@ var IndexedDbAsyncStorageDriver = class {
380
388
  });
381
389
  });
382
390
  await transactionDone(transaction);
391
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(void 0, "list-scopes", startTime, {
392
+ count: discoveredScopes.length,
393
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
394
+ ...sessionKey !== void 0 ? { sessionKey } : {}
395
+ });
383
396
  discoveredScopes.sort((left, right) => getNamespaceId(left.scope).localeCompare(getNamespaceId(right.scope)));
384
397
  this.#instrumentation?.record({
385
398
  scopeIds: discoveredScopes.map(({ scope }) => getNamespaceId(scope)),
@@ -390,6 +403,7 @@ var IndexedDbAsyncStorageDriver = class {
390
403
  return discoveredScopes;
391
404
  }
392
405
  async readManagedEntries(scope, keys) {
406
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
393
407
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
394
408
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
395
409
  const uniqueKeys = [...new Set(keys)];
@@ -407,6 +421,11 @@ var IndexedDbAsyncStorageDriver = class {
407
421
  });
408
422
  }));
409
423
  await transactionDone(transaction);
424
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "read-records", startTime, {
425
+ hitCount: [...result.values()].filter((value) => value !== null).length,
426
+ keyCount: uniqueKeys.length,
427
+ objectStores: [INDEXED_DB_ENTRY_STORE]
428
+ });
410
429
  this.#instrumentation?.record({
411
430
  keys: uniqueKeys,
412
431
  resultKeys: [...result.entries()].flatMap(([key, value]) => value === null ? [] : [key]).sort((left, right) => left.localeCompare(right)),
@@ -417,6 +436,7 @@ var IndexedDbAsyncStorageDriver = class {
417
436
  return result;
418
437
  }
419
438
  async listManagedMetadata(scope, args = {}) {
439
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
420
440
  const order = args.order ?? "key";
421
441
  const transaction = (await this.#getDatabase()).transaction(INDEXED_DB_ENTRY_STORE, "readonly");
422
442
  const store = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
@@ -448,6 +468,12 @@ var IndexedDbAsyncStorageDriver = class {
448
468
  const filter = args.filter;
449
469
  const filteredEntries = filter === void 0 ? entries : entries.filter((entry) => entry.customMetadata[filter.key] === filter.equals);
450
470
  if (usedIndex !== "lru") filteredEntries.sort((left, right) => compareMetadata(left, right, order));
471
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-record-metadata", startTime, {
472
+ count: filteredEntries.length,
473
+ objectStores: [INDEXED_DB_ENTRY_STORE],
474
+ order,
475
+ usedIndex
476
+ });
451
477
  this.#instrumentation?.record({
452
478
  order,
453
479
  resultKeys: filteredEntries.map((entry) => entry.key),
@@ -462,6 +488,7 @@ var IndexedDbAsyncStorageDriver = class {
462
488
  return (await this.listManagedMetadata(scope, { order: "key" })).map((entry) => entry.key);
463
489
  }
464
490
  async clearManagedNamespace(scope) {
491
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
465
492
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
466
493
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
467
494
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -470,6 +497,7 @@ var IndexedDbAsyncStorageDriver = class {
470
497
  });
471
498
  policyStore.delete(createScopePolicyKey(scope));
472
499
  await transactionDone(transaction);
500
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "clear-records", startTime, { objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE] });
473
501
  this.#instrumentation?.onClearManagedNamespace?.(scope);
474
502
  this.#instrumentation?.record({
475
503
  scope,
@@ -478,6 +506,7 @@ var IndexedDbAsyncStorageDriver = class {
478
506
  });
479
507
  }
480
508
  async applyManagedCommit(scope, args, helpers) {
509
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
481
510
  const transaction = (await this.#getDatabase()).transaction([INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE], "readwrite");
482
511
  const entryStore = transaction.objectStore(INDEXED_DB_ENTRY_STORE);
483
512
  const policyStore = transaction.objectStore(INDEXED_DB_NAMESPACE_POLICY_STORE);
@@ -544,6 +573,12 @@ var IndexedDbAsyncStorageDriver = class {
544
573
  s: scope.sessionKey
545
574
  }, createScopePolicyKey(scope)));
546
575
  await transactionDone(transaction);
576
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-records", startTime, {
577
+ objectStores: [INDEXED_DB_ENTRY_STORE, INDEXED_DB_NAMESPACE_POLICY_STORE],
578
+ removes: removes.length,
579
+ touches: touches.length,
580
+ upserts: upserts.length
581
+ });
547
582
  this.#instrumentation?.onApplyManagedCommit?.(scope, args);
548
583
  this.#instrumentation?.record({
549
584
  removes,
@@ -883,6 +918,32 @@ var IndexedDbAsyncStorageDriver = class {
883
918
  });
884
919
  return this.#databasePromise;
885
920
  }
921
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
922
+ if (!import.meta.env.DEV) return;
923
+ if (startTime === null) return;
924
+ if (!this.debugLogger) return;
925
+ const status = typeof details.status === "string" ? details.status : "success";
926
+ emitTSDFDebugLog(this.debugLogger, {
927
+ area: "persistent-storage",
928
+ level: "log",
929
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
930
+ operation: "adapter-operation",
931
+ details: {
932
+ adapter: "async",
933
+ adapterName: "indexeddb",
934
+ adapterOperation,
935
+ databaseName: this.databaseName,
936
+ durationMs: getTSDFDebugTimingMs() - startTime,
937
+ status,
938
+ ...scope !== void 0 ? {
939
+ namespaceKind: scope.kind,
940
+ sessionKey: scope.sessionKey,
941
+ storeName: scope.storeName
942
+ } : {},
943
+ ...details
944
+ }
945
+ });
946
+ }
886
947
  };
887
948
  function createIndexedDbPersistentStorage$1(options = {}) {
888
949
  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, _ 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-2zQlbxtw.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 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-CNuCgLRs.js";
2
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
3
3
  import { Emitter } from "evtmitter";
4
4
  import { Context } from "react";
@@ -38,7 +38,8 @@ type DynamicRealtimeThrottleMs = (params: {
38
38
  }) => number;
39
39
  type StoreManagerStoreDefaults = {
40
40
  /** Default minimum interval between low-priority fetches for attached stores. */readonly lowPriorityThrottleMs: number; /** Default coalescing window used by attached stores when they do not override it. */
41
- readonly baseCoalescingWindowMs: number; /** Default adaptive throttle for real-time updates in attached stores. */
41
+ readonly baseCoalescingWindowMs: number; /** Extra browser-tab coalescing delay applied only while a tab is in the background. */
42
+ readonly backgroundCoalescingDelayMs: number; /** Default adaptive throttle for real-time updates in attached stores. */
42
43
  readonly dynamicRealtimeThrottleMs: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. */
43
44
  readonly blockWindowClose: BlockWindowCloseHandler | null; /** Default focus revalidation policy for attached stores. */
44
45
  readonly revalidateOnWindowFocus: boolean | (() => boolean) | undefined;
@@ -72,7 +73,7 @@ type StoreManagerOfflineApi<TUploadRef extends ValidPayload = ValidPayload> = {
72
73
  };
73
74
  /** Shared coordinator passed to every TSDF store instance in an app/session. */
74
75
  type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
75
- /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync and persistent storage internals. */
76
+ /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync, focus lifecycle, and persistent storage internals. */
76
77
  debugLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
77
78
  errorNormalizer: (exception: Error) => StoreError; /** Global fallback for persistent storage failures in attached stores. */
78
79
  onPersistentStorageError: PersistentStorageErrorHandler | undefined; /** Global fallback for mutation failures in attached stores. */
@@ -90,16 +91,17 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
90
91
  * behavior while no account is loaded.
91
92
  */
92
93
  getSessionKey: () => string | false; /** Normalizes raw exceptions into the shared StoreError shape. */
93
- errorNormalizer: (exception: Error) => StoreError; /** Default minimum interval between low-priority fetches for attached stores. Defaults to 5ms. */
94
- lowPriorityThrottleMs?: number; /** Default coalescing window for attached stores. Defaults to 10ms. */
95
- baseCoalescingWindowMs?: number; /** Default adaptive throttle for real-time updates in attached stores. Store-level values override it. */
94
+ errorNormalizer: (exception: Error) => StoreError; /** Default minimum interval between low-priority fetches for attached stores. Defaults to 40 minutes. */
95
+ lowPriorityThrottleMs?: number; /** Default coalescing window for attached stores. Defaults to 16ms. */
96
+ baseCoalescingWindowMs?: number; /** Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to 3000ms. */
97
+ backgroundCoalescingDelayMs?: number; /** Default adaptive throttle for real-time updates in attached stores. Store-level values override it. */
96
98
  dynamicRealtimeThrottleMs?: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. Pass `null` to disable. */
97
99
  blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
98
100
  onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
99
101
  onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
100
102
  revalidateOnWindowFocus?: boolean | (() => boolean);
101
103
  /**
102
- * Enables debug logs for browser-tab sync and persistent storage operations.
104
+ * Enables debug logs for browser-tab sync, focus revalidation, and persistent storage operations.
103
105
  * Pass `true` to use console logging, or pass a logger function.
104
106
  */
105
107
  debug?: TSDFDebugOptions; /** Optional shared offline session config for every attached store. */
@@ -1511,4 +1513,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
1511
1513
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
1512
1514
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
1513
1515
  //#endregion
1514
- 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 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 };
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 };
package/dist/main.js CHANGED
@@ -1,5 +1,6 @@
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 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-BaojFC2B.js";
2
+ import { n as getTSDFDebugTimingMs, r as resolveTSDFDebugLogger, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
3
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-5jUV7H9_.js";
3
4
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
5
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
6
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
@@ -964,39 +965,6 @@ function parsePersistedListQueryData(value, payloadSchema) {
964
965
  };
965
966
  }
966
967
  //#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
968
  //#region src/persistentStorage/offlineUploadRegistry.ts
1001
969
  const uploadAdaptersBySession = /* @__PURE__ */ new Map();
1002
970
  function registerOfflineUploadAdapterForSession(sessionKey, adapter) {
@@ -1242,14 +1210,12 @@ function createPersistentStorageDebugContext(adapter, storeName, debugLogger, en
1242
1210
  };
1243
1211
  }
1244
1212
  function startPersistentStorageDebugTiming(context) {
1245
- if (!import.meta.env.DEV) return null;
1246
- if (!context?.debugLogger) return null;
1247
- return context.adapterKind === "async" ? getTSDFDebugTimingMs() : null;
1213
+ return null;
1248
1214
  }
1249
1215
  function logPersistentStorageOperation(context, operation, status, startTime, details, error) {
1250
1216
  if (!import.meta.env.DEV) return;
1251
1217
  if (!context?.debugLogger) return;
1252
- const durationMs = startTime === null ? void 0 : getTSDFDebugTimingMs() - startTime;
1218
+ const durationMs = startTime === null ? void 0 : Date.now() - startTime;
1253
1219
  const logDetails = {
1254
1220
  adapter: context.adapterKind,
1255
1221
  storeName: context.storeName,
@@ -1421,6 +1387,7 @@ function createPersistentStorageHandle(config, { asyncValueCodec, getManifestMet
1421
1387
  if (asyncAdapter === null) return null;
1422
1388
  const sessionKey = config.getSessionKey();
1423
1389
  if (sessionKey === false) return null;
1390
+ if (import.meta.env.DEV) asyncAdapter.debugLogger = config.debugLogger;
1424
1391
  return asyncAdapter.openNamespace({
1425
1392
  sessionKey,
1426
1393
  storeName: asyncNamespace?.storeName ?? config.storeName,
@@ -1625,6 +1592,7 @@ 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
+ if (import.meta.env.DEV) asyncAdapter.debugLogger = config.debugLogger;
1628
1596
  return asyncAdapter.openNamespace({
1629
1597
  sessionKey,
1630
1598
  storeName: config.storeName,
@@ -2205,7 +2173,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2205
2173
  }
2206
2174
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2207
2175
  async function clearAllSessionStorage(sessionKey) {
2208
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-W8bChTBu.js");
2176
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-CjRwtUxc.js");
2209
2177
  await Promise.all([
2210
2178
  clearSessionStorage(sessionKey, "local-sync"),
2211
2179
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -3017,6 +2985,7 @@ function captureOfflineOverlayEntries(overlayStore, itemKeys, createOverlay) {
3017
2985
  //#endregion
3018
2986
  //#region src/utils/browserTabsPriority.ts
3019
2987
  const DEFAULT_FETCH_LEASE_MS = 1e4;
2988
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1 = 3e3;
3020
2989
  const COALESCING_WINDOW_STEP_MS = 1e3;
3021
2990
  /** @internal */
3022
2991
  function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWindowIsFocused, onWindowFocusChange, publishStatus, timings, onLeaderChange) {
@@ -3112,7 +3081,7 @@ function createBrowserTabsPriority(transportEnabled, getIsEnabled, tabId, getWin
3112
3081
  if (baseCoalescingWindowMs <= 0) return baseCoalescingWindowMs;
3113
3082
  const coalescingRank = getCoalescingRank();
3114
3083
  if (coalescingRank <= 0) return baseCoalescingWindowMs;
3115
- return baseCoalescingWindowMs + coalescingRank * COALESCING_WINDOW_STEP_MS;
3084
+ return baseCoalescingWindowMs + Math.max(0, timings?.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS$1) + (coalescingRank - 1) * COALESCING_WINDOW_STEP_MS;
3116
3085
  }
3117
3086
  function onTabStatusMessage(remoteTabId, message) {
3118
3087
  if (!getIsEnabled()) return;
@@ -7504,8 +7473,9 @@ var RequestScheduler = class {
7504
7473
  };
7505
7474
  //#endregion
7506
7475
  //#region src/storeManager.ts
7507
- const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 5;
7508
- const DEFAULT_BASE_COALESCING_WINDOW_MS = 10;
7476
+ const DEFAULT_LOW_PRIORITY_THROTTLE_MS = 2400 * 1e3;
7477
+ const DEFAULT_BASE_COALESCING_WINDOW_MS = 16;
7478
+ const DEFAULT_BACKGROUND_COALESCING_DELAY_MS = 3e3;
7509
7479
  function defaultDynamicRealtimeThrottleMs({ windowIsNotFocused }) {
7510
7480
  return windowIsNotFocused ? 1e3 : 100;
7511
7481
  }
@@ -7600,6 +7570,7 @@ function createStoreManager(options) {
7600
7570
  storeDefaults: Object.freeze({
7601
7571
  lowPriorityThrottleMs: options.lowPriorityThrottleMs ?? DEFAULT_LOW_PRIORITY_THROTTLE_MS,
7602
7572
  baseCoalescingWindowMs: options.baseCoalescingWindowMs ?? DEFAULT_BASE_COALESCING_WINDOW_MS,
7573
+ backgroundCoalescingDelayMs: options.backgroundCoalescingDelayMs ?? DEFAULT_BACKGROUND_COALESCING_DELAY_MS,
7603
7574
  dynamicRealtimeThrottleMs: options.dynamicRealtimeThrottleMs ?? defaultDynamicRealtimeThrottleMs,
7604
7575
  blockWindowClose: options.blockWindowClose ?? null,
7605
7576
  revalidateOnWindowFocus: options.revalidateOnWindowFocus
@@ -7654,7 +7625,10 @@ function getOrCreateStoreManagerBrowserTabsPresence(storeManager, options) {
7654
7625
  onWindowFocusChange: options.onWindowFocusChange,
7655
7626
  transportFactory: options.transportFactory,
7656
7627
  ...import.meta.env.DEV ? { debugLogger: storeManager.debugLogger } : void 0,
7657
- priorityTimings: options.priorityTimings
7628
+ priorityTimings: {
7629
+ backgroundCoalescingDelayMs: storeManager.storeDefaults.backgroundCoalescingDelayMs,
7630
+ ...options.priorityTimings
7631
+ }
7658
7632
  });
7659
7633
  return {
7660
7634
  priority: presence.priority,
@@ -7707,7 +7681,7 @@ async function performMutationWithLifecycle(startMutation, mutation, onError, op
7707
7681
  //#endregion
7708
7682
  //#region src/utils/storeFocusLifecycle.ts
7709
7683
  /** @internal */
7710
- function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate) {
7684
+ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates, transportReconnectCooldownMs, getWindowIsFocused, onWindowFocus, onWindowFocusRevalidate, onTransportReconnectRevalidate, debug) {
7711
7685
  let cleanupFocusListener = null;
7712
7686
  let cleanupReconnectFocusListener = null;
7713
7687
  let reconnectCooldownTimeoutId = null;
@@ -7727,6 +7701,19 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7727
7701
  if (typeof revalidateOnWindowFocus === "function") return revalidateOnWindowFocus();
7728
7702
  return !!revalidateOnWindowFocus;
7729
7703
  }
7704
+ const logWindowFocusRevalidate = import.meta.env.DEV && debug?.debugLogger ? (message, details) => {
7705
+ emitTSDFDebugLog(debug.debugLogger, {
7706
+ area: "focus",
7707
+ level: "log",
7708
+ message,
7709
+ operation: "window-focus-revalidate",
7710
+ details: {
7711
+ storeId: debug.storeId,
7712
+ storeType: debug.storeType,
7713
+ ...details
7714
+ }
7715
+ });
7716
+ } : void 0;
7730
7717
  function runTransportReconnectRevalidate() {
7731
7718
  lastTransportReconnectRevalidateAt = Date.now();
7732
7719
  onTransportReconnectRevalidate();
@@ -7765,9 +7752,28 @@ function createStoreFocusLifecycle(revalidateOnWindowFocus, usesRealTimeUpdates,
7765
7752
  clearReconnectCooldownTimeout();
7766
7753
  hasPendingReconnectRevalidateOnFocus = false;
7767
7754
  lastTransportReconnectRevalidateAt = Number.NEGATIVE_INFINITY;
7768
- if (!revalidateOnWindowFocus || usesRealTimeUpdates) return;
7755
+ if (!revalidateOnWindowFocus) return;
7756
+ if (usesRealTimeUpdates) {
7757
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7758
+ reason: "real-time-updates",
7759
+ status: "skipped"
7760
+ });
7761
+ return;
7762
+ }
7769
7763
  cleanupFocusListener = onWindowFocus(() => {
7770
- if (isFocusRevalidationEnabled()) onWindowFocusRevalidate();
7764
+ if (!isFocusRevalidationEnabled()) {
7765
+ logWindowFocusRevalidate?.("window focus revalidation skipped", {
7766
+ policy: "dynamic",
7767
+ reason: "dynamic-disabled",
7768
+ status: "skipped"
7769
+ });
7770
+ return;
7771
+ }
7772
+ logWindowFocusRevalidate?.("window focus revalidation triggered", {
7773
+ policy: typeof revalidateOnWindowFocus === "function" ? "dynamic" : "enabled",
7774
+ status: "triggered"
7775
+ });
7776
+ onWindowFocusRevalidate();
7771
7777
  });
7772
7778
  }
7773
7779
  function dispose() {
@@ -9176,7 +9182,11 @@ function createCollectionStore(storeOptions) {
9176
9182
  invalidateItem(() => true, "lowPriority");
9177
9183
  }, () => {
9178
9184
  invalidateItem(() => true, "realtimeUpdate");
9179
- });
9185
+ }, import.meta.env.DEV ? {
9186
+ debugLogger: storeManager.debugLogger,
9187
+ storeId: id,
9188
+ storeType: "collection"
9189
+ } : void 0);
9180
9190
  const { enforceCacheLimits } = createCollectionCacheLimits(store, maxItems, itemCacheRuntime, isProtectedFromEviction, cleanupItemResources, onStateCleanup);
9181
9191
  const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
9182
9192
  function scheduleCacheLimitEnforcement() {
@@ -9802,7 +9812,11 @@ function createDocumentStore(storeOptions) {
9802
9812
  invalidateData("lowPriority");
9803
9813
  }, () => {
9804
9814
  invalidateData("realtimeUpdate");
9805
- });
9815
+ }, import.meta.env.DEV ? {
9816
+ debugLogger: storeManager.debugLogger,
9817
+ storeId: id,
9818
+ storeType: "document"
9819
+ } : void 0);
9806
9820
  persistence?.attach(store);
9807
9821
  initializeOfflineStoreController(offlineController);
9808
9822
  function scheduleFetch(fetchType, options) {
@@ -15269,7 +15283,11 @@ function createListQueryStore(storeOptions) {
15269
15283
  all: true,
15270
15284
  type: "realtimeUpdate"
15271
15285
  });
15272
- });
15286
+ }, import.meta.env.DEV ? {
15287
+ debugLogger: storeManager.debugLogger,
15288
+ storeId: id,
15289
+ storeType: "listQuery"
15290
+ } : void 0);
15273
15291
  const { enforceCacheLimits } = createListQueryCacheLimits(store, maxItems, maxQueries, itemCacheRuntime, queryCacheRuntime, isQueryProtectedFromEviction, isStandaloneItemProtectedFromEviction, cleanupItemStateMetadata, cleanupQueryStateMetadata, deleteQueryFetchResources, deleteItemFetchResources, onStateCleanup);
15274
15292
  const cacheLimitEnforcementScheduler = createIdleThrottledScheduler(CACHE_LIMIT_ENFORCEMENT_THROTTLE_MS, enforceCacheLimits);
15275
15293
  function scheduleCacheLimitEnforcement() {
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CBnUebnf.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-D3zaTTNQ.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-5jUV7H9_.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,5 @@
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 parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, I as getNamespaceId, L as getPayloadRecordKey, V as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter } from "./asyncStorageAdapter-BaojFC2B.js";
2
+ import { n as getTSDFDebugTimingMs, t as emitTSDFDebugLog } from "./debug--Qic3VU9.js";
2
3
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
3
4
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
5
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -134,6 +135,7 @@ async function getFileHandleIfExists(parent, name) {
134
135
  const OPFS_DIR_HANDLE_CACHE_MAX_SIZE = 500;
135
136
  const OPFS_FILE_HANDLE_CACHE_MAX_SIZE = 1e4;
136
137
  var OpfsAsyncStorageDriver = class {
138
+ debugLogger;
137
139
  #rootDirPromise = null;
138
140
  #mainCacheContext = {
139
141
  cleanupKnowledge: null,
@@ -247,7 +249,15 @@ var OpfsAsyncStorageDriver = class {
247
249
  storeDir
248
250
  });
249
251
  if (fileHandle === null) return null;
250
- return this.#readJsonFile(this.#getFilePath(scope, key), fileHandle, cacheContext);
252
+ const filePath = this.#getFilePath(scope, key);
253
+ if (!import.meta.env.DEV || !this.debugLogger) return this.#readJsonFile(filePath, fileHandle, cacheContext);
254
+ const startTime = getTSDFDebugTimingMs();
255
+ return this.#readJsonFile(filePath, fileHandle, cacheContext).finally(() => {
256
+ this.#logAdapterOperation(scope, "read-file", startTime, {
257
+ filePath,
258
+ key
259
+ });
260
+ });
251
261
  }));
252
262
  }
253
263
  async #setManyWithContext(scope, entries, cacheContext) {
@@ -265,10 +275,20 @@ var OpfsAsyncStorageDriver = class {
265
275
  if (await this.#removeWholeStoreDirIfAllKnownEntriesAreBeingRemoved(scope, uniqueKeys, cacheContext)) return;
266
276
  const removeResults = await Promise.all(uniqueKeys.map(async (key) => {
267
277
  const fileName = buildFileName(scope, key);
278
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
268
279
  try {
269
280
  await storeDir.removeEntry(fileName);
281
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
282
+ fileName,
283
+ key
284
+ });
270
285
  return true;
271
286
  } catch {
287
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
288
+ fileName,
289
+ key,
290
+ status: "miss"
291
+ });
272
292
  return false;
273
293
  } finally {
274
294
  this.#invalidateFileHandle(scope, key, cacheContext);
@@ -279,8 +299,14 @@ var OpfsAsyncStorageDriver = class {
279
299
  await this.#pruneEmptyDirectories(scope, cacheContext);
280
300
  }
281
301
  async #listKeysWithContext(scope, cacheContext) {
302
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
282
303
  const { resolvedEntries } = await this.#listScopedFiles(scope, cacheContext);
283
- return resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
304
+ const keys = resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
305
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-directory", startTime, {
306
+ count: keys.length,
307
+ storeDirPath: this.#getStoreDirPath(scope)
308
+ });
309
+ return keys;
284
310
  }
285
311
  async #clearWithContext(scope, cacheContext) {
286
312
  const storeDir = await this.#getStoreDir(scope, {
@@ -633,11 +659,17 @@ var OpfsAsyncStorageDriver = class {
633
659
  if (fileHandle === null) throw new Error("[TSDF] Failed to open OPFS file handle.");
634
660
  const writable = await fileHandle.createWritable();
635
661
  const rawValue = entry.serializedValue ?? JSON.stringify(entry.value);
662
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
636
663
  try {
637
664
  await writable.write(rawValue);
638
665
  } finally {
639
666
  await writable.close();
640
667
  }
668
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-file", startTime, {
669
+ filePath: this.#getFilePath(scope, entry.key),
670
+ key: entry.key,
671
+ sizeBytes: rawValue.length
672
+ });
641
673
  cacheContext.readValueCache?.set(this.#getFilePath(scope, entry.key), entry.value);
642
674
  return;
643
675
  } catch (error) {
@@ -648,6 +680,29 @@ var OpfsAsyncStorageDriver = class {
648
680
  this.#invalidateDirectory(this.#getSessionDirPath(scope.sessionKey), cacheContext);
649
681
  }
650
682
  }
683
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
684
+ if (!import.meta.env.DEV) return;
685
+ if (startTime === null) return;
686
+ if (!this.debugLogger) return;
687
+ const status = typeof details.status === "string" ? details.status : "success";
688
+ emitTSDFDebugLog(this.debugLogger, {
689
+ area: "persistent-storage",
690
+ level: "log",
691
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
692
+ operation: "adapter-operation",
693
+ details: {
694
+ adapter: "async",
695
+ adapterName: "opfs",
696
+ adapterOperation,
697
+ durationMs: getTSDFDebugTimingMs() - startTime,
698
+ namespaceKind: scope.kind,
699
+ sessionKey: scope.sessionKey,
700
+ status,
701
+ storeName: scope.storeName,
702
+ ...details
703
+ }
704
+ });
705
+ }
651
706
  async #cleanupRemoveKnownRecordsWithContext(scope, keys, cacheContext) {
652
707
  if (keys.length === 0) return [];
653
708
  const storeDir = await this.#getStoreDir(scope, {
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-2zQlbxtw.js";
1
+ import { t as AsyncStorageAdapter } from "./types-CNuCgLRs.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -7,9 +7,11 @@ import { StandardSchemaV1 } from "@standard-schema/spec";
7
7
  /** Debug log severity used to choose the default console method. */
8
8
  type TSDFDebugLogLevel = 'log' | 'warn' | 'error';
9
9
  /** Internal subsystem that emitted a debug log entry. */
10
- type TSDFDebugLogArea = 'browser-tabs' | 'persistent-storage';
10
+ type TSDFDebugLogArea = 'browser-tabs' | 'focus' | 'persistent-storage';
11
+ /** Operations emitted by focus lifecycle handling. */
12
+ type TSDFFocusDebugOperation = 'window-focus-revalidate';
11
13
  /** Operations emitted by the persistent storage subsystem. */
12
- 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' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
13
15
  /** Operations emitted by the browser-tab sync subsystem. */
14
16
  type TSDFBrowserTabsDebugOperation = 'leader-change' | 'publish' | 'publish-skipped' | 'receive' | 'receive-skipped' | 'session-change' | 'transport-close' | 'transport-open' | 'transport-unavailable';
15
17
  /** Structured debug log entry emitted by TSDF internals. */
@@ -17,7 +19,7 @@ type TSDFDebugLogEntry = {
17
19
  /** Subsystem that emitted the entry. */area: TSDFDebugLogArea; /** Severity of the entry. */
18
20
  level: TSDFDebugLogLevel; /** Human-readable summary of the operation. */
19
21
  message: string; /** Stable operation id, such as `publish`, `load`, or `write`. */
20
- operation: TSDFPersistentStorageDebugOperation | TSDFBrowserTabsDebugOperation; /** Structured operation metadata for filtering and diagnostics. */
22
+ operation: TSDFFocusDebugOperation | TSDFPersistentStorageDebugOperation | TSDFBrowserTabsDebugOperation; /** Structured operation metadata for filtering and diagnostics. */
21
23
  details?: Readonly<Record<string, unknown>>;
22
24
  };
23
25
  /** Custom debug logger invoked for each emitted TSDF debug entry. */
@@ -1312,7 +1314,8 @@ type AsyncStorageDiscoveredScope = {
1312
1314
  };
1313
1315
  /** Low-level async backend contract implemented by custom storage drivers. */
1314
1316
  type AsyncStorageDriver = {
1315
- /** 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; /** Read a single raw record from a logical namespace. */
1318
+ get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1316
1319
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
1317
1320
  remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
1318
1321
  listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
@@ -1343,7 +1346,8 @@ type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string,
1343
1346
  };
1344
1347
  /** Managed async adapter consumed by TSDF persistence internals. */
1345
1348
  type AsyncStorageAdapter = {
1346
- /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
1349
+ /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Mutable debug logger used by concrete adapters to emit operation timings. */
1350
+ debugLogger?: TSDFDebugLogger; /** Open a logical namespace with managed batching and touch guarantees. */
1347
1351
  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. */
1348
1352
  readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
1349
1353
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
@@ -1472,4 +1476,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
1472
1476
  /** Persistent storage config for ListQueryStore. */
1473
1477
  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>;
1474
1478
  //#endregion
1475
- 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, 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 };
1479
+ 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 };
package/docs/README.md CHANGED
@@ -50,8 +50,8 @@ const storeManager = createStoreManager({
50
50
  id: 'fetch-error',
51
51
  message: err.message,
52
52
  }),
53
- lowPriorityThrottleMs: 5,
54
- baseCoalescingWindowMs: 10,
53
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
54
+ baseCoalescingWindowMs: 16,
55
55
  blockWindowClose: null,
56
56
  revalidateOnWindowFocus: true,
57
57
  onMutationError: (error) => {
@@ -24,7 +24,7 @@ Tabs use a versioned message model so later snapshots do not overwrite fresher r
24
24
 
25
25
  - Tab status messages include focus and presence timestamp data.
26
26
  - Focused tabs keep the base `baseCoalescingWindowMs`.
27
- - Background tabs are ranked and may receive an extended coalescing window (`base` + rank \* `1000ms`), which helps avoid duplicate background refetch work.
27
+ - Background tabs are ranked and may receive an extended coalescing window (`base` + `backgroundCoalescingDelayMs` + background rank \* `1000ms`), which helps avoid duplicate background refetch work. The first background tab uses rank `0`, so the default first background window is `base + 3000ms`.
28
28
  - `fetch-start` messages let sibling tabs drop duplicate scheduled work when another tab is already fetching the same request IDs.
29
29
  - Confirmed snapshots from one tab are only applied to others when remote ordering says they are newer than the current version.
30
30
 
@@ -47,6 +47,7 @@ const storeManager = createStoreManager({
47
47
  return isLoggedIn ? `tenant:${tenantId}` : false;
48
48
  },
49
49
  errorNormalizer: normalizeError,
50
+ backgroundCoalescingDelayMs: 3_000,
50
51
  });
51
52
 
52
53
  const store = createDocumentStore({
@@ -14,8 +14,8 @@ const storeManager = createStoreManager({
14
14
  getSessionKey: () =>
15
15
  authState.userId ? `tenant:${authState.tenantId}` : false,
16
16
  errorNormalizer: normalizeError,
17
- lowPriorityThrottleMs: 5,
18
- baseCoalescingWindowMs: 10,
17
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
18
+ baseCoalescingWindowMs: 16,
19
19
  blockWindowClose: null,
20
20
  });
21
21
 
@@ -14,8 +14,8 @@ const storeManager = createStoreManager({
14
14
  getSessionKey: () =>
15
15
  authState.userId ? `tenant:${authState.tenantId}` : false,
16
16
  errorNormalizer: normalizeError,
17
- lowPriorityThrottleMs: 5,
18
- baseCoalescingWindowMs: 10,
17
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
18
+ baseCoalescingWindowMs: 16,
19
19
  blockWindowClose: null,
20
20
  });
21
21
 
@@ -116,8 +116,8 @@ const storeManager = createStoreManager({
116
116
  getSessionKey: () =>
117
117
  authState.userId ? `tenant:${authState.tenantId}` : false,
118
118
  errorNormalizer: normalizeError,
119
- lowPriorityThrottleMs: 5,
120
- baseCoalescingWindowMs: 10,
119
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
120
+ baseCoalescingWindowMs: 16,
121
121
  blockWindowClose: null,
122
122
  });
123
123
 
@@ -18,7 +18,7 @@ Every fetch request has a priority that determines its behavior:
18
18
  Low-priority fetches are throttled to avoid redundant requests:
19
19
 
20
20
  ```
21
- lowPriorityThrottleMs: 5
21
+ lowPriorityThrottleMs: 40 * 60 * 1_000
22
22
  ```
23
23
 
24
24
  If a hook mounts within the configured throttle window after the last fetch completed, the low-priority fetch is **skipped** because the data is still fresh enough.
@@ -28,14 +28,14 @@ If a hook mounts within the configured throttle window after the last fetch comp
28
28
  When multiple fetch requests arrive in a short window, they are coalesced into a single batch:
29
29
 
30
30
  ```
31
- baseCoalescingWindowMs: 10
31
+ baseCoalescingWindowMs: 16
32
32
  ```
33
33
 
34
34
  If three `useItem` hooks mount within the configured coalescing window, their fetches are grouped and executed as one request (when using batch fetching) or sequentially but without duplicate requests for the same item.
35
35
 
36
36
  ### Background Tabs
37
37
 
38
- When synced browser tabs are open, TSDF can extend coalescing internally for background tabs based on focus ranking. Focused tabs keep `baseCoalescingWindowMs`; background tabs may wait longer so duplicate background work can be dropped when another tab is already fetching the same data.
38
+ When synced browser tabs are open, TSDF can extend coalescing internally for background tabs based on focus ranking. Focused tabs keep `baseCoalescingWindowMs`; background tabs use `baseCoalescingWindowMs + backgroundCoalescingDelayMs + backgroundRank * 1000ms`, where the first background tab has rank `0`. This gives sibling tabs time to drop duplicate background work when another tab is already fetching the same data.
39
39
 
40
40
  See [Browser Tabs Sync](./browser-tabs-sync.md) for focus ranking and request deduplication behavior across tabs.
41
41
 
@@ -71,8 +71,9 @@ This is useful for background refetches that should yield to user-initiated acti
71
71
 
72
72
  | Option | Required | Description |
73
73
  | ----------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
74
- | `lowPriorityThrottleMs` | No | Manager default minimum interval between low-priority fetches, or a store-level override. Defaults to `5` |
75
- | `baseCoalescingWindowMs` | No | Manager default time window to group multiple requests into a single batch, or a store-level override. Defaults to `10` |
74
+ | `lowPriorityThrottleMs` | No | Manager default minimum interval between low-priority fetches, or a store-level override. Defaults to 40 minutes (`2_400_000ms`) |
75
+ | `baseCoalescingWindowMs` | No | Manager default time window to group multiple requests into a single batch, or a store-level override. Defaults to `16ms` |
76
+ | `backgroundCoalescingDelayMs` | No | Manager-level delay added only for background browser tabs before the per-rank `1000ms` step. Defaults to `3000ms` |
76
77
  | `mediumPriorityDelayMs` | No | Delay before medium-priority fetches execute |
77
78
  | `dynamicRealtimeThrottleMs` | No | Manager default or store override returning throttle duration for real-time updates. Built-in default: `100ms` focused, `1000ms` background. See [Real-Time Updates](./real-time-updates.md) |
78
79
  | `maxBatchSize` / `maxItemBatchSize` | No | Collection/ListQuery batch cap. List Query `maxItemBatchSize` defaults to `50`. Triggers immediate fetch when reached |
@@ -81,11 +82,14 @@ This is useful for background refetches that should yield to user-initiated acti
81
82
 
82
83
  ```ts
83
84
  {
84
- // Skip refetch if one happened in the last 5ms
85
- lowPriorityThrottleMs: 5,
85
+ // Skip refetch if one happened in the last 40 minutes
86
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
86
87
 
87
- // Group fetches within 10ms
88
- baseCoalescingWindowMs: 10,
88
+ // Group fetches within 16ms
89
+ baseCoalescingWindowMs: 16,
90
+
91
+ // Add 3s before background browser-tab rank staggering
92
+ backgroundCoalescingDelayMs: 3_000,
89
93
 
90
94
  // Wait 300ms before executing medium-priority fetches
91
95
  mediumPriorityDelayMs: 300,
@@ -20,8 +20,8 @@ const storeManager = createStoreManager({
20
20
  getSessionKey: () =>
21
21
  authState.userId ? `tenant:${authState.tenantId}` : false,
22
22
  errorNormalizer: normalizeError,
23
- lowPriorityThrottleMs: 5,
24
- baseCoalescingWindowMs: 10,
23
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
24
+ baseCoalescingWindowMs: 16,
25
25
  blockWindowClose: null,
26
26
  });
27
27
 
package/docs/offline.md CHANGED
@@ -34,8 +34,8 @@ type UserOfflineOperations = DefineListQueryOfflineOperations<
34
34
  const storeManager = createStoreManager({
35
35
  getSessionKey: () => currentTenantId ?? false,
36
36
  errorNormalizer: normalizeError,
37
- lowPriorityThrottleMs: 5,
38
- baseCoalescingWindowMs: 10,
37
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
38
+ baseCoalescingWindowMs: 16,
39
39
  blockWindowClose: null,
40
40
  offlineSession: {
41
41
  network: { enabled: true },
@@ -137,8 +137,8 @@ They are **not** triggered by:
137
137
  const storeManager = createStoreManager({
138
138
  getSessionKey: () => currentTenantId ?? false,
139
139
  errorNormalizer: normalizeError,
140
- lowPriorityThrottleMs: 5,
141
- baseCoalescingWindowMs: 10,
140
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
141
+ baseCoalescingWindowMs: 16,
142
142
  blockWindowClose: null,
143
143
  });
144
144
 
@@ -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({ debug: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work.
68
68
 
69
69
  ## Converted Data Schemas
70
70
 
@@ -202,8 +202,8 @@ const getSessionKey = () => (userId ? `tenant:${userId}` : false);
202
202
  const storeManager = createStoreManager({
203
203
  getSessionKey,
204
204
  errorNormalizer: normalizeError,
205
- lowPriorityThrottleMs: 5,
206
- baseCoalescingWindowMs: 10,
205
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
206
+ baseCoalescingWindowMs: 16,
207
207
  blockWindowClose: null,
208
208
  onPersistentStorageError: (error) => {
209
209
  console.error('TSDF persistence failed', error);
@@ -16,8 +16,9 @@ const storeManager = createStoreManager({
16
16
  id: 'unknown-error',
17
17
  message: error.message,
18
18
  }),
19
- lowPriorityThrottleMs: 5,
20
- baseCoalescingWindowMs: 10,
19
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
20
+ baseCoalescingWindowMs: 16,
21
+ backgroundCoalescingDelayMs: 3_000,
21
22
  dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) =>
22
23
  windowIsNotFocused ? lastFetchDuration * 10 : lastFetchDuration * 2,
23
24
  blockWindowClose: null,
@@ -34,29 +35,30 @@ const storeManager = createStoreManager({
34
35
 
35
36
  Options:
36
37
 
37
- | Option | Required | Description |
38
- | --------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
39
- | `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
40
- | `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
41
- | `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to `5`. |
42
- | `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `10`. |
43
- | `dynamicRealtimeThrottleMs` | No | Default adaptive throttle for real-time updates in attached stores. Defaults to `100ms` focused and `1000ms` in the background. Store options override it. |
44
- | `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
45
- | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
46
- | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
47
- | `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
48
- | `debug` | No | Enables browser-tab sync and persistent-storage debug logs. Pass `true` or a logger function. |
49
- | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
38
+ | Option | Required | Description |
39
+ | ----------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
40
+ | `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
41
+ | `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
42
+ | `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to 40 minutes (`2_400_000ms`). |
43
+ | `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `16ms`. |
44
+ | `backgroundCoalescingDelayMs` | No | Extra browser-tab coalescing delay applied only while a tab is in the background. Defaults to `3000ms`. |
45
+ | `dynamicRealtimeThrottleMs` | No | Default adaptive throttle for real-time updates in attached stores. Defaults to `100ms` focused and `1000ms` in the background. Store options override it. |
46
+ | `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
47
+ | `revalidateOnWindowFocus` | No | Default focus revalidation policy for attached stores. Store options override it. |
48
+ | `onMutationError` | No | Global fallback for mutation failures when a store does not provide its own handler. |
49
+ | `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
+ | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
50
52
 
51
53
  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.
52
54
 
53
- Stores inherit the manager's `lowPriorityThrottleMs`, `baseCoalescingWindowMs`, and `dynamicRealtimeThrottleMs` unless they provide their own store-level overrides. The built-in `dynamicRealtimeThrottleMs` default returns `100ms` while focused and `1000ms` while the window is in the background. `blockWindowClose` is manager-only so window-close mutation protection is consistent across attached stores.
55
+ Stores inherit the manager's `lowPriorityThrottleMs`, `baseCoalescingWindowMs`, and `dynamicRealtimeThrottleMs` unless they provide their own store-level overrides. `backgroundCoalescingDelayMs` and `blockWindowClose` are manager-only so browser-tab background coordination and window-close mutation protection stay consistent across attached stores. The built-in `dynamicRealtimeThrottleMs` default returns `100ms` while focused and `1000ms` while the window is in the background.
54
56
 
55
57
  Store-level options can explicitly disable inherited defaults when the option supports disabling: use `revalidateOnWindowFocus: false`, `onMutationError: null`, or `persistentStorage.onPersistentStorageError: null`.
56
58
 
57
59
  ## Debug Logging
58
60
 
59
- Pass `debug: true` to log browser-tab sync operations 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. 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.
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 adapters emit timed `adapter-operation` entries with `durationMs` so slow OPFS, IndexedDB, or custom driver paths can be inspected.
60
62
 
61
63
  ```ts
62
64
  const storeManager = createStoreManager({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "17.0.0-alpha.11",
3
+ "version": "17.0.0-alpha.13",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",