tsdf 18.1.0 → 18.2.0

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-DgsuE-T8.js";
1
+ import { t as createAsyncStorageAdapter } from "./asyncStorageAdapter-Bbepjtkd.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1,2 +1,2 @@
1
- import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { i as createAsyncStorageAdapter } from "./asyncStorageAdapter-YuIJ7hwm.js";
2
2
  export { createAsyncStorageAdapter };
@@ -1,4 +1,4 @@
1
- import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-BlyGC_PO.js";
1
+ import { r as AsyncStorageDriver, t as AsyncStorageAdapter } from "./types-DDjEjIqQ.js";
2
2
 
3
3
  //#region src/persistentStorage/asyncStorageAdapter.d.ts
4
4
  declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
@@ -622,7 +622,6 @@ function getDefaultMaxBytesForScope(adapter, scopeKind) {
622
622
  //#region src/debug.ts
623
623
  function defaultConsoleDebugLogger(entry) {
624
624
  const consoleForLevel = globalThis.console[entry.level];
625
- if (typeof consoleForLevel !== "function") return;
626
625
  const details = entry.details ? {
627
626
  operation: entry.operation,
628
627
  ...entry.details
@@ -1108,6 +1107,13 @@ function unregisterAsyncStartupStoreCleanup(adapter, sessionKey, storeName) {
1108
1107
  registry.delete(getStoreRegistryKey(sessionKey, storeName));
1109
1108
  if (registry.size === 0) registeredAsyncStartupStoreCleanupCallbacks.delete(adapter);
1110
1109
  }
1110
+ /**
1111
+ * Managed adapters keyed by themselves. Helpers used by the `local-sync`
1112
+ * persistence paths look adapters up here instead of using `instanceof`, so
1113
+ * bundlers can drop the `ManagedAsyncStorageAdapter` class from apps that never
1114
+ * create an async adapter.
1115
+ */
1116
+ const managedAsyncStorageAdapters = /* @__PURE__ */ new WeakMap();
1111
1117
  var ManagedAsyncStorageAdapter = class {
1112
1118
  kind = "async";
1113
1119
  #driver;
@@ -1125,6 +1131,7 @@ var ManagedAsyncStorageAdapter = class {
1125
1131
  constructor(driver) {
1126
1132
  this.#driver = driver;
1127
1133
  registerAsyncStorageReadCacheParticipant(this);
1134
+ managedAsyncStorageAdapters.set(this, this);
1128
1135
  }
1129
1136
  get debugLogger() {
1130
1137
  return this.#debugLogger;
@@ -2224,7 +2231,8 @@ const PER_KEY_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE = 25;
2224
2231
  const INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE = 250;
2225
2232
  /** Number of keys idle-deadline maintenance removes per commit. */
2226
2233
  function getAsyncStorageMaintenanceRemoveBatchSize(adapter) {
2227
- return adapter instanceof ManagedAsyncStorageAdapter ? adapter.getMaintenanceRemoveBatchSize() : INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE;
2234
+ const managedAdapter = adapter && managedAsyncStorageAdapters.get(adapter);
2235
+ return managedAdapter ? managedAdapter.getMaintenanceRemoveBatchSize() : INDEX_REWRITE_COMMIT_MAINTENANCE_REMOVE_BATCH_SIZE;
2228
2236
  }
2229
2237
  /**
2230
2238
  * Removes entries only while they still have the metadata the caller read,
@@ -2233,7 +2241,8 @@ function getAsyncStorageMaintenanceRemoveBatchSize(adapter) {
2233
2241
  * other adapters only get a best-effort metadata re-read before removing.
2234
2242
  */
2235
2243
  async function removeAsyncStorageNamespaceEntriesIfUnchanged(adapter, scope, entries) {
2236
- if (adapter instanceof ManagedAsyncStorageAdapter) return adapter.commitToNamespaceNow(scope, { conditionalRemoves: entries });
2244
+ const managedAdapter = managedAsyncStorageAdapters.get(adapter);
2245
+ if (managedAdapter) return managedAdapter.commitToNamespaceNow(scope, { conditionalRemoves: entries });
2237
2246
  const namespace = adapter.openNamespace(scope);
2238
2247
  const currentEntries = new Map((await namespace.listMetadata()).map((entry) => [entry.key, entry]));
2239
2248
  const removes = [];
@@ -1,3 +1,3 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-JsSCNBTr.js";
2
- import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-BameJ4st.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-6OuHQ3d-.js";
2
+ import { n as indexedDbPersistentStorage } from "./indexedDbPersistentStorage-CFH2BFL-.js";
3
3
  export { indexedDbPersistentStorage, opfsPersistentStorage };
@@ -1,14 +1,12 @@
1
- import { t as AsyncStorageAdapter } from "./types-BlyGC_PO.js";
1
+ import { t as AsyncStorageAdapter } from "./types-DDjEjIqQ.js";
2
2
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
3
3
  /** Options for creating the IndexedDB persistent storage adapter. */
4
- type IndexedDbPersistentStorageOptions$1 = {
4
+ type IndexedDbPersistentStorageOptions = {
5
5
  /** IndexedDB database name used by the adapter. */databaseName?: string;
6
6
  };
7
7
  //#endregion
8
8
  //#region src/persistentStorage/indexedDbPersistentStorage.d.ts
9
9
  declare const indexedDbPersistentStorage: AsyncStorageAdapter;
10
- /** Options for creating the IndexedDB persistent storage adapter. */
11
- type IndexedDbPersistentStorageOptions = IndexedDbPersistentStorageOptions$1;
12
10
  declare function createIndexedDbPersistentStorage(options?: IndexedDbPersistentStorageOptions): AsyncStorageAdapter;
13
11
  //#endregion
14
12
  export { type IndexedDbPersistentStorageOptions, createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-BameJ4st.js";
1
+ import { n as indexedDbPersistentStorage, t as createIndexedDbPersistentStorage } from "./indexedDbPersistentStorage-CFH2BFL-.js";
2
2
  export { createIndexedDbPersistentStorage, indexedDbPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { $ as parseAsyncStorageRecordKey, A as serializeJsonForStorage, J as getNamespaceId, K as compareMetadata, Q as normalizeStaticPolicy, X as getPersistedNamespaceId, Y as getPayloadRecordKey, Z as matchesConditionalRemove, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, tt as serializeProtectedRef, y as emitTSDFDebugLog } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { $ as parseAsyncStorageRecordKey, A as serializeJsonForStorage, J as getNamespaceId, K as compareMetadata, Q as normalizeStaticPolicy, X as getPersistedNamespaceId, Y as getPayloadRecordKey, Z as matchesConditionalRemove, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, tt as serializeProtectedRef, y as emitTSDFDebugLog } from "./asyncStorageAdapter-YuIJ7hwm.js";
2
2
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
3
3
  import { isObject } from "@ls-stack/utils/typeGuards";
4
4
  //#region src/persistentStorage/indexedDbAsyncStorageAdapter.ts
package/dist/main.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as OfflineResolutionRecord, $t as StoreError, A as DefineListQueryOfflineOperations, At as DerivedQuerySource, B as OfflineEntityMutationKind, Bt as OptimisticListUpdate, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as ListQueryUseMultipleItemsQuery, G as OfflineMutationQueueingPolicy, Gt as TSFDListQuery, H as OfflineMutationInput, Ht as QueryFetchPayload, I as ListQueryOfflineOperationDefinition, It as ListQueryUseMultipleListQueriesQuery, J as OfflineReplayRetryConfig, Jt as TSFDUseListQueryReturn, K as OfflineOperationKind, Kt as TSFDListQueryState, L as OfflineAccumulationConfig, Lt as OffsetPaginationConfig, M as DocumentOfflineOperationDefinition, Mt as FetchListFnReturnItem, N as GlobalOfflineEntity, Nt as FieldsInput, O as DefineCollectionOfflineOperations, Ot as DerivedQueriesConfig, P as GlobalOfflineStatus, Pt as FieldsOption, Q as OfflineResolutionConflictParseErrorCode, Qt as PayloadDebounce, R as OfflineAccumulationMergeContext, Rt as OnListQueryInvalidate, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as QueryStatus, V as OfflineMutationDescriptor, Vt as PartialResourcesConfig, W as OfflineMutationQueueingConfig, Wt as TSDFItemQuery, X as OfflineResolutionActionForOperation, Xt as MaybeTSDFResult, Y as OfflineResolutionAction, Yt as TSFDUsePendingOfflineItemsReturn, Z as OfflineResolutionConflictParseError, Zt as MutationSkipped, _ as ListQueryOfflineOperationsConfig, _n as TSDFDebugLogger, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, an as ValidPayload, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, cn as mutationSkipped, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dn as RequestSchedulerEvents, dt as OfflineTempEntityConfig, en as StoreFetchError, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, fn as ScheduleFetchOptions, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gn as TSDFDebugLogLevel, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, hn as TSDFDebugLogEntry, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, in as UnwrapTSDFResult, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as FetchListFnReturn, k as DefineDocumentOfflineOperations, kt as DerivedQueryContext, l as AsyncStorageNamespaceGetResult, ln as FetchType, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mn as TSDFDebugLogArea, mt as OperationResult, n as AsyncStorageDiscoveredScope, nn as StoreMutationErrorOptions, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, on as ValidStoreState, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pn as ScheduleFetchResults, pt as OperationConflict, q as OfflineQueueEntry, qt as TSFDUseListItemReturn, r as AsyncStorageDriver, rn as TSDFStatus, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, sn as fetchTypePriority, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tn as StoreMutationError, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, un as RequestSchedulerEventData, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vn as TSDFFocusDebugOperation, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yn as TSDFLoggerOptions, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as OnListQueryItemInvalidate } from "./types-BlyGC_PO.js";
1
+ import { $ as OfflineResolutionRecord, $t as StoreError, A as DefineListQueryOfflineOperations, At as DerivedQuerySource, B as OfflineEntityMutationKind, Bt as OptimisticListUpdate, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as ListQueryUseMultipleItemsQuery, G as OfflineMutationQueueingPolicy, Gt as TSFDListQuery, H as OfflineMutationInput, Ht as QueryFetchPayload, I as ListQueryOfflineOperationDefinition, It as ListQueryUseMultipleListQueriesQuery, J as OfflineReplayRetryConfig, Jt as TSFDUseListQueryReturn, K as OfflineOperationKind, Kt as TSFDListQueryState, L as OfflineAccumulationConfig, Lt as OffsetPaginationConfig, M as DocumentOfflineOperationDefinition, Mt as FetchListFnReturnItem, N as GlobalOfflineEntity, Nt as FieldsInput, O as DefineCollectionOfflineOperations, Ot as DerivedQueriesConfig, P as GlobalOfflineStatus, Pt as FieldsOption, Q as OfflineResolutionConflictParseErrorCode, Qt as PayloadDebounce, R as OfflineAccumulationMergeContext, Rt as OnListQueryInvalidate, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as QueryStatus, V as OfflineMutationDescriptor, Vt as PartialResourcesConfig, W as OfflineMutationQueueingConfig, Wt as TSDFItemQuery, X as OfflineResolutionActionForOperation, Xt as MaybeTSDFResult, Y as OfflineResolutionAction, Yt as TSFDUsePendingOfflineItemsReturn, Z as OfflineResolutionConflictParseError, Zt as MutationSkipped, _ as ListQueryOfflineOperationsConfig, _n as TSDFDebugLogger, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, an as ValidPayload, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, cn as mutationSkipped, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dn as RequestSchedulerEvents, dt as OfflineTempEntityConfig, en as StoreFetchError, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, fn as ScheduleFetchOptions, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gn as TSDFDebugLogLevel, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, hn as TSDFDebugLogEntry, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, in as UnwrapTSDFResult, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as FetchListFnReturn, k as DefineDocumentOfflineOperations, kt as DerivedQueryContext, l as AsyncStorageNamespaceGetResult, ln as FetchType, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mn as TSDFDebugLogArea, mt as OperationResult, n as AsyncStorageDiscoveredScope, nn as StoreMutationErrorOptions, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, on as ValidStoreState, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pn as ScheduleFetchResults, pt as OperationConflict, q as OfflineQueueEntry, qt as TSFDUseListItemReturn, r as AsyncStorageDriver, rn as TSDFStatus, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, sn as fetchTypePriority, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tn as StoreMutationError, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, un as RequestSchedulerEventData, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vn as TSDFFocusDebugOperation, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yn as TSDFLoggerOptions, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as OnListQueryItemInvalidate } from "./types-DDjEjIqQ.js";
2
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
3
3
  import { Emitter } from "evtmitter";
4
4
  import { Context } from "react";
@@ -1318,4 +1318,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
1318
1318
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
1319
1319
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
1320
1320
  //#endregion
1321
- export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFLoggerOptions, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
1321
+ 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, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFFocusDebugOperation, type TSDFItemQuery, type TSDFLoggerOptions, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
- import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-URS9eulL.js";
2
- import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-JsSCNBTr.js";
1
+ import { A as serializeJsonForStorage, B as getSessionProtectedKeysSnapshot, C as createShouldIgnoreItemPredicate, D as keepEntriesWithinByteBudget, E as isQuotaExceededError, F as isModeEffectivelyActive, G as parseCompactLocalStorageEntry, H as getNavigatorLockManager, I as isOfflineModeStatusValue, L as offlineItemEntityRefSchema, M as compactOfflineStatusSnapshotSchema, N as defaultOfflineRuntimeConfig, O as keepEntriesWithinByteBudgetDuringIdle, P as getIsOfflineModeFromStatus, R as offlineResolutionRecordSchema, S as getDefaultMaxBytesForScope, T as getSerializedStringSize, U as warnIfNavigatorLockUnavailable, V as setSessionProtectedKeysSnapshot, W as createCompactLocalStorageEntry, Y as getPayloadRecordKey, _ as getOfflineSessionStatusStorageKey, a as estimateManagedAsyncStorageEntrySizeBytes, b as getTSDFDebugTimingMs, c as isAsyncStorageMetadataOfflineProtected, d as registerAsyncStartupStoreCleanup, et as parsePersistedAsyncNamespaceKind, f as removeAsyncStorageNamespaceEntriesIfUnchanged, g as OFFLINE_SESSION_STATUS_STORE_NAME, h as parseAsyncStorageNamespaceKind, it as scheduleIdleCleanup, j as OfflineResolutionConflictParseError, k as removeAsyncMaintenanceEntriesIfUnchanged, l as mergeManagedAsyncStorageCustomMetadata, m as unregisterAsyncStartupStoreCleanup, nt as INITIAL_MAINTENANCE_CLEANUP_DELAY_MS, o as getAsyncStorageMaintenanceRemoveBatchSize, p as serializeProtectedRef$1, r as buildPersistedStaticPolicy, rt as createIdleCleanupContext, s as getProtectedKeysFromMetadata, tt as serializeProtectedRef, u as readAsyncStorageNamespaceIndexStateUsingDriver, v as logPersistentStorageQuotaCleanup, w as createTimedKeySet, x as resolveTSDFLogger, y as emitTSDFDebugLog, z as clearSessionProtectedKeysSnapshot } from "./asyncStorageAdapter-YuIJ7hwm.js";
2
+ import { a as encodePathSegment, i as getNavigatorStorageDirectory, n as getDirectoryHandleIfExists, r as getFileHandleIfExists } from "./opfsPersistentStorage-6OuHQ3d-.js";
3
3
  import { isWindowFocused, onWindowFocus } from "@ls-stack/browser-utils/window";
4
4
  import { filterAndMap, findAndMap, sortBy } from "@ls-stack/utils/arrayUtils";
5
5
  import { deepEqual } from "@ls-stack/utils/deepEqual";
@@ -1238,7 +1238,7 @@ const persistedListQueryDataSchema = rc_object({
1238
1238
  hasMore: rc_boolean
1239
1239
  });
1240
1240
  function normalizePersistentStorageDataSchema(schema) {
1241
- if (typeof schema === "object" && "storeSchema" in schema) return {
1241
+ if ("storeSchema" in schema) return {
1242
1242
  mode: "converted",
1243
1243
  ...schema
1244
1244
  };
@@ -2789,7 +2789,7 @@ async function clearSessionStorage(sessionKey, adapter) {
2789
2789
  }
2790
2790
  /** Clears all persistent storage entries for a given session key across built-in adapters. */
2791
2791
  async function clearAllSessionStorage(sessionKey) {
2792
- const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Bxrrj_Mt.js");
2792
+ const { indexedDbPersistentStorage, opfsPersistentStorage } = await import("./asyncStorageAdapters-Rh3o1FAG.js");
2793
2793
  await Promise.all([
2794
2794
  clearSessionStorage(sessionKey, "local-sync"),
2795
2795
  clearSessionStorage(sessionKey, opfsPersistentStorage),
@@ -5289,38 +5289,41 @@ var SessionOfflineCoordinator = class {
5289
5289
  }
5290
5290
  #scheduleRecoveryProbe(target) {
5291
5291
  this.#scheduledRecoveryMode = target.mode;
5292
- this.#recoveryTimer = setTimeout(async () => {
5292
+ this.#recoveryTimer = setTimeout(() => {
5293
5293
  this.#recoveryTimer = null;
5294
5294
  this.#scheduledRecoveryMode = null;
5295
- const nextTarget = this.#getDesiredRecoveryTarget();
5296
- if (nextTarget === null || nextTarget.mode !== target.mode) return;
5297
- let recovered = false;
5298
- try {
5299
- recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5300
- } catch {
5301
- recovered = false;
5302
- }
5303
- const recoveryCheckAt = Date.now();
5304
- if (recovered) {
5305
- this.#recoveryAttempt = 0;
5306
- if (target.mode === "network") {
5307
- this.setNetworkActive(false, {
5308
- classified: false,
5309
- recoveryCheckAt
5310
- });
5311
- return;
5312
- }
5313
- this.setOutageActive(false, { recoveryCheckAt });
5295
+ this.#runRecoveryProbe(target);
5296
+ }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5297
+ }
5298
+ async #runRecoveryProbe(target) {
5299
+ const nextTarget = this.#getDesiredRecoveryTarget();
5300
+ if (nextTarget === null || nextTarget.mode !== target.mode) return;
5301
+ let recovered = false;
5302
+ try {
5303
+ recovered = await nextTarget.recoveryCheck({ sessionKey: this.sessionKey });
5304
+ } catch {
5305
+ recovered = false;
5306
+ }
5307
+ const recoveryCheckAt = Date.now();
5308
+ if (recovered) {
5309
+ this.#recoveryAttempt = 0;
5310
+ if (target.mode === "network") {
5311
+ this.setNetworkActive(false, {
5312
+ classified: false,
5313
+ recoveryCheckAt
5314
+ });
5314
5315
  return;
5315
5316
  }
5316
- this.#updateStatus((current) => ({
5317
- ...current,
5318
- lastRecoveryCheckAt: recoveryCheckAt
5319
- }));
5320
- this.#recoveryAttempt += 1;
5321
- const nextProbeTarget = this.#getDesiredRecoveryTarget();
5322
- if (nextProbeTarget !== null && nextProbeTarget.mode === target.mode) this.#scheduleRecoveryProbe(nextProbeTarget);
5323
- }, this.#getRecoveryProbeDelay(target.recoveryProbe));
5317
+ this.setOutageActive(false, { recoveryCheckAt });
5318
+ return;
5319
+ }
5320
+ this.#updateStatus((current) => ({
5321
+ ...current,
5322
+ lastRecoveryCheckAt: recoveryCheckAt
5323
+ }));
5324
+ this.#recoveryAttempt += 1;
5325
+ const nextProbeTarget = this.#getDesiredRecoveryTarget();
5326
+ if (nextProbeTarget !== null && nextProbeTarget.mode === target.mode) this.#scheduleRecoveryProbe(nextProbeTarget);
5324
5327
  }
5325
5328
  #syncRecoveryProbe() {
5326
5329
  const target = this.#getDesiredRecoveryTarget();
@@ -6860,7 +6863,7 @@ function createOfflineStoreController(storeName, storeType, getSessionKey, onPer
6860
6863
  });
6861
6864
  }
6862
6865
  function prepareMutationWithSession(current, args) {
6863
- const operationName = String(args.operation);
6866
+ const operationName = args.operation;
6864
6867
  const operation = operations[operationName];
6865
6868
  if (!operation) throw new Error(`Unknown offline operation "${operationName}" for store "${storeName}"`);
6866
6869
  const validatedInput = validateWithSchema(operation.inputSchema, args.input);
@@ -11286,6 +11289,7 @@ function setupListQueryPersistence(config, options = {}) {
11286
11289
  const resolveItemKey = options.getItemKey ?? ((payload) => getCompositeKey(payload));
11287
11290
  const resolveQueryKey = options.getQueryKey ?? ((payload) => getCompositeKey(payload));
11288
11291
  const getItemDerivedGroup = options.getItemDerivedGroup;
11292
+ const getItemLoadedFieldsToPersist = options.getItemLoadedFieldsToPersist;
11289
11293
  const pinnedItemKeys = new Set((config.pinnedItems ?? []).map((payload) => resolveItemKey(payload)));
11290
11294
  const pinnedQueryKeys = new Set((config.pinnedQueries ?? []).map((payload) => resolveQueryKey(payload)));
11291
11295
  const shouldIgnoreItem = createShouldIgnoreItemPredicate(config.ignoreItems, resolveItemKey);
@@ -12743,7 +12747,8 @@ function setupListQueryPersistence(config, options = {}) {
12743
12747
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
12744
12748
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
12745
12749
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
12746
- const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
12750
+ const stateLoadedFields = state.itemLoadedFields[itemKey];
12751
+ const loadedFields = hasItemInState ? getItemLoadedFieldsToPersist ? getItemLoadedFieldsToPersist(itemKey, stateLoadedFields) : stateLoadedFields : hydratedItem?.loadedFields;
12747
12752
  if (item === null || itemQuery == null) {
12748
12753
  if (previousKnownLocalItemKeys.has(itemKey)) {
12749
12754
  tasks.push(itemNamespace.remove(itemKey));
@@ -12953,7 +12958,8 @@ function setupListQueryPersistence(config, options = {}) {
12953
12958
  const hasLoadedFieldsInState = Object.hasOwn(state.itemLoadedFields, itemKey);
12954
12959
  const hydratedItem = hasItemQueryInState && hasLoadedFieldsInState ? void 0 : readHydratedItem(itemKey);
12955
12960
  const itemQuery = hasItemQueryInState ? state.itemQueries[itemKey] : hydratedItem?.itemQuery;
12956
- const loadedFields = hasItemInState ? state.itemLoadedFields[itemKey] : hydratedItem?.loadedFields;
12961
+ const stateLoadedFields = state.itemLoadedFields[itemKey];
12962
+ const loadedFields = hasItemInState ? getItemLoadedFieldsToPersist ? getItemLoadedFieldsToPersist(itemKey, stateLoadedFields) : stateLoadedFields : hydratedItem?.loadedFields;
12957
12963
  if (item === null || itemQuery == null) {
12958
12964
  if (previousKnownLocalItemKeys.has(itemKey)) finalPersistedItemKeys.delete(itemKey);
12959
12965
  continue;
@@ -14829,13 +14835,13 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14829
14835
  onItemMutationsEnd();
14830
14836
  };
14831
14837
  }
14832
- function applyOptimisticListUpdates(itemKeys) {
14838
+ function applyOptimisticListUpdates(items) {
14833
14839
  if (!optimisticListUpdates) return;
14834
14840
  const queriesToInvalidate = /* @__PURE__ */ new Map();
14835
14841
  const changedQueryKeys = /* @__PURE__ */ new Set();
14836
14842
  const deferredOptimisticQueryInvalidations = deferredOptimisticQueryInvalidationsStack[deferredOptimisticQueryInvalidationsStack.length - 1];
14837
14843
  store.produceState((draftState) => {
14838
- for (const itemKey of itemKeys) {
14844
+ for (const { itemKey, payload: itemPayload } of items) {
14839
14845
  const item = draftState.items[itemKey];
14840
14846
  if (!item) continue;
14841
14847
  for (const { queries, filterItem, appendNewTo = "end", invalidateQueries, sort } of optimisticListUpdates) {
@@ -14843,7 +14849,15 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14843
14849
  for (const { key: queryKey, payload } of relatedFilterQueries) {
14844
14850
  const queryState = draftState.queries[queryKey];
14845
14851
  if (filterItem) {
14846
- const itemShouldBeIncluded = filterItem(item);
14852
+ let cachedItemIndex;
14853
+ const getItemIndex = () => cachedItemIndex ??= queryState ? queryState.items.indexOf(itemKey) : -1;
14854
+ const itemShouldBeIncluded = filterItem(item, {
14855
+ queryPayload: payload,
14856
+ itemPayload,
14857
+ get isInQuery() {
14858
+ return getItemIndex() !== -1;
14859
+ }
14860
+ });
14847
14861
  if (itemShouldBeIncluded === null) continue;
14848
14862
  if (itemShouldBeIncluded) {
14849
14863
  captureAndLockOptimisticMutationQuery(queryKey);
@@ -14860,14 +14874,15 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14860
14874
  changedQueryKeys.add(queryKey);
14861
14875
  continue;
14862
14876
  }
14863
- if (queryState.items.includes(itemKey)) continue;
14864
- if (invalidateQueries) queriesToInvalidate.set(queryKey, payload);
14865
- if (appendNewTo === "end") queryState.items.push(itemKey);
14866
- else queryState.items.unshift(itemKey);
14867
- changedQueryKeys.add(queryKey);
14877
+ if (getItemIndex() === -1) {
14878
+ if (invalidateQueries) queriesToInvalidate.set(queryKey, payload);
14879
+ if (appendNewTo === "end") queryState.items.push(itemKey);
14880
+ else queryState.items.unshift(itemKey);
14881
+ changedQueryKeys.add(queryKey);
14882
+ }
14868
14883
  } else {
14869
14884
  if (!queryState) continue;
14870
- const itemIndex = queryState.items.indexOf(itemKey);
14885
+ const itemIndex = getItemIndex();
14871
14886
  if (itemIndex !== -1) {
14872
14887
  captureAndLockOptimisticMutationQuery(queryKey);
14873
14888
  if (invalidateQueries) queriesToInvalidate.set(queryKey, queryState.payload);
@@ -14880,10 +14895,11 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14880
14895
  if (!queryState) continue;
14881
14896
  if (!queryState.items.includes(itemKey)) continue;
14882
14897
  captureAndLockOptimisticMutationQuery(queryKey);
14898
+ if (invalidateQueries) queriesToInvalidate.set(queryKey, payload);
14883
14899
  queryState.items = sortBy(queryState.items, (itemId) => {
14884
14900
  const itemState = store.state.items[itemId];
14885
14901
  const itemPayloadFromState = store.state.itemQueries[itemId]?.payload;
14886
- if (!itemState || !itemPayloadFromState) return Infinity;
14902
+ if (!itemState || itemPayloadFromState === void 0) return Infinity;
14887
14903
  return sort.sortBy(itemState, itemPayloadFromState);
14888
14904
  }, { order: sort.order });
14889
14905
  changedQueryKeys.add(queryKey);
@@ -14950,7 +14966,7 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14950
14966
  if (newData) draftState.items[itemKey] = newData;
14951
14967
  }
14952
14968
  });
14953
- if (someItemWasUpdated) applyOptimisticListUpdates(itemKeys.map((i) => i.itemKey));
14969
+ if (someItemWasUpdated) applyOptimisticListUpdates(itemKeys);
14954
14970
  if (options.ifNothingWasUpdated && !someItemWasUpdated) options.ifNothingWasUpdated();
14955
14971
  }, { type: "update-item-state" });
14956
14972
  if (updatedItemKeys.size > 0) {
@@ -14994,7 +15010,10 @@ function createMutationApi(store, fetchItemFn, partialResources, optimisticListU
14994
15010
  }
14995
15011
  }
14996
15012
  }, { action: "create-item-state" });
14997
- applyOptimisticListUpdates([itemKey]);
15013
+ applyOptimisticListUpdates([{
15014
+ itemKey,
15015
+ payload: itemPayload
15016
+ }]);
14998
15017
  });
14999
15018
  publishItemSnapshot(itemKey);
15000
15019
  for (const { key } of getQueriesRelatedToItem(itemPayload)) publishQuerySnapshot(key);
@@ -16717,9 +16736,28 @@ function createListQueryStore(storeOptions) {
16717
16736
  getSessionKey: getSessionKeyForRuntime,
16718
16737
  storeName: id
16719
16738
  }) : null;
16739
+ const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
16740
+ const itemsPendingFullInvalidation = /* @__PURE__ */ new Map();
16741
+ /**
16742
+ * Loaded fields to persist for an in-state item. An invalidation strips the
16743
+ * stale fields from `itemLoadedFields` and keeps the baseline only in the
16744
+ * in-memory tracking maps above, which do not survive a reload — persisting
16745
+ * the stripped metadata would leave the cached snapshot unusable (every
16746
+ * field `inferFields` cannot vouch for reads as never loaded). Restored
16747
+ * items are always stale (`refetchOnMount`), so the snapshot is persisted
16748
+ * with every field it still holds, stale or not.
16749
+ */
16750
+ function getItemLoadedFieldsToPersist(itemKey, loadedFields) {
16751
+ if (loadedFields === void 0 || loadedFields === "*") return loadedFields;
16752
+ if (itemsPendingFullInvalidation.has(itemKey)) return "*";
16753
+ const pendingFields = itemPendingInvalidationFields.get(itemKey);
16754
+ if (!pendingFields || pendingFields.size === 0) return loadedFields;
16755
+ return Array.from(new Set([...loadedFields, ...pendingFields.keys()])).sort();
16756
+ }
16720
16757
  const persistence = resolvedPersistentStorageConfig ? setupListQueryPersistence(resolvedPersistentStorageConfig, {
16721
16758
  getItemKey,
16722
16759
  getItemDerivedGroup: derivedQueries?.getItemGroup,
16760
+ getItemLoadedFieldsToPersist: partialResources ? getItemLoadedFieldsToPersist : void 0,
16723
16761
  getQueryKey
16724
16762
  }) : null;
16725
16763
  const persistentStorageErrorReporter = resolvedPersistentStorageConfig ? resolvedPersistentStorageConfig.onPersistentStorageError : storeManager.onPersistentStorageError;
@@ -16941,8 +16979,6 @@ function createListQueryStore(storeOptions) {
16941
16979
  preloaded: results[index] ?? false
16942
16980
  }));
16943
16981
  }
16944
- const itemPendingInvalidationFields = /* @__PURE__ */ new Map();
16945
- const itemsPendingFullInvalidation = /* @__PURE__ */ new Map();
16946
16982
  const itemDroppedFieldInvalidations = /* @__PURE__ */ new Map();
16947
16983
  const itemMutationCountsWithoutScheduler = /* @__PURE__ */ new Map();
16948
16984
  const { getQueryState, getQueriesKeyArray, getQueriesState, getQueriesRelatedToItem, getItemsKeyArray, getItemState, scheduleListQueryFetch, loadMore, awaitListQueryFetch, getQueryFromStateOrFetch, scheduleItemFetch, awaitItemFetch, getItemFromStateOrFetch, getOrCreateQueryScheduler, getOrCreateItemScheduler, getKnownQueryScheduler, getKnownItemScheduler, syncRemoteFetchStart, syncRemoteFetchSuccess, deleteQueryFetchResources, deleteItemFetchResources, resetSchedulers, reevaluateDelayedRTUs } = createFetchApi(store, normalizedFetchListFn, offsetPagination, fetchItemFn, batchFetchItemFn, getItemsBatchKey, errorNormalizer, partialResources, lowPriorityThrottleMs, getCoalescingWindowMs, mediumPriorityDelayMs, wrappedDynamicRealtimeThrottleMs, onSchedulerEvent, usesRealTimeUpdates, defaultQuerySize, maxItemBatchSize, getQueryKey, getItemKey, normalizeFieldsOption, !!persistence && !persistence.hasAsyncPreload, persistence ? (queryKeys) => persistence.preloadQueries(queryKeys) : void 0, persistence ? (itemKeys) => persistence.preloadItems(itemKeys) : void 0, persistence, testOptions?.initialLastFetchStartTime, (requests, startedAt) => {
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-BngS1m0X.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CapHC7zC.js";
2
2
  export { opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-JsSCNBTr.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-6OuHQ3d-.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { $ as parseAsyncStorageRecordKey, J as getNamespaceId, Y as getPayloadRecordKey, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, y as emitTSDFDebugLog } from "./asyncStorageAdapter-URS9eulL.js";
1
+ import { $ as parseAsyncStorageRecordKey, J as getNamespaceId, Y as getPayloadRecordKey, b as getTSDFDebugTimingMs, et as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter, q as encodePersistedAsyncNamespaceKind, y as emitTSDFDebugLog } from "./asyncStorageAdapter-YuIJ7hwm.js";
2
2
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
3
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
4
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -887,6 +887,6 @@ var OpfsAsyncStorageDriver = class {
887
887
  };
888
888
  //#endregion
889
889
  //#region src/persistentStorage/opfsPersistentStorage.ts
890
- const opfsPersistentStorage = /* @__PURE__ */ createAsyncStorageAdapter(new OpfsAsyncStorageDriver());
890
+ const opfsPersistentStorage = /* @__PURE__ */ createAsyncStorageAdapter(/* @__PURE__ */ new OpfsAsyncStorageDriver());
891
891
  //#endregion
892
892
  export { encodePathSegment as a, getNavigatorStorageDirectory as i, getDirectoryHandleIfExists as n, getFileHandleIfExists as r, opfsPersistentStorage as t };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-BlyGC_PO.js";
1
+ import { t as AsyncStorageAdapter } from "./types-DDjEjIqQ.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -272,8 +272,26 @@ type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload ex
272
272
  }) => void;
273
273
  /** Rule for keeping cached list query membership in sync after item updates. */
274
274
  type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
275
- /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
276
- filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
275
+ /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
276
+ /**
277
+ * Decides whether an item belongs in each affected query. Called once per
278
+ * affected query, so a single rule can decide membership from
279
+ * `context.queryPayload` instead of needing one rule per query.
280
+ *
281
+ * - `true`: the item should be in the query (added if missing)
282
+ * - `false`: the item should not be in the query (removed if present)
283
+ * - `null`: keep the membership as is and skip this rule for the query
284
+ */
285
+ filterItem?: (item: ItemState, context: {
286
+ /** Payload of the query being evaluated. */readonly queryPayload: QueryPayload; /** Payload of the item being evaluated. */
287
+ readonly itemPayload: ItemPayload;
288
+ /**
289
+ * Whether the item is in the query's cached list right before this rule
290
+ * is applied. Computed on first read, so it costs nothing when unused,
291
+ * and must be read while `filterItem` is running.
292
+ */
293
+ readonly isInQuery: boolean;
294
+ }) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
277
295
  appendNewTo?: 'start' | 'end';
278
296
  /**
279
297
  * Schedules a background refetch of queries this rule mutated. Leave off
@@ -74,7 +74,41 @@ filterItem: (item) => {
74
74
 
75
75
  - When `filterItem` returns `true` and the item is not in the query, it's added at the position specified by `appendNewTo`
76
76
  - When `filterItem` returns `false` and the item is in the query, it's removed
77
- - When `filterItem` returns `null`, the rule is skipped for that item
77
+ - When `filterItem` returns `null`, the rule is skipped for that item in that query
78
+
79
+ `filterItem` is called once for each matching query and receives a context object as second argument:
80
+
81
+ | Field | Description |
82
+ | -------------- | -------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `queryPayload` | Payload of the query being evaluated |
84
+ | `itemPayload` | Payload of the item being evaluated |
85
+ | `isInQuery` | Whether the item is in the query right before the rule is applied. Computed on first read; read it while `filterItem` is running |
86
+
87
+ With the query payload, one rule can decide membership for every query, instead of one rule per filter combination:
88
+
89
+ ```ts
90
+ optimisticListUpdates: [
91
+ {
92
+ queries: () => true,
93
+ filterItem: (task, { queryPayload }) =>
94
+ taskBelongsToQuery(task, queryPayload),
95
+ },
96
+ ];
97
+ ```
98
+
99
+ Return `null` for queries whose filters depend on data the client cannot evaluate (server-side search, permissions). `isInQuery` tells if the item already passed those filters on the server:
100
+
101
+ ```ts
102
+ filterItem: (task, { queryPayload, isInQuery }) => {
103
+ const matchesLocalFilters = taskMatchesLocalFilters(task, queryPayload);
104
+
105
+ if (!queryPayload.search) return matchesLocalFilters;
106
+
107
+ // In the query: it already matched the search, so only the local filters
108
+ // can remove it. Not in the query: no way to know, keep as is.
109
+ return isInQuery ? matchesLocalFilters : null;
110
+ };
111
+ ```
78
112
 
79
113
  ### appendNewTo
80
114
 
@@ -117,6 +151,8 @@ Schedules a background refetch of queries this rule mutated.
117
151
  invalidateQueries: true;
118
152
  ```
119
153
 
154
+ With `invalidateQueries` enabled, a rule with `sort` refetches every matching query that contains the updated item on each update, even when the optimistic order did not change — the client can't tell whether the server order did.
155
+
120
156
  ## When Rules Are Applied
121
157
 
122
158
  Optimistic list updates are triggered by:
@@ -143,6 +143,8 @@ If you enable `showPartialAsRefetching`, the hook exposes `loadingFields` with t
143
143
 
144
144
  Invalidations are refetches, not new loads: when an invalidation (full or per-field) marks cached data as stale, hooks whose requested fields are still present keep the stale data visible while the refetch is in flight (with a `refetching` status when `returnRefetchingStatus` is enabled). Data is only hidden behind `loading` when a requested field was genuinely never loaded.
145
145
 
146
+ The same holds across reloads with persistent storage: an item invalidated before the page was closed is persisted with every field its snapshot still holds, and is restored as stale cached data: shown right away, then refetched on mount (a hook with a `fields` selection refetches only the fields it requests). An invalidated fully-loaded (`'*'`) item still satisfies `fields: '*'` reads from cache, which keeps it readable when the app is reopened offline.
147
+
146
148
  ## Fields in Scheduling and Fetching
147
149
 
148
150
  Fields propagate through the scheduling and fetching APIs:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "18.1.0",
3
+ "version": "18.2.0",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Lucas Santos",
@@ -42,26 +42,24 @@
42
42
  "node": ">=16.0.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@ls-stack/eslint-cfg": "^0.10.0",
46
- "@ls-stack/extended-lint": "^0.89.3",
45
+ "@ls-stack/fast-lint": "^0.7.0",
47
46
  "@playwright/test": "^1.58.2",
48
47
  "@testing-library/react": "^16.3.2",
49
48
  "@types/node": "^25.0.3",
50
49
  "@types/react": "^18.3.27",
51
50
  "@types/react-dom": "^18.3.7",
52
- "@typescript/native-preview": "7.0.0-dev.20260302.1",
53
51
  "@vitest/coverage-v8": "4.1.2",
54
52
  "@vitest/ui": "^4.1.0",
55
- "eslint": "^9.39.2",
56
- "eslint-plugin-react-hooks": "^7.0.1",
57
53
  "fake-indexeddb": "^6.2.5",
58
54
  "happy-dom": "^20.8.4",
59
55
  "knip": "^6.4.1",
60
56
  "oxfmt": "^0.40.0",
57
+ "oxlint": "1.94.0",
61
58
  "react": "^19.2.3",
62
59
  "react-dom": "^19.2.3",
63
60
  "simple-git-hooks": "^2.13.1",
64
61
  "tsdown": "^0.21.10",
62
+ "tsrs": "0.25.0-ts7.1.0-beta",
65
63
  "typescript": "^5.9.3",
66
64
  "vite": "^8.0.0",
67
65
  "vitest": "^4.1.0",
@@ -96,11 +94,12 @@
96
94
  "test:coverage": "vitest run --coverage",
97
95
  "test:all": "vitest --run && playwright test",
98
96
  "lint": "pnpm lint:lib && pnpm --filter @tsdf/playground lint",
99
- "lint:lib": "pnpm tsc && pnpm tsc:isolated && pnpm eslint",
100
- "eslint": "eslint src/ tests/ --fix",
97
+ "lint:lib": "pnpm oxlint && pnpm fast-lint && pnpm typecheck:extra",
98
+ "oxlint": "oxlint --type-check src/ tests/ --deny-warnings --fix",
99
+ "fast-lint": "fast-lint src/ tests/ --max-warnings 0 --fix",
101
100
  "format": "oxfmt src/ tests/ apps/playground/src/",
102
- "tsc": "tsgo -p tsconfig.prod.json && tsgo -p tsconfig.playwright-fixture.json",
103
- "tsc:isolated": "tsgo -p tsconfig.isolated.json",
101
+ "typecheck": "tsrs --fast && pnpm typecheck:extra",
102
+ "typecheck:extra": "tsrs --fast -p tsconfig.isolated.json && tsrs --fast -p tsconfig.playwright-fixture.json",
104
103
  "dev": "pnpm --filter @tsdf/playground dev",
105
104
  "playground:build": "pnpm --filter @tsdf/playground build",
106
105
  "build": "pnpm lint && pnpm test:all && pnpm build:no-test",