tsdf 17.0.0-alpha.12 → 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-CYxABChu.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-DqUm_Sv7.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-DqUm_Sv7.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, 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 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";
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),
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-C6KKLdos.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-DqUm_Sv7.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;
@@ -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' | '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. */
@@ -1314,7 +1314,8 @@ 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; /** 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. */
1318
1319
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
1319
1320
  remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
1320
1321
  listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
@@ -1345,7 +1346,8 @@ type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string,
1345
1346
  };
1346
1347
  /** Managed async adapter consumed by TSDF persistence internals. */
1347
1348
  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. */
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. */
1349
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. */
1350
1352
  readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
1351
1353
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
@@ -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
 
@@ -58,7 +58,7 @@ Store-level options can explicitly disable inherited defaults when the option su
58
58
 
59
59
  ## Debug Logging
60
60
 
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.
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.
62
62
 
63
63
  ```ts
64
64
  const storeManager = createStoreManager({
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.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",