tsdf 16.0.3 → 17.0.0-alpha.10

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.
Files changed (39) hide show
  1. package/LICENSE +140 -0
  2. package/README.md +5 -0
  3. package/dist/async-storage.d.ts +2 -0
  4. package/dist/async-storage.js +2 -0
  5. package/dist/asyncStorageAdapter-BMYAF6rt.d.ts +6 -0
  6. package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
  7. package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
  8. package/dist/indexed-db-storage.d.ts +14 -0
  9. package/dist/indexed-db-storage.js +2 -0
  10. package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
  11. package/dist/main.d.ts +1487 -373
  12. package/dist/main.js +16146 -2475
  13. package/dist/opfs-storage.d.ts +2 -0
  14. package/dist/opfs-storage.js +2 -0
  15. package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
  16. package/dist/opfsPersistentStorage-CBnUebnf.d.ts +6 -0
  17. package/dist/types-2zQlbxtw.d.ts +1475 -0
  18. package/docs/README.md +98 -0
  19. package/docs/batch-fetching.md +125 -0
  20. package/docs/browser-tabs-sync.md +61 -0
  21. package/docs/cache-limits.md +105 -0
  22. package/docs/collection-store.md +173 -0
  23. package/docs/document-store.md +149 -0
  24. package/docs/fetch-scheduling.md +93 -0
  25. package/docs/hooks.md +416 -0
  26. package/docs/invalidation.md +135 -0
  27. package/docs/list-query-store.md +352 -0
  28. package/docs/mutations.md +266 -0
  29. package/docs/offline.md +207 -0
  30. package/docs/offset-pagination.md +111 -0
  31. package/docs/optimistic-list-updates.md +180 -0
  32. package/docs/partial-resources.md +168 -0
  33. package/docs/persistent-storage.md +290 -0
  34. package/docs/real-time-updates.md +158 -0
  35. package/docs/shared-types.md +181 -0
  36. package/docs/store-manager.md +147 -0
  37. package/package.json +81 -47
  38. package/dist/main.cjs +0 -2511
  39. package/dist/main.d.cts +0 -400
package/dist/main.d.ts CHANGED
@@ -1,400 +1,1514 @@
1
- import { Store } from 't-state';
1
+ import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as PayloadDebounce, B as OfflineEntityMutationKind, Bt as mutationSkipped, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as TSDFStatus, G as OfflineMutationQueueingPolicy, Gt as ScheduleFetchResults, H as OfflineMutationInput, Ht as RequestSchedulerEventData, I as ListQueryOfflineOperationDefinition, It as UnwrapTSDFResult, J as OfflineReplayRetryConfig, Jt as TSDFDebugLogLevel, K as OfflineOperationKind, Kt as TSDFDebugLogArea, L as OfflineAccumulationConfig, Lt as ValidPayload, M as DocumentOfflineOperationDefinition, Mt as StoreFetchError, N as GlobalOfflineEntity, Nt as StoreMutationError, O as DefineCollectionOfflineOperations, Ot as MaybeTSDFResult, P as GlobalOfflineStatus, Pt as StoreMutationErrorOptions, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as ValidStoreState, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as RequestSchedulerEvents, V as OfflineMutationDescriptor, Vt as FetchType, W as OfflineMutationQueueingConfig, Wt as ScheduleFetchOptions, X as OfflineResolutionActionForOperation, Xt as TSDFDebugOptions, Y as OfflineResolutionAction, Yt as TSDFDebugLogger, Z as OfflineResolutionConflictParseError, _ as ListQueryOfflineOperationsConfig, _t as defaultOfflineRuntimeConfig, a as AsyncStorageMetadataOrder, at as OfflineSession, b as PersistentStorageDataSchema, bt as OfflineSessionUploadsConfig, c as AsyncStorageNamespaceCommitUpsert, ct as OfflineSyncState, d as AsyncStorageNamespaceKind, dt as OfflineTempEntityConfig, et as OfflineResolutionRecordForOperation, f as AsyncStorageNamespaceScope, ft as OfflineTempEntityPendingEntry, g as DocumentPersistentStorageConfig, gt as ParsedOfflineResolutionConflictResultForStore, h as ConvertedPersistentStorageDataSchema, ht as ParsedOfflineResolutionConflictResultForOperation, i as AsyncStorageDriverSetEntry, it as OfflineRuntimeConfigUpdate, j as DefineOfflineOperation, jt as StoreError, k as DefineDocumentOfflineOperations, kt as MutationSkipped, l as AsyncStorageNamespaceGetResult, lt as OfflineTempEntitiesConfig, m as CollectionPersistentStorageConfig, mt as OperationResult, n as AsyncStorageDiscoveredScope, nt as OfflineRetryExhaustedResolutionAction, o as AsyncStorageNamespaceCommitArgs, ot as OfflineSessionConfig, p as AsyncStorageReadOptions, pt as OperationConflict, q as OfflineQueueEntry, qt as TSDFDebugLogEntry, r as AsyncStorageDriver, rt as OfflineRuntimeConfig, s as AsyncStorageNamespaceCommitTouch, st as OfflineSupersedeConfig, t as AsyncStorageAdapter, tt as OfflineResolutionRecordForStore, u as AsyncStorageNamespaceHandle, ut as OfflineTempEntitiesReconciliation, v as ListQueryPersistentStorageConfig, vt as OfflineMutationUploadsInput, w as StorageAdapter, wt as OfflineUploadProgress, x as PersistentStorageErrorHandler, xt as OfflineStoredUploadRecord, y as PersistentStorageBaseConfig, yt as OfflineOperationUploadsContext, z as OfflineConflictResolutionAction, zt as fetchTypePriority } from "./types-2zQlbxtw.js";
2
+ import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
3
+ import { Emitter } from "evtmitter";
4
+ import { Context } from "react";
5
+ import { Result } from "t-result";
6
+ import { Store } from "t-state";
2
7
 
3
- type FetchType = 'lowPriority' | 'highPriority' | 'realtimeUpdate';
4
- type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled';
5
-
6
- type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
7
- type ValidPayload = number | string | Record<string, unknown>;
8
- type ValidStoreState = Record<string, unknown> | any[];
9
-
10
- type DocumentStatus = TSDFStatus | 'idle';
11
- type TSDFDocumentStoreState<State extends ValidStoreState, NError> = {
12
- data: State | null;
13
- error: NError | null;
14
- status: DocumentStatus;
15
- refetchOnMount: false | FetchType;
16
- };
17
- type TSDFUseDocumentReturn<Selected, NError> = {
18
- status: DocumentStatus;
19
- data: Selected;
20
- error: NError | null;
21
- isLoading: boolean;
8
+ //#region src/persistentStorage/offline/mutationRuntime.d.ts
9
+ /**
10
+ * Successful result of an offline-enabled mutation attempt.
11
+ *
12
+ * `online` means the direct request completed and returned the server payload.
13
+ * `queued` means the mutation was durably persisted for offline replay.
14
+ */
15
+ type OfflineMutationResult<T> = {
16
+ /** The direct online mutation completed successfully. */kind: 'online'; /** Server payload returned by the direct mutation. */
17
+ data: Awaited<T>;
18
+ } | {
19
+ /** The mutation was durably queued for offline replay. */kind: 'queued';
22
20
  };
23
- type OnDocumentInvalidate = (priority: FetchType) => void;
24
- declare function newTSDFDocumentStore<State extends ValidStoreState, NError>({ debugName, fetchFn, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, disableInitialDataInvalidation, errorNormalizer, onInvalidate, }: {
25
- debugName?: string;
26
- fetchFn: () => Promise<State>;
27
- getInitialData?: () => State | undefined;
28
- disableInitialDataInvalidation?: boolean;
29
- errorNormalizer: (exception: unknown) => NError;
30
- disableRefetchOnMount?: boolean;
31
- lowPriorityThrottleMs?: number;
32
- mediumPriorityThrottleMs?: number;
33
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
34
- onInvalidate?: OnDocumentInvalidate;
35
- }): {
36
- store: Store<TSDFDocumentStoreState<State, NError>>;
37
- reset: () => void;
38
- awaitFetch: () => Promise<{
39
- data: State;
40
- error: null;
41
- } | {
42
- data: null;
43
- error: NError;
44
- }>;
45
- scheduleFetch: (fetchType: FetchType) => ScheduleFetchResults;
46
- invalidateData: (priority?: FetchType) => void;
47
- useDocument: <Selected = State | null>({ selector, isOffScreen, disabled, returnRefetchingStatus, disableRefetchOnMount, returnIdleStatus, ensureIsLoaded, selectorUsesExternalDeps, }?: {
48
- selector?: (data: State | null) => Selected;
49
- disabled?: boolean;
50
- isOffScreen?: boolean;
51
- disableRefetchOnMount?: boolean;
52
- returnIdleStatus?: boolean;
53
- ensureIsLoaded?: boolean;
54
- returnRefetchingStatus?: boolean;
55
- selectorUsesExternalDeps?: boolean;
56
- }) => Readonly<TSDFUseDocumentReturn<Selected, NError>>;
57
- updateState: (produceNewData: (draftData: State) => State | void | undefined) => boolean;
58
- startMutation: () => () => boolean;
59
- };
60
- type TSDFDocumentStore<State extends ValidStoreState, NError> = ReturnType<typeof newTSDFDocumentStore<State, NError>>;
61
-
21
+ //#endregion
22
+ //#region src/utils/performMutation.d.ts
23
+ /** Starts a temporary window-close block while a mutation is in progress. */
24
+ type BlockWindowCloseHandler = () => {
25
+ /** Releases the window-close block. */unblock: () => void;
26
+ };
27
+ /** Debounce settings for mutation calls sharing a logical context and payload. */
28
+ type MutationDebounce = {
29
+ /** Logical namespace for the debounced mutation group. */context: string; /** Payload compared with the context to decide which calls supersede each other. */
30
+ payload: unknown; /** Debounce window in milliseconds. */
31
+ ms: number;
32
+ };
33
+ //#endregion
34
+ //#region src/storeManager.d.ts
35
+ type DynamicRealtimeThrottleMs = (params: {
36
+ readonly lastFetchDuration: number;
37
+ readonly windowIsNotFocused: boolean;
38
+ }) => number;
39
+ type StoreManagerStoreDefaults = {
40
+ /** Default minimum interval between low-priority fetches for attached stores. */readonly lowPriorityThrottleMs: number; /** Default coalescing window used by attached stores when they do not override it. */
41
+ readonly baseCoalescingWindowMs: number; /** Default adaptive throttle for real-time updates in attached stores. */
42
+ readonly dynamicRealtimeThrottleMs: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. */
43
+ readonly blockWindowClose: BlockWindowCloseHandler | null; /** Default focus revalidation policy for attached stores. */
44
+ readonly revalidateOnWindowFocus: boolean | (() => boolean) | undefined;
45
+ };
46
+ type StoreManagerMutationErrorHandler = (error: unknown, options: StoreMutationErrorOptions) => void;
47
+ type StoreManagerOfflineApi<TUploadRef extends ValidPayload = ValidPayload> = {
48
+ /** Returns the shared offline config, when configured. */getOfflineConfig: () => OfflineSessionConfig<TUploadRef> | undefined; /** Latest effective runtime config for this manager's offline session. */
49
+ getOfflineRuntimeConfig: () => OfflineRuntimeConfig; /** Updates runtime controls for this manager's offline session. */
50
+ setOfflineRuntimeConfig: (update: OfflineRuntimeConfigUpdate) => Result<void, Error>; /** Resets runtime controls back to the static session config. */
51
+ resetOfflineRuntimeConfig: () => void; /** Returns the latest aggregated offline status for this manager. */
52
+ getOfflineStatus: () => GlobalOfflineStatus; /** Returns the latest aggregated offline entities for this manager. */
53
+ getOfflineEntities: () => readonly GlobalOfflineEntity[]; /** Returns the latest aggregated offline resolutions for this manager. */
54
+ getOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns the latest session-scoped offline uploads for this manager. */
55
+ getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
56
+ resolveOfflineUpload: (id: string) => Promise<Result<TUploadRef, Error>>; /** Resolves multiple staged upload ids to their latest final refs. */
57
+ resolveOfflineUploads: (ids: readonly string[]) => Promise<Result<Record<string, TUploadRef>, Error>>; /** Saves a session-scoped upload locally for later dependency resolution. */
58
+ saveOfflineUpload: (args: {
59
+ id: string;
60
+ file: Blob | File;
61
+ }) => Promise<Result<void, Error>>; /** Replaces a previously stored session-scoped upload. */
62
+ replaceOfflineUpload: (args: {
63
+ id: string;
64
+ file: Blob | File;
65
+ }) => Promise<Result<void, Error>>; /** Loads a previously stored session-scoped upload. */
66
+ loadOfflineUpload: (id: string) => Promise<Result<File | null, Error>>; /** Deletes a stored upload when it is no longer referenced. */
67
+ deleteOfflineUpload: (id: string) => Promise<Result<void, Error>>; /** React hook subscribing to the manager's aggregated offline status. */
68
+ useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the manager's aggregated offline entities. */
69
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to the manager's aggregated offline resolutions. */
70
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the manager's aggregated offline uploads. */
71
+ useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
72
+ };
73
+ /** Shared coordinator passed to every TSDF store instance in an app/session. */
74
+ type StoreManager<TUploadRef extends ValidPayload = ValidPayload> = {
75
+ /** Returns the active shared session / tenant key. */getSessionKey: () => string | false; /** Shared debug logger for browser-tab sync and persistent storage internals. */
76
+ debugLogger?: TSDFDebugLogger; /** Normalizes raw exceptions into the shared StoreError shape. */
77
+ errorNormalizer: (exception: Error) => StoreError; /** Global fallback for persistent storage failures in attached stores. */
78
+ onPersistentStorageError: PersistentStorageErrorHandler | undefined; /** Global fallback for mutation failures in attached stores. */
79
+ onMutationError: StoreManagerMutationErrorHandler | undefined; /** Shared defaults used by attached stores unless a store-level override exists. */
80
+ storeDefaults: StoreManagerStoreDefaults; /** Returns the unique ids of all currently registered store instances. */
81
+ getAllStoreIds: () => string[]; /** Resets all registered stores except the ignored logical ids. */
82
+ resetAll: (ignoreStores: string[]) => void; /** Signals a shared real-time transport reconnect to all registered stores. */
83
+ onTransportReconnect: () => void;
84
+ } & StoreManagerOfflineApi<TUploadRef>;
85
+ /** Options used to create a shared TSDF store manager. */
86
+ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> = {
87
+ /**
88
+ * Returns the current authenticated session / tenant key shared by all
89
+ * stores attached to this manager. Return `false` to disable session-scoped
90
+ * behavior while no account is loaded.
91
+ */
92
+ getSessionKey: () => string | false; /** Normalizes raw exceptions into the shared StoreError shape. */
93
+ errorNormalizer: (exception: Error) => StoreError; /** Default minimum interval between low-priority fetches for attached stores. Defaults to 5ms. */
94
+ lowPriorityThrottleMs?: number; /** Default coalescing window for attached stores. Defaults to 10ms. */
95
+ baseCoalescingWindowMs?: number; /** Default adaptive throttle for real-time updates in attached stores. Store-level values override it. */
96
+ dynamicRealtimeThrottleMs?: DynamicRealtimeThrottleMs; /** Shared window-close blocker used by mutations in attached stores. Pass `null` to disable. */
97
+ blockWindowClose?: BlockWindowCloseHandler | null; /** Global fallback for persistent storage failures when a store does not provide its own handler. */
98
+ onPersistentStorageError?: PersistentStorageErrorHandler; /** Global fallback for mutation failures when a store does not provide its own handler. */
99
+ onMutationError?: StoreManagerMutationErrorHandler; /** Default focus revalidation policy for attached stores. Store-level values override it. */
100
+ revalidateOnWindowFocus?: boolean | (() => boolean);
101
+ /**
102
+ * Enables debug logs for browser-tab sync and persistent storage operations.
103
+ * Pass `true` to use console logging, or pass a logger function.
104
+ */
105
+ debug?: TSDFDebugOptions; /** Optional shared offline session config for every attached store. */
106
+ offlineSession?: OfflineSessionConfig<TUploadRef>;
107
+ };
108
+ declare function createStoreManager<TUploadRef extends ValidPayload = ValidPayload>(options: CreateStoreManagerOptions<TUploadRef>): StoreManager<TUploadRef>;
109
+ //#endregion
110
+ //#region src/collectionStore/useMultipleItems.d.ts
111
+ type UseMultipleItemsOptions$1<ItemState extends ValidStoreState, Selected> = {
112
+ /** Maps each item before it is returned from the hook. */selector?: (data: ItemState | null) => Selected; /** Returns `idle` instead of `loading` while items have not been fetched. */
113
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
114
+ returnRefetchingStatus?: boolean; /** Omits `payload` from each query result unless overridden per item. */
115
+ omitPayload?: boolean;
116
+ /**
117
+ * Only fetches when an item is missing from state, skipping stale-state and
118
+ * invalidation refetches.
119
+ */
120
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
121
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
122
+ isOffScreen?: boolean;
123
+ /**
124
+ * Debounces automatic fetches caused by payload changes, while selection
125
+ * still reads from the latest payload. Supports trailing debounce via `ms`,
126
+ * optional `leading`, and optional `maxWait`.
127
+ */
128
+ debouncePayload?: PayloadDebounce;
129
+ };
130
+ //#endregion
131
+ //#region src/collectionStore/useItem.d.ts
132
+ type UseItemOptions$1<ItemState extends ValidStoreState, Selected> = UseMultipleItemsOptions$1<ItemState, Selected> & {
133
+ /**
134
+ * Forces a high-priority fetch on mount and keeps the hook in `loading`
135
+ * until the current payload finishes loading. Cannot be combined with
136
+ * `debouncePayload`.
137
+ */
138
+ ensureIsLoaded?: boolean;
139
+ };
140
+ //#endregion
141
+ //#region src/collectionStore/collectionStore.d.ts
142
+ /** Lifecycle status for a cached collection item. */
62
143
  type CollectionItemStatus = TSDFStatus;
63
- type TSFDCollectionItem<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, NError> = {
64
- data: ItemState | null;
65
- error: NError | null;
66
- status: CollectionItemStatus;
67
- payload: ItemPayload;
68
- refetchOnMount: false | FetchType;
69
- wasLoaded: boolean;
144
+ /** Raw cached state for one collection item. */
145
+ type TSFDCollectionItem<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
146
+ /** Latest loaded item data, or `null` before the item is available. */data: ItemState | null; /** Last fetch error for this item, when the latest fetch failed. */
147
+ error: StoreError | null; /** Current fetch lifecycle status for this item. */
148
+ status: CollectionItemStatus; /** Payload used to identify and fetch this item. */
149
+ payload: ItemPayload; /** Pending automatic refetch priority for stale data mounted by hooks. */
150
+ refetchOnMount: false | FetchType; /** Whether this item has ever loaded successfully. */
151
+ wasLoaded: boolean;
70
152
  };
71
- type TSFDCollectionState<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, NError> = Record<string, TSFDCollectionItem<ItemState, ItemPayload, NError> | null>;
72
- type TSFDUseCollectionItemReturn<Selected, ItemPayload, NError, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
73
- data: Selected;
74
- status: CollectionItemStatus | 'idle' | 'deleted';
75
- payload: ItemPayload | undefined;
76
- error: NError | null;
77
- itemStateKey: string;
78
- isLoading: boolean;
79
- queryMetadata: QueryMetadata;
153
+ /** Raw t-state shape used by a collection store. */
154
+ type TSFDCollectionState<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, TSFDCollectionItem<ItemState, ItemPayload> | null>;
155
+ /** Value returned by `CollectionStore.useItem(...)` and `useMultipleItems(...)`. */
156
+ type TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
157
+ /** Selected item data. Defaults to the full item or `null`. */data: Selected; /** Hook-visible item status, including idle/deleted states for hook ergonomics. */
158
+ status: CollectionItemStatus | 'idle' | 'deleted'; /** Item payload for this result, unless omitted or unavailable. */
159
+ payload: ItemPayload | undefined; /** Last item fetch error, if any. */
160
+ error: StoreError | null; /** Stable store key for the current item payload. */
161
+ itemStateKey: string; /** Convenience flag for `loading` or `refetching` states. */
162
+ isLoading: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
163
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
164
+ queryMetadata: QueryMetadata;
80
165
  };
81
- type CollectionInitialStateItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
82
- payload: ItemPayload;
83
- data: ItemState;
166
+ /** Item descriptor accepted by `CollectionStore.useMultipleItems(...)`. */
167
+ type CollectionUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
168
+ /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload; /** Metadata returned with this query result for caller-side bookkeeping. */
169
+ queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
170
+ omitPayload?: boolean;
171
+ /**
172
+ * Only fetches when the item is missing from state, skipping stale-state and
173
+ * invalidation refetches.
174
+ */
175
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
176
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the item has not been fetched. */
177
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
178
+ returnRefetchingStatus?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
179
+ isOffScreen?: boolean;
84
180
  };
181
+ /** Callback invoked when an already-loaded collection item is invalidated. */
85
182
  type OnCollectionItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
86
- itemState: ItemState;
87
- payload: ItemPayload;
88
- priority: FetchType;
183
+ /** Current cached item state at invalidation time. */itemState: ItemState; /** Payload of the invalidated item. */
184
+ payload: ItemPayload; /** Fetch priority requested for the invalidation. */
185
+ priority: FetchType;
89
186
  }) => void;
90
- type CollectionUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
91
- payload: ItemPayload;
92
- queryMetadata?: QueryMetadata;
93
- omitPayload?: boolean;
94
- disableRefetchOnMount?: boolean;
187
+ /** Events emitted by collection mutation lifecycle helpers. */
188
+ type CollectionStoreStoreEvents<ItemPayload extends ValidPayload> = {
189
+ /** Emitted when a mutation begins executing */mutationStart: {
190
+ mutationId: number;
191
+ items: ItemPayload[];
192
+ }; /** Emitted when a mutation completes, fails, or is skipped */
193
+ mutationEnd: {
194
+ mutationId: number;
195
+ items: ItemPayload[];
196
+ status: 'success' | 'error' | 'skipped';
197
+ }; /** Emitted when an offline temp item is reconciled to its final payload. */
198
+ tempEntityReconciled: {
199
+ tempId: ItemPayload;
200
+ finalPayload: ItemPayload;
201
+ };
202
+ };
203
+ /** Details passed when collection cache-limit cleanup evicts cached items. */
204
+ type CollectionStateCleanup<ItemPayload extends ValidPayload> = {
205
+ /** Cleanup trigger that removed these items. */reason: 'cacheLimitEviction'; /** Store keys removed from the collection state. */
206
+ itemKeys: string[]; /** Original item payloads removed from the collection state. */
207
+ payloads: ItemPayload[];
208
+ };
209
+ type InternalCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition & {
210
+ getEntityRefs: (ctx: {
211
+ input: __LEGIT_ANY__;
212
+ }) => CollectionOfflineEntityRef<ItemPayload>[];
213
+ }> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
214
+ type CollectionOfflineOperationsConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations<ItemState, ItemPayload> | null;
215
+ /** Options used to create a collection store. */
216
+ type CollectionStoreOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown> = {
217
+ /**
218
+ * Stable id for this logical collection store. Used for debug labels,
219
+ * persistence namespaces, and browser tab sync.
220
+ */
221
+ id: string; /** Shared global store manager providing session scoping and error normalization. */
222
+ storeManager: StoreManager; /** Fetches one item by payload. */
223
+ fetchFn: (params: ItemPayload, signal: AbortSignal) => Promise<MaybeTSDFResult<ItemState>>; /** Optional batch fetch function for fetching multiple items at once */
224
+ batchFetchFn?: (payloads: ItemPayload[], signal: AbortSignal, batchKey: string) => Promise<MaybeTSDFResult<Map<ItemPayload, MaybeTSDFResult<ItemState> | Error>>>; /** Optional function to group batch fetches by key. When omitted, all batched items share one default batch key. Return false to fall back to individual fetchFn */
225
+ getItemsBatchKey?: (payload: ItemPayload) => string | false; /** Max items per batch - triggers immediate fetch when reached */
226
+ maxBatchSize?: number; /** Maximum number of cached items kept in memory. Defaults to 5,000. Inactive items are evicted in LRU order, while mounted hook items stay protected. */
227
+ maxItems?: number; /** Called when cache-limit eviction removes items from in-memory state. */
228
+ onStateCleanup?: (cleanup: CollectionStateCleanup<ItemPayload>) => void; /** Converts an item payload to the stable cache key used by this store. */
229
+ getCollectionItemKey?: (params: ItemPayload) => ValidPayload | unknown[]; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
230
+ lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
231
+ baseCoalescingWindowMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
232
+ mediumPriorityDelayMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
233
+ dynamicRealtimeThrottleMs?: (params: {
234
+ lastFetchDuration: number;
235
+ windowIsNotFocused: boolean;
236
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
237
+ revalidateOnWindowFocus?: boolean | (() => boolean);
238
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
239
+ * additional reconnects within the cooldown are coalesced into one trailing
240
+ * revalidation. Set to `0` to disable this cooldown. */
241
+ transportReconnectCooldownMs?: number; /** Called when an already-loaded item is invalidated. */
242
+ onInvalidate?: OnCollectionItemInvalidate<ItemState, ItemPayload>; /** Observes request scheduler lifecycle events for this store. */
243
+ onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
244
+ /**
245
+ * Store-specific mutation error handler.
246
+ *
247
+ * Overrides the manager fallback. Use `null` to disable inherited mutation
248
+ * error handling for this store.
249
+ */
250
+ onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null; /** Treats refetches as real-time driven, disabling stale mount refetches by default. Defaults to `false`. */
251
+ usesRealTimeUpdates?: boolean;
252
+ /** Opt-in persistent storage configuration. When provided, cached items are loaded
253
+ * from storage on first read and saved back on successful fetches.
254
+ * Session scoping always reuses this store manager's `getSessionKey`, and the
255
+ * persisted namespace always reuses this store's `id`. */
256
+ persistentStorage?: CollectionPersistentStorageConfig<ItemState, ItemPayload, StorageState, TOfflineOperations>;
257
+ };
258
+ /** Event payloads emitted by `CollectionStore.events`. */
259
+ type CollectionStoreEvents = {
260
+ /** Emitted whenever one or more cached items are invalidated. */invalidateData: {
261
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated item. */
262
+ itemKey: string;
263
+ };
264
+ };
265
+ type CollectionFilterItemsFn<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (params: ItemPayload, data: ItemState | null) => boolean;
266
+ type ResolvedCollectionOfflineOperations<TOfflineOperations> = TOfflineOperations extends null ? Record<never, never> : Exclude<TOfflineOperations, null>;
267
+ type CollectionMutationPayload<ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[] | null;
268
+ type CollectionMutationTarget<ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[];
269
+ type CollectionMutationPayloadToUse<ItemPayload extends ValidPayload> = CollectionMutationTarget<ItemPayload>;
270
+ type CollectionMutationArgsBase<T, ItemPayload extends ValidPayload> = {
271
+ /**
272
+ * Applies optimistic updates for the affected item payloads before the
273
+ * mutation runs. Return `false` to cancel the mutation before the async
274
+ * mutation function is called.
275
+ */
276
+ optimisticUpdate?: (payload: CollectionMutationPayloadToUse<ItemPayload>) => void | boolean; /** Performs the server mutation for the affected item payloads. */
277
+ mutation: (payload: CollectionMutationPayloadToUse<ItemPayload>) => Promise<T>; /** Called after a successful online mutation. */
278
+ onSuccess?: (response: UnwrapTSDFResult<Awaited<T>>, payload: CollectionMutationPayloadToUse<ItemPayload>) => void; /** Invalidates affected items after a successful online mutation. */
279
+ revalidateOnSuccess?: boolean;
280
+ /**
281
+ * Passes `{ silentErrors: true }` to `onMutationError`.
282
+ *
283
+ * The handler is still called so centralized logging and recovery can run,
284
+ * but UI handlers can suppress user-facing notifications.
285
+ */
286
+ silentErrors?: boolean; /** Debounces mutations with the same context and payload. Superseded calls are skipped. */
287
+ debounce?: {
288
+ context: string;
289
+ payload: __LEGIT_ANY__;
290
+ ms: number;
291
+ };
292
+ };
293
+ type CollectionOnlineMutationArgs<T, ItemPayload extends ValidPayload> = CollectionMutationArgsBase<T, ItemPayload> & {
294
+ offline?: undefined;
295
+ upload?: undefined;
296
+ };
297
+ type CollectionOfflineMutationArgs<T, ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload>> = CollectionMutationArgsBase<T, ItemPayload> & {
298
+ /**
299
+ * Queues this mutation through the store's registered offline operation when
300
+ * the session is offline or the direct request fails with an offline outage.
301
+ */
302
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
303
+ upload?: OfflineMutationUploadsInput;
304
+ };
305
+ type CollectionPerformMutation<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload>> = {
306
+ /**
307
+ * Runs a collection mutation for one or more existing item payloads.
308
+ *
309
+ * Returns the direct server result when offline replay is not configured for
310
+ * this call.
311
+ */
312
+ <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
313
+ /**
314
+ * Runs a collection mutation for one or more existing item payloads, with
315
+ * durable offline queueing as a fallback.
316
+ *
317
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
318
+ * the server payload.
319
+ */
320
+ <T>(payload: CollectionMutationTarget<ItemPayload>, args: CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
321
+ /**
322
+ * Runs a collection mutation with no current item target.
323
+ *
324
+ * Use this for create mutations that do not have a pre-generated item payload
325
+ * yet. Optimistic updates are not available without a target payload.
326
+ */
327
+ <T>(payload: null, args: Omit<CollectionOnlineMutationArgs<T, ItemPayload>, 'optimisticUpdate'>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
328
+ /**
329
+ * Runs an offline-capable collection mutation with no current item target.
330
+ *
331
+ * Use this for create mutations that do not have a pre-generated item payload
332
+ * yet. When the mutation is queued, the result is `{ kind: 'queued' }`.
333
+ */
334
+ <T>(payload: null, args: Omit<CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
335
+ <T>(payload: CollectionMutationPayload<ItemPayload>, args: CollectionOnlineMutationArgs<T, ItemPayload> | CollectionOfflineMutationArgs<T, ItemState, ItemPayload, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
336
+ };
337
+ /** Public API returned by `createCollectionStore(...)`. */
338
+ type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null> = {
339
+ /** Underlying t-state store containing raw cached items. */store: Store<TSFDCollectionState<ItemState, ItemPayload>>; /** Invalidation event emitter used by hooks and integrations. */
340
+ events: Emitter<CollectionStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
341
+ storeEvents: Emitter<CollectionStoreStoreEvents<ItemPayload>>; /** Item keys that have been explicitly invalidated and are awaiting refresh. */
342
+ readonly invalidationWasTriggered: Set<string>; /** Schedules a fetch for one item or a batch of item payloads. */
343
+ scheduleFetch: {
344
+ (fetchType: FetchType, payload: ItemPayload, options?: ScheduleFetchOptions): ScheduleFetchResults;
345
+ (fetchType: FetchType, payload: ItemPayload[], options?: ScheduleFetchOptions): ScheduleFetchResults[];
346
+ }; /** Waits for an item fetch to settle and returns data or a fetch error. */
347
+ awaitFetch: (params: ItemPayload, options?: {
348
+ timeoutMs?: number;
349
+ }) => Promise<{
350
+ data: ItemState;
351
+ error: null;
352
+ } | {
353
+ data: null;
354
+ error: StoreFetchError;
355
+ }>; /** Returns cached item data when usable, otherwise fetches it first. */
356
+ getItemFromStateOrFetch: (params: ItemPayload, options?: {
357
+ /** When `true`, stale cached data is ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
358
+ timeoutMs?: number;
359
+ }) => Promise<Result<ItemState, StoreFetchError>>; /** React hook for subscribing to many collection items at once. */
360
+ useMultipleItems: <Selected = ItemState | null, QueryMetadata extends undefined | Record<string, unknown> = undefined>(items: CollectionUseMultipleItemsQuery<ItemPayload, QueryMetadata>[], options?: UseMultipleItemsOptions$1<ItemState, Selected>) => readonly TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata>[]; /** React hook for subscribing to one collection item. */
361
+ useItem: <Selected = ItemState | null>(payload: ItemPayload | undefined | false | null, options?: UseItemOptions$1<ItemState, Selected>) => TSFDUseCollectionItemReturn<Selected, ItemPayload>; /** React hook that tracks whether a nested list item is still loading. */
362
+ useListItemIsLoading: (payload: ItemPayload, args: {
363
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
364
+ selector: (data: ItemState | null) => unknown; /** Called if the sub-item is still missing and no refetch is in progress. */
365
+ loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
366
+ ensureIsLoaded?: boolean;
367
+ }) => boolean; /** React hook that tracks whether a nested list item has been deleted. */
368
+ useListItemIsDeleted: (payload: ItemPayload, args: {
369
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
370
+ selector: (data: ItemState | null) => unknown; /** Called once when deletion is detected. */
371
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
372
+ ensureIsLoaded?: boolean;
373
+ }) => boolean; /** React hook for selecting one nested list item plus loading/deleted flags. */
374
+ useListItem: <Selected>(payload: ItemPayload, args: {
375
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts and maps the sub-item from the collection item data. */
376
+ selector: (data: ItemState | null) => Selected; /** Called if the sub-item is still missing and no refetch is in progress. */
377
+ loadItemFallback?: () => void; /** Called once when deletion is detected. */
378
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
379
+ ensureIsLoaded?: boolean;
380
+ }) => {
381
+ isLoading: boolean;
382
+ isDeleted: boolean;
383
+ data: Selected;
384
+ }; /** Clears in-memory state and cancels store-local runtime state. */
385
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
386
+ dispose: () => void; /** Loads item payloads from persistent storage into memory when available. */
387
+ preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>; /** Returns the stable cache key for an item payload. */
388
+ getItemKey: (params: ItemPayload) => string; /** Reads one or many cached items directly from store state. */
389
+ getItemState: {
390
+ (params: ItemPayload): TSFDCollectionItem<ItemState, ItemPayload> | undefined | null;
391
+ (params: ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>): TSFDCollectionItem<ItemState, ItemPayload>[];
392
+ }; /** Returns offline sync metadata for this store's tracked entities. */
393
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
394
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
395
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
396
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
397
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedCollectionOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
398
+ resolveOfflineResolution: <TName extends keyof ResolvedCollectionOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedCollectionOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void; /** Marks one or more items as mutating and returns a function that ends the mutation. */
399
+ startMutation: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>) => () => void; /** Marks cached items stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
400
+ invalidateItem: (itemPayload: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>, /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
401
+
402
+ priority?: FetchType) => void; /** Applies an immutable update to one or more cached collection items. */
403
+ updateItemState: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>, produceNewData: (draftData: ItemState, collectionItem: TSFDCollectionItem<ItemState, ItemPayload>) => void | ItemState, options?: {
404
+ ifNothingWasUpdated?: () => void;
405
+ }) => boolean; /** Adds or replaces one cached item directly in state. */
406
+ addItemToState: (fetchParams: ItemPayload, data: ItemState) => void; /** Deletes one or more cached items directly from state. */
407
+ deleteItemState: (fetchParams: ItemPayload | ItemPayload[] | CollectionFilterItemsFn<ItemState, ItemPayload>) => void;
408
+ /**
409
+ * Runs the full mutation lifecycle: optional optimistic update, async
410
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
411
+ */
412
+ performMutation: CollectionPerformMutation<ItemState, ItemPayload, TOfflineOperations>; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
413
+ onTransportReconnect: () => void;
414
+ };
415
+ declare function createCollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown>(storeOptions: CollectionStoreOptions<ItemState, ItemPayload, TOfflineOperations, StorageState>): CollectionStore<ItemState, ItemPayload, TOfflineOperations>;
416
+ //#endregion
417
+ //#region src/documentStore.d.ts
418
+ /** Lifecycle status for a document store. */
419
+ type DocumentStatus = 'idle' | TSDFStatus;
420
+ /** Value returned by `DocumentStore.useDocument(...)`. */
421
+ type TSDFUseDocumentReturn<Selected> = {
422
+ /** Hook-visible document status. */status: DocumentStatus; /** Selected document data. Defaults to the full document or `null`. */
423
+ data: Selected; /** Last document fetch error, if any. */
424
+ error: StoreError | null; /** Convenience flag for `loading` or `refetching` states. */
425
+ isLoading: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
426
+ pendingSync: boolean;
427
+ };
428
+ type DocumentStoreState<State extends ValidStoreState> = {
429
+ /** Latest loaded document data, or `null` before the document is available. */data: State | null; /** Last fetch error for this document, when the latest fetch failed. */
430
+ error: StoreError | null; /** Current fetch lifecycle status for the document. */
431
+ status: DocumentStatus; /** Pending automatic refetch priority for stale data mounted by hooks. */
432
+ refetchOnMount: false | FetchType;
433
+ };
434
+ type DocumentStoreEvents = {
435
+ invalidateData: FetchType;
436
+ };
437
+ type OnDocumentInvalidate = (priority: FetchType) => void;
438
+ /** Events emitted by document mutation lifecycle helpers. */
439
+ type DocumentStoreStoreEvents = {
440
+ /** Emitted when a mutation begins executing */mutationStart: {
441
+ mutationId: number;
442
+ }; /** Emitted when a mutation completes, fails, or is skipped */
443
+ mutationEnd: {
444
+ mutationId: number;
445
+ status: 'success' | 'error' | 'skipped';
446
+ };
447
+ };
448
+ type InternalDocumentOfflineOperations<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
449
+ type DocumentOfflineOperationsConfig<State extends ValidStoreState> = InternalDocumentOfflineOperations<State> | null;
450
+ type DocumentStoreOptions<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown> = {
451
+ /**
452
+ * Stable id for this logical document store. Used for debug labels,
453
+ * persistence namespaces, and browser tab sync.
454
+ */
455
+ id: string; /** Shared global store manager providing session scoping and error normalization. */
456
+ storeManager: StoreManager;
457
+ fetchFn: (signal: AbortSignal) => Promise<MaybeTSDFResult<State>>; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
458
+ lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
459
+ baseCoalescingWindowMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
460
+ dynamicRealtimeThrottleMs?: (params: {
461
+ lastFetchDuration: number;
462
+ windowIsNotFocused: boolean;
463
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
464
+ revalidateOnWindowFocus?: boolean | (() => boolean);
465
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
466
+ * additional reconnects within the cooldown are coalesced into one trailing
467
+ * revalidation. Set to `0` to disable this cooldown. */
468
+ transportReconnectCooldownMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
469
+ mediumPriorityDelayMs?: number; /** Observes request scheduler lifecycle events for this store. */
470
+ onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
471
+ /**
472
+ * Store-specific mutation error handler.
473
+ *
474
+ * Overrides the manager fallback. Use `null` to disable inherited mutation
475
+ * error handling for this store.
476
+ */
477
+ onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null;
478
+ /** Indicates that fresh data arrives via a real-time channel. Defaults to `false`. The store
479
+ * skips the mount-time stale refetch since real-time pushes already cover
480
+ * revalidation. */
481
+ usesRealTimeUpdates?: boolean;
482
+ /** Opt-in persistent storage configuration. When provided, cached data is loaded
483
+ * from storage on first read and saved back on successful fetches.
484
+ * Session scoping always reuses this store manager's `getSessionKey`, and the
485
+ * persisted namespace always reuses this store's `id`. */
486
+ persistentStorage?: DocumentPersistentStorageConfig<State, StorageState, TOfflineOperations>;
487
+ };
488
+ type ResolvedDocumentOfflineOperations<TOfflineOperations> = TOfflineOperations extends null ? Record<never, never> : Exclude<TOfflineOperations, null>;
489
+ type DocumentUpdateState<State extends ValidStoreState> = (produceNewData: (draftData: State) => State | void | undefined) => boolean;
490
+ type DocumentMutationContext<State extends ValidStoreState> = {
491
+ /** Updates the current document state during the mutation. Returns `false` when no document data is loaded. */updateState: DocumentUpdateState<State>; /** Document state at the moment the mutation function runs. */
492
+ currentState: State | null;
493
+ };
494
+ type DocumentMutationArgsBase<State extends ValidStoreState, T> = {
495
+ /**
496
+ * Applies an optimistic document update before the mutation runs.
497
+ *
498
+ * Return `false` to cancel the mutation before the async mutation function is
499
+ * called.
500
+ */
501
+ optimisticUpdate?: (currentState: State | null) => void | boolean; /** Performs the server mutation. */
502
+ mutation: (ctx: DocumentMutationContext<State>) => Promise<T>; /** Debounces mutations with the same context and payload. Superseded calls are skipped. */
503
+ debounce?: {
504
+ context: string;
505
+ payload: __LEGIT_ANY__;
506
+ ms: number;
507
+ };
508
+ /**
509
+ * Passes `{ silentErrors: true }` to `onMutationError`.
510
+ *
511
+ * The handler is still called so centralized logging and recovery can run,
512
+ * but UI handlers can suppress user-facing notifications.
513
+ */
514
+ silentErrors?: boolean; /** Invalidates the document after a successful online mutation. */
515
+ revalidateOnSuccess?: boolean;
516
+ };
517
+ type DocumentOnlineMutationArgs<State extends ValidStoreState, T> = DocumentMutationArgsBase<State, T> & {
518
+ offline?: undefined;
519
+ upload?: undefined;
520
+ };
521
+ type DocumentOfflineMutationArgs<State extends ValidStoreState, T, TOfflineOperations extends DocumentOfflineOperationsConfig<State>> = DocumentMutationArgsBase<State, T> & {
522
+ /**
523
+ * Queues this mutation through the store's registered offline operation when
524
+ * the session is offline or the direct request fails with an offline outage.
525
+ */
526
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
527
+ upload?: OfflineMutationUploadsInput;
528
+ };
529
+ type DocumentPerformMutation<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State>> = {
530
+ /**
531
+ * Runs a document mutation with optional optimistic updates and revalidation.
532
+ *
533
+ * Returns the direct server result when offline replay is not configured for
534
+ * this call.
535
+ */
536
+ <T>(args: DocumentOnlineMutationArgs<State, T>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
537
+ /**
538
+ * Runs a document mutation that may fall back to durable offline queueing.
539
+ *
540
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
541
+ * the server payload.
542
+ */
543
+ <T>(args: DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
544
+ <T>(args: DocumentOnlineMutationArgs<State, T> | DocumentOfflineMutationArgs<State, T, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
545
+ };
546
+ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null> = {
547
+ /** Underlying t-state store containing the raw document cache state. */store: Store<DocumentStoreState<State>>; /** Invalidation event emitter used by hooks and integrations. */
548
+ events: Emitter<DocumentStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
549
+ storeEvents: Emitter<DocumentStoreStoreEvents>; /** Whether the document has been explicitly invalidated and is awaiting refresh. */
550
+ readonly invalidationWasTriggered: boolean; /** Schedules a document fetch with the requested priority. */
551
+ scheduleFetch: (fetchType: FetchType, options?: ScheduleFetchOptions) => ScheduleFetchResults; /** Waits for a document fetch to settle and returns data or a fetch error. */
552
+ awaitFetch: (options?: {
553
+ timeoutMs?: number;
554
+ }) => Promise<{
555
+ data: State;
556
+ error: null;
557
+ } | {
558
+ data: null;
559
+ error: StoreFetchError;
560
+ }>; /** Returns cached document data when usable, otherwise fetches it first. */
561
+ getDataFromStateOrFetch: (options?: {
562
+ /** When `true`, stale cached data is ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
563
+ timeoutMs?: number;
564
+ }) => Promise<Result<State, StoreFetchError>>; /** Loads cached document data from persistent storage when available. */
565
+ preloadPersistentStorage: () => Promise<void>; /** Marks the document stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
566
+ invalidateData: (/** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
567
+
568
+ priority?: FetchType) => void; /** Applies an immutable update to the cached document data. */
569
+ updateState: DocumentUpdateState<State>; /** Clears in-memory state and cancels store-local runtime state. */
570
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
571
+ dispose: () => void; /** Marks the document as mutating and returns a function that ends the mutation. */
572
+ startMutation: () => () => boolean; /** Returns offline sync metadata for this store's tracked entity. */
573
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
574
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
575
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
576
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
577
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedDocumentOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
578
+ resolveOfflineResolution: <TName extends keyof ResolvedDocumentOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedDocumentOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void;
579
+ useDocument: <Selected = State | null>(args?: {
580
+ /** Maps the document data before it is returned from the hook. */selector?: (data: State | null) => Selected; /** Disables this hook subscription and prevents automatic fetches. */
581
+ disabled?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
582
+ isOffScreen?: boolean;
583
+ /**
584
+ * Only fetches when the document is missing from state, skipping stale-state
585
+ * and invalidation refetches.
586
+ */
587
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
588
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the document has not been fetched. */
95
589
  returnIdleStatus?: boolean;
590
+ /**
591
+ * Forces a high-priority fetch on mount and keeps the hook in `loading`
592
+ * until the document finishes loading.
593
+ */
594
+ ensureIsLoaded?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
96
595
  returnRefetchingStatus?: boolean;
97
- isOffScreen?: boolean;
596
+ }) => TSDFUseDocumentReturn<Selected>; /** React hook that tracks whether a nested list item is still loading. */
597
+ useListItemIsLoading: (args: {
598
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
599
+ selector: (data: State | null) => unknown; /** Called if the item is still missing and no refetch is in progress. */
600
+ loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
601
+ ensureIsLoaded?: boolean;
602
+ }) => boolean; /** React hook that tracks whether a nested list item has been deleted. */
603
+ useListItemIsDeleted: (args: {
604
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
605
+ selector: (data: State | null) => unknown; /** Called once when deletion is detected. */
606
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
607
+ ensureIsLoaded?: boolean;
608
+ }) => boolean; /** React hook for selecting one nested list item plus loading/deleted flags. */
609
+ useListItem: <Selected>(args: {
610
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts and maps the item from the document data. */
611
+ selector: (data: State | null) => Selected; /** Called if the item is still missing and no refetch is in progress. */
612
+ loadItemFallback?: () => void; /** Called once when deletion is detected. */
613
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
614
+ ensureIsLoaded?: boolean;
615
+ }) => {
616
+ isLoading: boolean;
617
+ isDeleted: boolean;
618
+ data: Selected;
619
+ };
620
+ /**
621
+ * Runs the full mutation lifecycle: optional optimistic update, async
622
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
623
+ */
624
+ performMutation: DocumentPerformMutation<State, TOfflineOperations>; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
625
+ onTransportReconnect: () => void;
98
626
  };
99
- declare function newTSDFCollectionStore<ItemState extends ValidStoreState, NError, ItemPayload extends ValidPayload>({ debugName, fetchFn, lowPriorityThrottleMs, errorNormalizer, disableInitialDataInvalidation, mediumPriorityThrottleMs, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, dynamicRealtimeThrottleMs, getCollectionItemKey: filterCollectionItemObjKey, onInvalidate, }: {
100
- debugName?: string;
101
- fetchFn: (params: ItemPayload) => Promise<ItemState>;
102
- getCollectionItemKey?: (params: ItemPayload) => ValidPayload | any[];
103
- errorNormalizer: (exception: unknown) => NError;
104
- disableRefetchOnMount?: boolean;
105
- getInitialData?: () => CollectionInitialStateItem<ItemPayload, ItemState>[] | undefined;
106
- disableInitialDataInvalidation?: boolean;
107
- lowPriorityThrottleMs?: number;
108
- mediumPriorityThrottleMs?: number;
109
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
110
- onInvalidate?: OnCollectionItemInvalidate<ItemState, ItemPayload>;
111
- }): {
112
- store: Store<TSFDCollectionState<ItemState, ItemPayload, NError>>;
113
- scheduleFetch: {
114
- (fetchType: FetchType, payload: ItemPayload): ScheduleFetchResults;
115
- (fetchType: FetchType, payload: ItemPayload[]): ScheduleFetchResults[];
116
- };
117
- awaitFetch: (params: ItemPayload) => Promise<{
118
- data: null;
119
- error: NError;
120
- } | {
121
- data: ItemState;
122
- error: null;
123
- }>;
124
- useMultipleItems: <Selected = ItemState | null, QueryMetadata extends Record<string, unknown> | undefined = undefined>(items: CollectionUseMultipleItemsQuery<ItemPayload, QueryMetadata>[], { selector, selectorUsesExternalDeps, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, omitPayload: allItemsOmitPayload, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, }?: {
125
- selector?: (data: ItemState | null) => Selected;
126
- selectorUsesExternalDeps?: boolean;
127
- returnIdleStatus?: boolean;
128
- returnRefetchingStatus?: boolean;
129
- omitPayload?: boolean;
130
- disableRefetchOnMount?: boolean;
131
- isOffScreen?: boolean;
132
- }) => readonly TSFDUseCollectionItemReturn<Selected, ItemPayload, NError, QueryMetadata>[];
133
- useItem: <Selected_1 = ItemState | null>(payload: ItemPayload | undefined | false | null, { omitPayload, selector, selectorUsesExternalDeps, ensureIsLoaded, returnRefetchingStatus, disableRefetchOnMount, returnIdleStatus, isOffScreen, }?: {
134
- selector?: ((data: ItemState | null) => Selected_1) | undefined;
135
- selectorUsesExternalDeps?: boolean | undefined;
136
- omitPayload?: boolean | undefined;
137
- returnRefetchingStatus?: boolean | undefined;
138
- disableRefetchOnMount?: boolean | undefined;
139
- ensureIsLoaded?: boolean | undefined;
140
- returnIdleStatus?: boolean | undefined;
141
- isOffScreen?: boolean | undefined;
142
- }) => TSFDUseCollectionItemReturn<Selected_1, ItemPayload, NError, undefined>;
143
- reset: () => void;
144
- getItemKey: (params: ItemPayload) => string;
145
- getItemState: {
146
- (fetchParam: ItemPayload): TSFDCollectionItem<ItemState, ItemPayload, NError> | null | undefined;
147
- (fetchParams: ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)): TSFDCollectionItem<ItemState, ItemPayload, NError>[];
148
- };
149
- startMutation: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)) => () => void;
150
- invalidateItem: (itemPayload: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean), priority?: FetchType) => void;
151
- updateItemState: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean), produceNewData: (draftData: ItemState, collectionItem: TSFDCollectionItem<ItemState, ItemPayload, NError>) => void | ItemState, ifNothingWasUpdated?: () => void) => boolean;
152
- addItemToState: (fetchParams: ItemPayload, data: ItemState) => void;
153
- deleteItemState: (fetchParams: ItemPayload | ItemPayload[] | ((params: ItemPayload, data: ItemState | null) => boolean)) => void;
154
- };
155
- type TSDFCollectionStore<ItemState extends ValidStoreState, NError, FetchParams extends ValidPayload> = ReturnType<typeof newTSDFCollectionStore<ItemState, NError, FetchParams>>;
156
-
627
+ declare function createDocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown>(storeOptions: DocumentStoreOptions<State, TOfflineOperations, StorageState>): DocumentStore<State, TOfflineOperations>;
628
+ //#endregion
629
+ //#region src/listQueryStore/types.d.ts
630
+ /** Lifecycle status for a list query or list item query. */
157
631
  type QueryStatus = TSDFStatus | 'loadingMore';
158
- type TSFDListQuery<NError, QueryPayload extends ValidPayload> = {
159
- error: NError | null;
160
- status: QueryStatus;
161
- payload: QueryPayload;
162
- hasMore: boolean;
163
- wasLoaded: boolean;
164
- refetchOnMount: false | FetchType;
165
- items: string[];
166
- };
167
- type TSDFItemQuery<NError, ItemPayload> = {
168
- error: NError | null;
169
- status: Exclude<QueryStatus, 'loadingMore'>;
170
- wasLoaded: boolean;
171
- refetchOnMount: false | FetchType;
172
- payload: ItemPayload;
632
+ /** Raw cached state for one list query. */
633
+ type TSFDListQuery<QueryPayload extends ValidPayload> = {
634
+ /** Last fetch error for this query, when the latest fetch failed. */error: StoreError | null; /** Current fetch lifecycle status for this query. */
635
+ status: QueryStatus; /** Payload used to identify and fetch this query. */
636
+ payload: QueryPayload; /** Whether another page is available. */
637
+ hasMore: boolean; /** Whether this query has ever loaded successfully. */
638
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
639
+ refetchOnMount: false | FetchType; /** Ordered item keys included in the cached query page. */
640
+ items: string[];
173
641
  };
174
- type TSFDListQueryState<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
175
- items: Record<string, ItemState | null>;
176
- queries: Record<string, TSFDListQuery<NError, QueryPayload>>;
177
- itemQueries: Record<string, TSDFItemQuery<NError, ItemPayload> | null>;
642
+ /** Raw cached state for one item query in a list-query store. */
643
+ type TSDFItemQuery<ItemPayload extends ValidPayload> = {
644
+ /** Last item fetch error, if any. */error: StoreError | null; /** Current fetch lifecycle status for this item. */
645
+ status: Exclude<QueryStatus, 'loadingMore'>; /** Whether this item has ever loaded successfully. */
646
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
647
+ refetchOnMount: false | FetchType; /** Payload used to identify and fetch this item. */
648
+ payload: ItemPayload;
178
649
  };
179
- type TSFDUseListQueryReturn<Selected, ItemPayload, NError, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
180
- items: Selected[];
181
- status: QueryStatus | 'idle';
182
- payload: ItemPayload | undefined;
183
- error: NError | null;
184
- queryKey: string;
185
- hasMore: boolean;
186
- isLoading: boolean;
187
- isLoadingMore: boolean;
188
- queryMetadata: QueryMetadata;
650
+ /** Raw t-state shape used by a list-query store. */
651
+ type TSFDListQueryState<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
652
+ /** Item data records keyed by item store key. */items: Record<string, ItemState | null>; /** List query records keyed by query store key. */
653
+ queries: Record<string, TSFDListQuery<QueryPayload>>; /** Item query records keyed by item store key. */
654
+ itemQueries: Record<string, TSDFItemQuery<ItemPayload> | null>; /** Loaded partial-resource fields for each item key. */
655
+ itemLoadedFields: Record<string, string[]>; /** Pending field invalidations for each item key. */
656
+ itemFieldInvalidationFields: Record<string, string[]>;
189
657
  };
190
- type TSFDUseListItemReturn<Selected, NError, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
191
- data: Selected;
192
- status: QueryStatus | 'idle' | 'deleted';
193
- payload: ItemPayload | null;
194
- error: NError | null;
195
- isLoading: boolean;
196
- queryMetadata: QueryMetadata;
658
+ /**
659
+ * Partial-resource fields to request.
660
+ *
661
+ * Pass a field-name array to load only those fields, or `'*'` to load the
662
+ * complete item.
663
+ */
664
+ type FieldsInput = string[] | '*';
665
+ /** Value returned by `ListQueryStore.useListQuery(...)` and `useMultipleListQueries(...)`. */
666
+ type TSFDUseListQueryReturn<Selected, QueryPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined, HasPartialResources extends boolean = false> = {
667
+ /** Selected items included in the current query result. */items: Selected[]; /** Hook-visible query status, including `idle` before a query runs. */
668
+ status: QueryStatus | 'idle'; /** Query payload for this result, unless omitted or unavailable. */
669
+ payload: QueryPayload | undefined; /** Requested partial-resource fields for this query result. */
670
+ fields: HasPartialResources extends true ? FieldsInput : FieldsInput | undefined; /** Requested partial-resource fields that are still pending. */
671
+ loadingFields?: string[]; /** Last query fetch error, if any. */
672
+ error: StoreError | null; /** Stable store key for the current query payload. */
673
+ queryKey: string; /** Whether another page is available. */
674
+ hasMore: boolean; /** Whether this result was derived from local items instead of fetched directly. */
675
+ isDerived: boolean; /** Convenience flag for `loading` or `refetching` states. */
676
+ isLoading: boolean; /** Whether a `loadMore(...)` request is currently active. */
677
+ isLoadingMore: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
678
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
679
+ queryMetadata: QueryMetadata;
680
+ };
681
+ /** Value returned by `ListQueryStore.useItem(...)` and `useMultipleItems(...)`. */
682
+ type TSFDUseListItemReturn<Selected, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
683
+ /** Selected item data. Defaults to the full item or `null`. */data: Selected; /** Hook-visible item status, including idle/deleted states for hook ergonomics. */
684
+ status: QueryStatus | 'idle' | 'deleted'; /** Item payload for this result, or `null` when unavailable. */
685
+ payload: ItemPayload | null; /** Requested partial-resource fields that are still pending. */
686
+ loadingFields?: string[]; /** Last item fetch error, if any. */
687
+ error: StoreError | null; /** Convenience flag for `loading` or `refetching` states. */
688
+ isLoading: boolean; /** Stable store key for the current item payload. */
689
+ itemStateKey: string; /** Whether this result has local offline changes that still need to sync to the server. */
690
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
691
+ queryMetadata: QueryMetadata;
692
+ };
693
+ /** Value returned by `ListQueryStore.usePendingOfflineItems(...)`. */
694
+ type TSFDUsePendingOfflineItemsReturn<Selected, ItemPayload extends ValidPayload> = {
695
+ /** Locally created or updated offline items selected by the hook. */items: Selected[]; /** Payloads for locally deleted offline items. */
696
+ deletedItems: ItemPayload[];
197
697
  };
698
+ /** One item returned from a list query fetch function. */
198
699
  type FetchListFnReturnItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
199
- itemPayload: ItemPayload;
200
- data: ItemState;
700
+ /** Item payload used to key and refetch the returned item. */itemPayload: ItemPayload; /** Item data returned by the server. */
701
+ data: ItemState;
201
702
  };
703
+ /** Return shape for list query fetch functions. */
202
704
  type FetchListFnReturn<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
203
- items: FetchListFnReturnItem<ItemPayload, ItemState>[];
204
- hasMore: boolean;
705
+ /** Items included in the fetched page. */items: FetchListFnReturnItem<ItemPayload, ItemState>[]; /** Whether the query has another page available. */
706
+ hasMore: boolean;
205
707
  };
206
- type ListQueryStoreInitialData<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
207
- items: {
208
- payload: ItemPayload;
209
- data: ItemState;
210
- }[];
211
- queries: {
212
- payload: QueryPayload;
213
- items: string[];
214
- hasMore: boolean;
215
- }[];
708
+ /** Item descriptor accepted by `ListQueryStore.useMultipleItems(...)`. */
709
+ type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
710
+ /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload;
711
+ /**
712
+ * Partial-resource fields to request for this item.
713
+ *
714
+ * Pass `'*'` to fetch the complete item. This option is required when
715
+ * `partialResources` is enabled and optional otherwise.
716
+ */
717
+ fields?: FieldsInput; /** Metadata returned with this item result for caller-side bookkeeping. */
718
+ queryMetadata?: QueryMetadata;
719
+ /**
720
+ * Only fetches when the item is missing from state, skipping stale-state and
721
+ * invalidation refetches.
722
+ */
723
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
724
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the item has not been fetched. */
725
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
726
+ returnRefetchingStatus?: boolean;
727
+ /**
728
+ * When requested fields are missing but cached partial data exists, return
729
+ * `refetching` instead of `loading`.
730
+ */
731
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
732
+ isOffScreen?: boolean;
733
+ };
734
+ /** Query descriptor accepted by `ListQueryStore.useMultipleListQueries(...)`. */
735
+ type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
736
+ /** Query payload to subscribe to and fetch when needed. */payload: QueryPayload;
737
+ /**
738
+ * Partial-resource fields to request for each item in this query.
739
+ *
740
+ * Pass `'*'` to fetch complete items. This option is required when
741
+ * `partialResources` is enabled and optional otherwise.
742
+ */
743
+ fields?: FieldsInput; /** Metadata returned with this query result for caller-side bookkeeping. */
744
+ queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
745
+ omitPayload?: boolean;
746
+ /**
747
+ * Only fetches when the query is missing from state, skipping stale-state and
748
+ * invalidation refetches.
749
+ */
750
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
751
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the query has not been fetched. */
752
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
753
+ returnRefetchingStatus?: boolean;
754
+ /**
755
+ * When requested fields are missing but cached partial data exists, return
756
+ * `refetching` instead of `loading`.
757
+ */
758
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
759
+ isOffScreen?: boolean; /** Number of items to request when fetching this query page. */
760
+ loadSize?: number;
216
761
  };
762
+ /** Callback invoked when an already-loaded list query is invalidated. */
217
763
  type OnListQueryInvalidate<QueryPayload extends ValidPayload> = (query: QueryPayload, priority: FetchType) => void;
764
+ /** Callback invoked when an already-loaded list-query item is invalidated. */
218
765
  type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
219
- itemState: ItemState;
220
- payload: ItemPayload;
221
- priority: FetchType;
766
+ /** Current cached item state at invalidation time. */itemState: ItemState; /** Payload of the invalidated item. */
767
+ payload: ItemPayload; /** Fetch priority requested for the invalidation. */
768
+ priority: FetchType;
222
769
  }) => void;
223
- type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown>> = {
224
- payload: ItemPayload;
225
- queryMetadata?: QueryMetadata;
226
- disableRefetchOnMount?: boolean;
227
- returnIdleStatus?: boolean;
228
- returnRefetchingStatus?: boolean;
229
- isOffScreen?: boolean;
770
+ /** Rule for keeping cached list query membership in sync after item updates. */
771
+ type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
772
+ /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
773
+ filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
774
+ appendNewTo?: 'start' | 'end'; /** Whether affected queries should still refetch after the optimistic list update. */
775
+ invalidateQueries?: boolean; /** Sort order to maintain inside affected query pages. */
776
+ sort?: {
777
+ /** Selects sortable values from an item. */sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[]; /** Sort direction for each `sortBy` value. */
778
+ order?: 'asc' | 'desc' | ('asc' | 'desc')[];
779
+ };
230
780
  };
231
- type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown>> = {
232
- payload: QueryPayload;
233
- queryMetadata?: QueryMetadata;
234
- omitPayload?: boolean;
235
- disableRefetchOnMount?: boolean;
236
- returnIdleStatus?: boolean;
237
- returnRefetchingStatus?: boolean;
238
- isOffScreen?: boolean;
239
- loadSize?: number;
240
- };
241
- declare function newTSDFListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload>({ debugName, fetchListFn, fetchItemFn, errorNormalizer, defaultQuerySize, getInitialData, disableRefetchOnMount: globalDisableRefetchOnMount, lowPriorityThrottleMs, disableInitialDataInvalidation, mediumPriorityThrottleMs, dynamicRealtimeThrottleMs, optimisticListUpdates, onInvalidateItem, onInvalidateQuery, }: {
242
- debugName?: string;
243
- fetchListFn: (payload: QueryPayload, size: number) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
244
- fetchItemFn?: (itemId: ItemPayload) => Promise<ItemState>;
245
- errorNormalizer: (exception: unknown) => NError;
246
- defaultQuerySize?: number;
247
- getInitialData?: () => ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload> | undefined;
248
- disableInitialDataInvalidation?: boolean;
249
- disableRefetchOnMount?: boolean;
250
- lowPriorityThrottleMs?: number;
251
- mediumPriorityThrottleMs?: number;
252
- dynamicRealtimeThrottleMs?: (lastFetchDuration: number) => number;
253
- optimisticListUpdates?: {
254
- queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[];
255
- filterItem?: (item: ItemState) => boolean | null;
256
- /** @default 'end' */
257
- appendNewTo?: 'start' | 'end';
258
- invalidateQueries?: boolean;
259
- sort?: {
260
- sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[];
261
- /** @default 'asc' */
262
- order?: 'asc' | 'desc' | ('asc' | 'desc')[];
263
- };
264
- }[];
265
- onInvalidateQuery?: OnListQueryInvalidate<QueryPayload>;
266
- onInvalidateItem?: OnListQueryItemInvalidate<ItemState, ItemPayload>;
267
- }): {
268
- store: Store<TSFDListQueryState<ItemState, NError, QueryPayload, ItemPayload>>;
269
- reset: () => void;
270
- scheduleListQueryFetch: {
271
- (fetchType: FetchType, payload: QueryPayload, size?: number): ScheduleFetchResults;
272
- (fetchType: FetchType, payload: QueryPayload[], size?: number): ScheduleFetchResults[];
273
- };
274
- getQueryState: (params: QueryPayload) => TSFDListQuery<NError, QueryPayload> | undefined;
275
- getQueryKey: (params: QueryPayload) => string;
276
- deleteItemState: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[]) => void;
277
- getItemState: {
278
- (itemPayload: ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[]): {
279
- payload: ItemPayload;
280
- data: ItemState;
281
- }[];
282
- (itemPayload: ItemPayload): ItemState | null | undefined;
283
- };
284
- loadMore: (params: QueryPayload, size?: number) => ScheduleFetchResults;
285
- invalidateQueryAndItems: ({ itemPayload, queryPayload, type: priority, }: {
286
- itemPayload: false | ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[];
287
- queryPayload: false | QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean);
288
- type?: FetchType | undefined;
289
- }) => void;
290
- scheduleItemFetch: {
291
- (fetchType: FetchType, itemPayload: ItemPayload): ScheduleFetchResults;
292
- (fetchType: FetchType, itemPayload: ItemPayload[]): ScheduleFetchResults[];
293
- };
294
- awaitItemFetch: (itemPayload: ItemPayload) => Promise<{
295
- data: null;
296
- error: NError;
297
- } | {
298
- data: ItemState;
299
- error: null;
300
- }>;
301
- awaitListQueryFetch: (params: QueryPayload, size?: number) => Promise<{
302
- items: [
303
- ];
304
- error: NError;
305
- hasMore: boolean;
306
- } | {
307
- items: {
308
- data: ItemState;
309
- itemPayload: ItemPayload;
310
- }[];
311
- error: null;
312
- hasMore: boolean;
313
- }>;
314
- useMultipleListQueries: <SelectedItem = ItemState, QueryMetadata extends Record<string, unknown> | undefined = undefined>(queries: ListQueryUseMultipleListQueriesQuery<QueryPayload, QueryMetadata>[], { itemSelector, selectorUsesExternalDeps, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, omitPayload: allItemsOmitPayload, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, loadSize: allItemsLoadSize, }?: {
315
- itemSelector?: (data: ItemState, id: ItemPayload, itemKey: string) => SelectedItem;
316
- selectorUsesExternalDeps?: boolean;
317
- returnIdleStatus?: boolean;
318
- returnRefetchingStatus?: boolean;
319
- omitPayload?: boolean;
320
- disableRefetchOnMount?: boolean;
321
- isOffScreen?: boolean;
322
- loadSize?: number;
323
- }) => readonly TSFDUseListQueryReturn<SelectedItem, QueryPayload, NError, QueryMetadata>[];
324
- useListQuery: <SelectedItem_1 = ItemState>(payload: QueryPayload | false | null | undefined, { isOffScreen, itemSelector, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, loadSize, omitPayload, ensureIsLoaded, selectorUsesExternalDeps, }?: {
325
- itemSelector?: ((data: ItemState, id: ItemPayload, itemKey: string) => SelectedItem_1) | undefined;
326
- omitPayload?: boolean | undefined;
327
- disableRefetchOnMount?: boolean | undefined;
328
- returnIdleStatus?: boolean | undefined;
329
- returnRefetchingStatus?: boolean | undefined;
330
- ensureIsLoaded?: boolean | undefined;
331
- loadSize?: number | undefined;
332
- isOffScreen?: boolean | undefined;
333
- selectorUsesExternalDeps?: boolean | undefined;
334
- }) => TSFDUseListQueryReturn<SelectedItem_1, QueryPayload, NError, undefined>;
335
- getItemKey: (params: ItemPayload) => string;
336
- useItem: <SelectedItem_2 = ItemState | null>(itemPayload: ItemPayload | false | null | undefined, { selector, selectorUsesExternalDeps, disableRefetchOnMount, returnIdleStatus, returnRefetchingStatus, ensureIsLoaded, loadFromStateOnly, isOffScreen, }?: {
337
- selector?: ((data: ItemState | null, id: ItemPayload | null) => SelectedItem_2) | undefined;
338
- selectorUsesExternalDeps?: boolean | undefined;
339
- disableRefetchOnMount?: boolean | undefined;
340
- returnIdleStatus?: boolean | undefined;
341
- returnRefetchingStatus?: boolean | undefined;
342
- ensureIsLoaded?: boolean | undefined;
343
- loadFromStateOnly?: boolean | undefined;
344
- isOffScreen?: boolean | undefined;
345
- }) => TSFDUseListItemReturn<SelectedItem_2, NError, ItemPayload, undefined>;
346
- useMultipleItems: <SelectedItem_3 = ItemState | null, QueryMetadata_1 extends Record<string, unknown> | undefined = undefined>(items: ListQueryUseMultipleItemsQuery<ItemPayload, QueryMetadata_1>[], { selector, loadFromStateOnly, selectorUsesExternalDeps, returnIdleStatus: allItemsReturnIdleStatus, returnRefetchingStatus: allItemsReturnRefetchingStatus, disableRefetchOnMount: allItemsDisableRefetchOnMount, isOffScreen: allItemsIsOffScreen, }?: {
347
- loadFromStateOnly?: boolean | undefined;
348
- selector?: ((data: ItemState | null, id: ItemPayload | null) => SelectedItem_3) | undefined;
349
- selectorUsesExternalDeps?: boolean | undefined;
350
- returnIdleStatus?: boolean | undefined;
351
- returnRefetchingStatus?: boolean | undefined;
352
- disableRefetchOnMount?: boolean | undefined;
353
- isOffScreen?: boolean | undefined;
354
- }) => readonly TSFDUseListItemReturn<SelectedItem_3, NError, ItemPayload, QueryMetadata_1>[];
355
- addItemToState: (itemPayload: ItemPayload, data: ItemState, { addItemToQueries, }?: {
356
- addItemToQueries?: {
357
- queries: QueryPayload | QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean);
358
- appendTo: 'start' | 'end' | ((itemsPayload: ItemPayload[]) => number);
359
- } | undefined;
360
- }) => void;
361
- updateItemState: (itemIds: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[], produceNewData: (draftData: ItemState, itemPayload: ItemPayload) => void | ItemState, { ifNothingWasUpdated, }?: {
362
- ifNothingWasUpdated?: () => void;
363
- }) => boolean;
364
- startItemMutation: (itemId: ItemPayload | ((ItemPayload: ItemPayload, itemState: ItemState) => boolean) | ItemPayload[]) => () => void;
365
- getQueriesState: (params: QueryPayload[] | ((params: QueryPayload, data: TSFDListQuery<NError, QueryPayload>, queryKey: string) => boolean)) => {
366
- query: TSFDListQuery<NError, QueryPayload>;
367
- key: string;
368
- }[];
369
- getQueriesRelatedToItem: (itemPayload: ItemPayload) => {
370
- query: TSFDListQuery<NError, QueryPayload>;
371
- key: string;
372
- }[];
373
- useFindItem: <SelectedItem_4 = ItemState | null>(findItem: (item: ItemState, itemPayload: ItemPayload) => boolean, { selector, }?: {
374
- selector?: ((data: ItemState, id: ItemPayload) => SelectedItem_4) | undefined;
375
- }) => Readonly<SelectedItem_4 | null>;
781
+ /** Payload passed to list fetch functions. */
782
+ type QueryFetchPayload<QueryPayload extends ValidPayload> = {
783
+ /** Whether this request loads the first page or a later page. */type: 'load' | 'loadMore'; /** Query payload being fetched. */
784
+ payload: QueryPayload; /** Offset used for offset-paginated fetches. */
785
+ offset: number; /** Maximum number of items requested. */
786
+ limit: number; /** Partial-resource fields requested for each item in the fetched query. */
787
+ fields?: string[];
376
788
  };
377
- type TSFDListQueryStore<ItemState extends ValidStoreState, NError, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = ReturnType<typeof newTSDFListQueryStore<ItemState, NError, QueryPayload, ItemPayload>>;
378
-
379
- /** Use to detect if a item of a list may be loading in cases which there is no
380
- * clear indication of the status of individual items, ex: an item in a document collection that is loaded on demand */
381
- declare function useListItemIsLoading({ listIsLoading, isRefetching, itemExists, loadItemFallback, itemId, }: {
382
- itemId: string | null | false;
383
- isRefetching: boolean;
384
- listIsLoading: boolean;
385
- /** true if item exists in any condition, ex: if list is not loaded item not exists in memory yet */
386
- itemExists: boolean;
387
- loadItemFallback: () => void;
388
- }): boolean;
389
-
390
- declare function getCacheId(input: unknown, maxDepth?: number): string;
391
-
392
- declare function useListItemIsDeleted({ itemExists, listIsLoading, onDelete, itemId, }: {
393
- itemId: string;
394
- /** true if item exists in any condition, ex: if list is not loaded item not exists in memory yet */
395
- itemExists: boolean;
396
- listIsLoading: boolean;
397
- onDelete?: () => void;
398
- }): boolean;
789
+ /** Options for offset-based list pagination. */
790
+ type OffsetPaginationConfig = {
791
+ /** Largest item count requested when refetching invalidated offset queries. */maxInvalidationLimit: number; /** Max parallel chunk requests during chunked invalidation (default: 3) */
792
+ maxParallel?: number;
793
+ };
794
+ /** Partial-resource helpers used to merge and select field subsets. */
795
+ type PartialResourcesConfig<ItemState extends ValidStoreState> = {
796
+ /** Merges a partial fetch result into an existing item snapshot. */mergeItems: (prev: ItemState | undefined, fetched: ItemState) => ItemState; /** Returns an item containing only the requested fields. */
797
+ selectFields: (fields: string[], item: ItemState) => ItemState;
798
+ };
799
+ type DerivedQuerySummary<QueryPayload extends ValidPayload> = {
800
+ payload: QueryPayload;
801
+ hasMore: boolean;
802
+ itemCount: number;
803
+ };
804
+ type DerivedQueryItem<ItemState extends ValidStoreState> = {
805
+ key: string;
806
+ data: ItemState;
807
+ };
808
+ /** Why a derived query is currently being resolved. */
809
+ type DerivedQuerySource = 'online' | 'offline' | 'sticky-offline';
810
+ /** Runtime context passed to `derivedQueries.deriveQuery(...)`. */
811
+ type DerivedQueryContext = {
812
+ /** The requested hook fields for this query, when partial resources are enabled. */fields: FieldsInput | undefined; /** Whether the store is currently in offline mode. */
813
+ isOfflineMode: boolean;
814
+ /**
815
+ * What caused derivation to run.
816
+ * `sticky-offline` means a query that was derived offline is still sticking
817
+ * to the local derived view after reconnect, until explicit invalidation.
818
+ */
819
+ deriveSource: DerivedQuerySource;
820
+ };
821
+ /** Configuration for deriving query membership from locally materialized items. */
822
+ type DerivedQueriesConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
823
+ /** Extracts the domain/group key for a query payload. */getQueryGroup: (queryPayload: QueryPayload) => string; /** Extracts the domain/group key for a materialized item. */
824
+ getItemGroup: (item: ItemState, itemPayload: ItemPayload) => string;
825
+ /**
826
+ * Returns whether the local data for the query group is complete enough to
827
+ * derive from while online.
828
+ */
829
+ isComplete: (queryPayload: QueryPayload, context: {
830
+ queries: DerivedQuerySummary<QueryPayload>[];
831
+ }) => boolean;
832
+ /**
833
+ * Computes a derived ordered list of item keys for a query, or `false` to
834
+ * fall back to the regular fetch/cache path. `context.fields` lets the
835
+ * callback decide whether partial-resource queries should still derive.
836
+ */
837
+ deriveQuery: (queryPayload: QueryPayload, items: DerivedQueryItem<ItemState>[], context: DerivedQueryContext) => string[] | false;
838
+ };
839
+ /** Field option shape used by APIs that are conditional on `partialResources`. */
840
+ type FieldsOption<HasPartialResources extends boolean> = HasPartialResources extends true ? {
841
+ /**
842
+ * Partial-resource fields to request.
843
+ *
844
+ * Pass `'*'` to fetch complete items. This option is required when
845
+ * `partialResources` is enabled.
846
+ */
847
+ fields: FieldsInput;
848
+ } : {
849
+ /**
850
+ * Partial-resource fields to request.
851
+ *
852
+ * Pass `'*'` to fetch complete items. This option is optional when
853
+ * `partialResources` is not enabled.
854
+ */
855
+ fields?: FieldsInput;
856
+ };
857
+ //#endregion
858
+ //#region src/listQueryStore/useMultipleItems.d.ts
859
+ type UseMultipleItemsOptions<ItemState extends ValidStoreState, Selected> = {
860
+ /** Maps each item before it is returned from the hook. */selector?: (data: ItemState | null, payload: ValidPayload | null) => Selected; /** Reads only from the current store state and never schedules fetches. */
861
+ loadFromStateOnly?: boolean; /** Returns `idle` instead of `loading` while items have not been fetched. */
862
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
863
+ returnRefetchingStatus?: boolean;
864
+ /**
865
+ * When requested fields are missing but cached partial data exists, return
866
+ * `refetching` instead of `loading`.
867
+ */
868
+ showPartialAsRefetching?: boolean;
869
+ /**
870
+ * Only fetches when an item is missing from state, skipping stale-state and
871
+ * invalidation refetches.
872
+ */
873
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
874
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
875
+ isOffScreen?: boolean;
876
+ /**
877
+ * Debounces automatic fetches caused by payload changes, while selection
878
+ * still reads from the latest payload. Supports trailing debounce via `ms`,
879
+ * optional `leading`, and optional `maxWait`.
880
+ */
881
+ debouncePayload?: PayloadDebounce;
882
+ };
883
+ //#endregion
884
+ //#region src/listQueryStore/useItem.d.ts
885
+ type UseItemOptions<ItemState extends ValidStoreState, Selected> = UseMultipleItemsOptions<ItemState, Selected> & {
886
+ /**
887
+ * Forces a high-priority fetch on mount and keeps the hook in `loading`
888
+ * until the current payload finishes loading. Cannot be combined with
889
+ * `debouncePayload`.
890
+ */
891
+ ensureIsLoaded?: boolean;
892
+ /**
893
+ * Partial-resource fields to request for this item.
894
+ *
895
+ * Pass `'*'` to fetch the complete item. This option is required when
896
+ * `partialResources` is enabled and optional otherwise.
897
+ */
898
+ fields?: FieldsInput;
899
+ /**
900
+ * When requested fields are missing but cached partial data exists, return
901
+ * `refetching` instead of `loading`.
902
+ */
903
+ showPartialAsRefetching?: boolean;
904
+ };
905
+ //#endregion
906
+ //#region src/listQueryStore/useMultipleListQueries.d.ts
907
+ type UseMultipleListQueriesOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, SelectedItem> = {
908
+ /** Maps each query item before it is returned from the hook. */itemSelector?: (data: ItemState, itemPayload: ItemPayload, itemKey: string) => SelectedItem; /** Returns `idle` instead of `loading` while queries have not been fetched. */
909
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
910
+ returnRefetchingStatus?: boolean;
911
+ /**
912
+ * When requested fields are missing but cached partial data exists, return
913
+ * `refetching` instead of `loading`.
914
+ */
915
+ showPartialAsRefetching?: boolean; /** Omits `payload` from each query result unless overridden per query. */
916
+ omitPayload?: boolean;
917
+ /**
918
+ * Only fetches when a query is missing from state, skipping stale-state and
919
+ * invalidation refetches.
920
+ */
921
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
922
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
923
+ isOffScreen?: boolean; /** Number of items to request when fetching each query page. */
924
+ loadSize?: number;
925
+ /**
926
+ * Debounces automatic fetches caused by payload changes, while selection
927
+ * still reads from the latest payload. Supports trailing debounce via `ms`,
928
+ * optional `leading`, and optional `maxWait`.
929
+ */
930
+ debouncePayload?: PayloadDebounce;
931
+ };
932
+ //#endregion
933
+ //#region src/listQueryStore/useListQuery.d.ts
934
+ type UseListQueryOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, SelectedItem> = UseMultipleListQueriesOptions<ItemState, ItemPayload, SelectedItem> & {
935
+ /**
936
+ * Forces a high-priority fetch on mount and keeps the hook in `loading`
937
+ * until the current payload finishes loading. Cannot be combined with
938
+ * `debouncePayload`.
939
+ */
940
+ ensureIsLoaded?: boolean;
941
+ /**
942
+ * Partial-resource fields to request for each item in this query.
943
+ *
944
+ * Pass `'*'` to fetch complete items. This option is required when
945
+ * `partialResources` is enabled and optional otherwise.
946
+ */
947
+ fields?: FieldsInput;
948
+ /**
949
+ * When requested fields are missing but cached partial data exists, return
950
+ * `refetching` instead of `loading`.
951
+ */
952
+ showPartialAsRefetching?: boolean;
953
+ };
954
+ //#endregion
955
+ //#region src/listQueryStore/usePendingOfflineItems.d.ts
956
+ type UsePendingOfflineItemsOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, SelectedItem> = {
957
+ /** Maps each visible pending item before it is returned from the hook. */selector?: (data: ItemState, payload: ItemPayload) => SelectedItem; /** Narrows the hook output using the tracked item payload, before selection. */
958
+ filterPayload?: (payload: ItemPayload) => boolean; /** Includes entities currently blocked in manual resolution. */
959
+ includeResolutionRequired?: boolean;
960
+ };
961
+ //#endregion
962
+ //#region src/listQueryStore/listQueryStore.d.ts
963
+ /** Event payloads emitted by `ListQueryStore.events`. */
964
+ type ListQueryStoreEvents = {
965
+ /** Emitted whenever one or more list queries are invalidated. */invalidateQuery: {
966
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated query. */
967
+ queryKey: string;
968
+ }; /** Emitted whenever one or more list-query items are invalidated. */
969
+ invalidateItem: {
970
+ /** Fetch priority requested by the invalidation. */priority: FetchType; /** Store key for the invalidated item. */
971
+ itemKey: string; /** Partial-resource fields invalidated on this item, when applicable. */
972
+ invalidateFields?: string[];
973
+ };
974
+ };
975
+ type ListQueryStoreStoreEvents<ItemPayload extends ValidPayload> = {
976
+ mutationStart: {
977
+ mutationId: number;
978
+ items: ItemPayload[];
979
+ };
980
+ mutationEnd: {
981
+ mutationId: number;
982
+ items: ItemPayload[];
983
+ status: 'success' | 'error' | 'skipped';
984
+ };
985
+ tempEntityReconciled: {
986
+ tempId: ItemPayload;
987
+ finalPayload: ItemPayload;
988
+ };
989
+ };
990
+ type ResolvedListQueryOfflineOperations<TOfflineOperations> = TOfflineOperations extends null ? Record<never, never> : Exclude<TOfflineOperations, null>;
991
+ type ListQueryHasPartialResources<TPartialResources extends boolean> = [TPartialResources] extends [true] ? true : false;
992
+ type ListQueryFetchFieldsOption<TPartialResources extends boolean> = ListQueryHasPartialResources<TPartialResources> extends true ? {
993
+ /**
994
+ * Partial-resource fields to request.
995
+ *
996
+ * Pass `'*'` to fetch complete items. This option is required when
997
+ * `partialResources` is enabled.
998
+ */
999
+ fields: FieldsInput;
1000
+ } : {
1001
+ /**
1002
+ * Partial-resource fields to request.
1003
+ *
1004
+ * Pass `'*'` to fetch complete items. This option is optional when
1005
+ * `partialResources` is not enabled.
1006
+ */
1007
+ fields?: FieldsInput;
1008
+ };
1009
+ type ListQueryScheduleFetchWithFieldsOption<TPartialResources extends boolean> = ScheduleFetchOptions & ListQueryFetchFieldsOption<TPartialResources>;
1010
+ type ListQueryScheduleListQueryFetchApi<QueryPayload extends ValidPayload, TPartialResources extends boolean> = {
1011
+ (fetchType: FetchType, payload: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults;
1012
+ (fetchType: FetchType, payload: QueryPayload[], ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size: number | undefined, options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [/** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults[];
1013
+ };
1014
+ type ListQueryScheduleItemFetchApi<ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
1015
+ (fetchType: FetchType, itemPayload: ItemPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults;
1016
+ (fetchType: FetchType, itemPayload: ItemPayload[], ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryScheduleFetchWithFieldsOption<TPartialResources>] : [options?: ListQueryScheduleFetchWithFieldsOption<TPartialResources>]): ScheduleFetchResults[];
1017
+ };
1018
+ type ListQueryLoadMoreWithFieldsOptions<TPartialResources extends boolean> = {
1019
+ /** Number of additional items to request. Defaults to the store's `defaultQuerySize`. */size?: number;
1020
+ } & ListQueryFetchFieldsOption<TPartialResources>;
1021
+ type ListQueryLoadMoreApi<QueryPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [size: number, options: ListQueryFetchFieldsOption<TPartialResources>] | [options: ListQueryLoadMoreWithFieldsOptions<TPartialResources>] : [/** Number of additional items to request. Defaults to the store's `defaultQuerySize`. */size?: number, options?: ListQueryFetchFieldsOption<TPartialResources>] | [options?: ListQueryLoadMoreWithFieldsOptions<TPartialResources>]) => ScheduleFetchResults;
1022
+ type ListQueryAwaitListQueryFetchOptions<TPartialResources extends boolean> = {
1023
+ /** Number of items to request. Defaults to the store's `defaultQuerySize`. */size?: number;
1024
+ timeoutMs?: number;
1025
+ } & ListQueryFetchFieldsOption<TPartialResources>;
1026
+ type ListQueryAwaitListQueryFetchApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryAwaitListQueryFetchOptions<TPartialResources>] : [options?: ListQueryAwaitListQueryFetchOptions<TPartialResources>]) => Promise<{
1027
+ items: [];
1028
+ error: StoreFetchError;
1029
+ hasMore: boolean;
1030
+ } | {
1031
+ items: {
1032
+ data: ItemState;
1033
+ itemPayload: ItemPayload;
1034
+ }[];
1035
+ error: null;
1036
+ hasMore: boolean;
1037
+ }>;
1038
+ type ListQueryGetQueryFromStateOrFetchOptions<TPartialResources extends boolean> = {
1039
+ /** When `true`, stale cached queries are ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean; /** Number of items to request when a fetch is needed. Defaults to the store's `defaultQuerySize`. */
1040
+ size?: number;
1041
+ timeoutMs?: number;
1042
+ } & ListQueryFetchFieldsOption<TPartialResources>;
1043
+ type ListQueryGetQueryFromStateOrFetchApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (params: QueryPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryGetQueryFromStateOrFetchOptions<TPartialResources>] : [options?: ListQueryGetQueryFromStateOrFetchOptions<TPartialResources>]) => Promise<Result<{
1044
+ items: {
1045
+ data: ItemState;
1046
+ itemPayload: ItemPayload;
1047
+ }[];
1048
+ hasMore: boolean;
1049
+ }, StoreFetchError>>;
1050
+ type ListQueryAwaitItemFetchOptions<TPartialResources extends boolean> = {
1051
+ timeoutMs?: number;
1052
+ } & ListQueryFetchFieldsOption<TPartialResources>;
1053
+ type ListQueryAwaitItemFetchApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (itemPayload: ItemPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryAwaitItemFetchOptions<TPartialResources>] : [options?: ListQueryAwaitItemFetchOptions<TPartialResources>]) => Promise<{
1054
+ data: null;
1055
+ error: StoreFetchError;
1056
+ } | {
1057
+ data: ItemState;
1058
+ error: null;
1059
+ }>;
1060
+ type ListQueryGetItemFromStateOrFetchOptions<TPartialResources extends boolean> = {
1061
+ /** When `true`, stale cached items are ignored and refetched before returning. Defaults to `false`. */ignoreStaleState?: boolean;
1062
+ timeoutMs?: number;
1063
+ } & ListQueryFetchFieldsOption<TPartialResources>;
1064
+ type ListQueryGetItemFromStateOrFetchApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = (itemPayload: ItemPayload, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: ListQueryGetItemFromStateOrFetchOptions<TPartialResources>] : [options?: ListQueryGetItemFromStateOrFetchOptions<TPartialResources>]) => Promise<Result<ItemState, StoreFetchError>>;
1065
+ type ListQueryUseMultipleListQueriesApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
1066
+ <SelectedItem = ItemState, QueryMetadata extends undefined | Record<string, unknown> = undefined>(queries: (ListQueryUseMultipleListQueriesQuery<QueryPayload, QueryMetadata> & FieldsOption<ListQueryHasPartialResources<TPartialResources>>)[], options?: UseMultipleListQueriesOptions<ItemState, ItemPayload, SelectedItem>): readonly TSFDUseListQueryReturn<SelectedItem, QueryPayload, QueryMetadata>[];
1067
+ <S = ItemState>(queries: ListQueryUseMultipleListQueriesQuery<QueryPayload, undefined>[], options: UseMultipleListQueriesOptions<ItemState, ItemPayload, S>): readonly TSFDUseListQueryReturn<S, QueryPayload, undefined>[];
1068
+ };
1069
+ type ListQueryUseListQueryApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
1070
+ <SelectedItem = ItemState>(payload: QueryPayload | false | null | undefined, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: UseListQueryOptions<ItemState, ItemPayload, SelectedItem> & FieldsOption<true>] : [options?: UseListQueryOptions<ItemState, ItemPayload, SelectedItem>]): TSFDUseListQueryReturn<SelectedItem, QueryPayload, undefined>;
1071
+ };
1072
+ type ListQueryUseMultipleItemsApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
1073
+ <Selected = ItemState | null, QueryMetadata extends undefined | Record<string, unknown> = undefined>(items: (ListQueryUseMultipleItemsQuery<ItemPayload, QueryMetadata> & FieldsOption<ListQueryHasPartialResources<TPartialResources>>)[], options?: UseMultipleItemsOptions<ItemState, Selected>): readonly TSFDUseListItemReturn<Selected, ItemPayload, QueryMetadata>[];
1074
+ <S = ItemState | null>(items: ListQueryUseMultipleItemsQuery<ItemPayload, undefined>[], options: UseMultipleItemsOptions<ItemState, S>): readonly TSFDUseListItemReturn<S, ItemPayload, undefined>[];
1075
+ };
1076
+ type ListQueryUseItemApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
1077
+ <Selected = ItemState | null>(itemPayload: ItemPayload | false | null | undefined, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: UseItemOptions<ItemState, Selected> & FieldsOption<true>] : [options?: UseItemOptions<ItemState, Selected>]): TSFDUseListItemReturn<Selected, ItemPayload>;
1078
+ };
1079
+ type ListQueryUsePendingOfflineItemsApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
1080
+ <SelectedItem = ItemState>(options?: UsePendingOfflineItemsOptions<ItemState, ItemPayload, SelectedItem>): TSFDUsePendingOfflineItemsReturn<SelectedItem, ItemPayload>;
1081
+ };
1082
+ type ListQueryFilterQuery<QueryPayload extends ValidPayload> = (params: QueryPayload, data: TSFDListQuery<QueryPayload>, queryKey: string) => boolean;
1083
+ type ListQueryRevalidateOnSuccessOption<QueryPayload extends ValidPayload> = boolean | 'queries' | ListQueryFilterQuery<QueryPayload> | {
1084
+ queries: ListQueryFilterQuery<QueryPayload>;
1085
+ items?: boolean;
1086
+ };
1087
+ type ListQueryFilterItem<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemPayload: ItemPayload, itemState: ItemState) => boolean;
1088
+ type ListQueryMutationPayload<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload> | null;
1089
+ type ListQueryMutationPayloadToUse<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>;
1090
+ type ListQueryMutationArgsBase<T, ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
1091
+ /**
1092
+ * Applies optimistic updates for the affected item payloads before the
1093
+ * mutation runs. Return `false` to cancel the mutation before the async
1094
+ * mutation function is called.
1095
+ */
1096
+ optimisticUpdate?: (payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void | boolean; /** Performs the server mutation for the affected item payloads. */
1097
+ mutation: (payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => Promise<T>;
1098
+ /**
1099
+ * Controls query and item invalidation after a successful online mutation.
1100
+ *
1101
+ * Use `true` to invalidate affected items and all queries, `'queries'` to
1102
+ * invalidate only queries, a query filter to invalidate affected items and
1103
+ * matching queries, or `{ queries, items }` to choose both explicitly.
1104
+ */
1105
+ revalidateOnSuccess?: ListQueryRevalidateOnSuccessOption<QueryPayload>; /** Called after a successful online mutation. */
1106
+ onSuccess?: (response: UnwrapTSDFResult<Awaited<T>>, payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>) => void; /** Called after a failed or skipped mutation. */
1107
+ onError?: (error: StoreMutationError | MutationSkipped) => void;
1108
+ /**
1109
+ * Passes `{ silentErrors: true }` to `onMutationError`.
1110
+ *
1111
+ * The handler is still called so centralized logging and recovery can run,
1112
+ * but UI handlers can suppress user-facing notifications.
1113
+ */
1114
+ silentErrors?: boolean; /** Debounces mutations with the same context and payload. Superseded calls are skipped. */
1115
+ debounce?: {
1116
+ context: string;
1117
+ payload: unknown;
1118
+ ms: number;
1119
+ };
1120
+ };
1121
+ type ListQueryOnlineMutationArgs<T, ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = ListQueryMutationArgsBase<T, ItemState, QueryPayload, ItemPayload> & {
1122
+ offline?: undefined;
1123
+ upload?: undefined;
1124
+ };
1125
+ type ListQueryOfflineMutationArgs<T, ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload>> = ListQueryMutationArgsBase<T, ItemState, QueryPayload, ItemPayload> & {
1126
+ /**
1127
+ * Queues this mutation through the store's registered offline operation when
1128
+ * the session is offline or the direct request fails with an offline outage.
1129
+ */
1130
+ offline: TOfflineOperations extends null ? never : OfflineMutationInput<Exclude<TOfflineOperations, null>>; /** Files to attach if this mutation is queued for offline replay. */
1131
+ upload?: OfflineMutationUploadsInput;
1132
+ };
1133
+ type ListQueryPerformMutationApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload>> = {
1134
+ /**
1135
+ * Runs a list-query mutation for existing item payloads or an item filter.
1136
+ *
1137
+ * Returns the direct server result when offline replay is not configured for
1138
+ * this call.
1139
+ */
1140
+ <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
1141
+ /**
1142
+ * Runs a list-query mutation for existing item payloads or an item filter,
1143
+ * with durable offline queueing as a fallback.
1144
+ *
1145
+ * When the mutation is queued, the result is `{ kind: 'queued' }` instead of
1146
+ * the server payload.
1147
+ */
1148
+ <T>(payload: ListQueryMutationPayloadToUse<ItemState, ItemPayload>, args: ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1149
+ /**
1150
+ * Runs a list-query mutation with no current item target.
1151
+ *
1152
+ * Use this for create mutations that do not have a pre-generated item payload
1153
+ * yet. Optimistic updates are not available without a target payload.
1154
+ */
1155
+ <T>(payload: null, args: Omit<ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload>, 'optimisticUpdate'>): Promise<Result<UnwrapTSDFResult<Awaited<T>>, StoreMutationError | MutationSkipped>>;
1156
+ /**
1157
+ * Runs an offline-capable list-query mutation with no current item target.
1158
+ *
1159
+ * Use this for create mutations that do not have a pre-generated item payload
1160
+ * yet. When the mutation is queued, the result is `{ kind: 'queued' }`.
1161
+ */
1162
+ <T>(payload: null, args: Omit<ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>, 'optimisticUpdate'>): Promise<Result<OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1163
+ <T>(payload: ListQueryMutationPayload<ItemState, ItemPayload>, args: ListQueryOnlineMutationArgs<T, ItemState, QueryPayload, ItemPayload> | ListQueryOfflineMutationArgs<T, ItemState, QueryPayload, ItemPayload, TOfflineOperations>): Promise<Result<UnwrapTSDFResult<Awaited<T>> | OfflineMutationResult<UnwrapTSDFResult<Awaited<T>>>, StoreMutationError | MutationSkipped>>;
1164
+ };
1165
+ type ListQueryUpdateItemStateApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemIds: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>, produceNewData: (draftData: ItemState, itemPayload: ItemPayload) => void | ItemState, options?: {
1166
+ ifNothingWasUpdated?: () => void;
1167
+ }) => boolean;
1168
+ type ListQueryAddItemToStateApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (itemPayload: ItemPayload, data: ItemState, options?: {
1169
+ addItemToQueries?: {
1170
+ queries: QueryPayload[] | ListQueryFilterQuery<QueryPayload> | QueryPayload;
1171
+ appendTo: 'start' | 'end' | ((itemsPayload: ItemPayload[]) => number);
1172
+ };
1173
+ }) => void;
1174
+ type ListQueryDeleteItemStateApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => void;
1175
+ type ListQueryInvalidateQueryAndItemsArgs<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
1176
+ /** Invalidate every cached query and every cached item. */all: true; /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
1177
+ type?: FetchType;
1178
+ /**
1179
+ * Partial-resource fields to invalidate on matching items.
1180
+ *
1181
+ * Omit to invalidate the full item data.
1182
+ */
1183
+ fields?: string[]; /** Not allowed when invalidating every query and item. */
1184
+ itemPayload?: undefined; /** Not allowed when invalidating every query and item. */
1185
+ queryPayload?: undefined;
1186
+ } | {
1187
+ /** Leave unset when invalidating selected queries or items. */all?: undefined;
1188
+ /**
1189
+ * Items to invalidate.
1190
+ *
1191
+ * Pass one payload, many payloads, a predicate over cached items, or
1192
+ * `false` to skip item invalidation.
1193
+ */
1194
+ itemPayload: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload> | false;
1195
+ /**
1196
+ * Queries to invalidate.
1197
+ *
1198
+ * Pass one payload, many payloads, a predicate over cached queries, or
1199
+ * `false` to skip query invalidation.
1200
+ */
1201
+ queryPayload: QueryPayload | QueryPayload[] | ListQueryFilterQuery<QueryPayload> | false; /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
1202
+ type?: FetchType;
1203
+ /**
1204
+ * Partial-resource fields to invalidate on matching items.
1205
+ *
1206
+ * Omit to invalidate the full item data.
1207
+ */
1208
+ fields?: string[];
1209
+ };
1210
+ /** Public API returned by `createListQueryStore(...)`. */
1211
+ type ListQueryStore<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = {
1212
+ /** Underlying t-state store containing raw cached queries and items. */store: Store<TSFDListQueryState<ItemState, QueryPayload, ItemPayload>>; /** Invalidation event emitter used by hooks and integrations. */
1213
+ events: Emitter<ListQueryStoreEvents>; /** Mutation lifecycle event emitter for observers and tests. */
1214
+ storeEvents: Emitter<ListQueryStoreStoreEvents<ItemPayload>>; /** Query keys that have been explicitly invalidated and are awaiting refresh. */
1215
+ readonly queryInvalidationWasTriggered: Set<string>; /** Item keys that have been explicitly invalidated and are awaiting refresh. */
1216
+ readonly itemInvalidationWasTriggered: Set<string>; /** Clears in-memory state and cancels store-local runtime state. */
1217
+ reset: () => void; /** Unregisters listeners and releases resources owned by this store. */
1218
+ dispose: () => void; /** Schedules a list-query fetch with the requested priority. */
1219
+ scheduleListQueryFetch: ListQueryScheduleListQueryFetchApi<QueryPayload, TPartialResources>; /** Reads one cached query directly from store state. */
1220
+ getQueryState: (params: QueryPayload) => TSFDListQuery<QueryPayload> | undefined; /** Returns the stable cache key for a query payload. */
1221
+ getQueryKey: (params: QueryPayload) => string; /** Reads many cached queries directly from store state. */
1222
+ getQueriesState: (params: QueryPayload[] | ListQueryFilterQuery<QueryPayload>) => {
1223
+ query: TSFDListQuery<QueryPayload>;
1224
+ key: string;
1225
+ }[]; /** Finds cached queries that currently include the item payload. */
1226
+ getQueriesRelatedToItem: (itemPayload: ItemPayload) => {
1227
+ query: TSFDListQuery<QueryPayload>;
1228
+ key: string;
1229
+ }[]; /** Waits for a list-query fetch to settle and returns query data or a fetch error. */
1230
+ awaitListQueryFetch: ListQueryAwaitListQueryFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** Returns a cached query when usable, otherwise fetches it first. */
1231
+ getQueryFromStateOrFetch: ListQueryGetQueryFromStateOrFetchApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** Loads query payloads from persistent storage into memory when available. */
1232
+ preloadQueryFromStorage: (params: QueryPayload | QueryPayload[]) => Promise<PersistentStoragePreloadResult<QueryPayload>[]>; /** Fetches and appends the next page for a list query. */
1233
+ loadMore: ListQueryLoadMoreApi<QueryPayload, TPartialResources>; /** Returns the stable cache key for an item payload. */
1234
+ getItemKey: (params: ItemPayload) => string; /** Reads one or many cached items directly from store state. */
1235
+ getItemState: {
1236
+ (itemPayload: ItemPayload): ItemState | null | undefined;
1237
+ (itemPayload: ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>): {
1238
+ payload: ItemPayload;
1239
+ data: ItemState;
1240
+ }[];
1241
+ }; /** React hook for locally pending offline items in this store. */
1242
+ usePendingOfflineItems: ListQueryUsePendingOfflineItemsApi<ItemState, ItemPayload>; /** Returns offline sync metadata for this store's tracked entities. */
1243
+ getOfflineEntities: () => GlobalOfflineEntity[]; /** React hook subscribing to this store's offline entity metadata. */
1244
+ useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to manual offline resolutions for this store. */
1245
+ useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns manual offline resolutions for this store. */
1246
+ getOfflineResolutions: () => OfflineResolutionRecord[]; /** Parses a stored offline conflict into the operation-specific conflict shape. */
1247
+ parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedListQueryOfflineOperations<TOfflineOperations>>; /** Applies a retry/discard/requeue/commit action to a pending offline resolution. */
1248
+ resolveOfflineResolution: <TName extends keyof ResolvedListQueryOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedListQueryOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void; /** Loads item payloads from persistent storage into memory when available. */
1249
+ preloadItemFromStorage: (params: ItemPayload | ItemPayload[]) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>; /** Schedules an item fetch with the requested priority. */
1250
+ scheduleItemFetch: ListQueryScheduleItemFetchApi<ItemPayload, TPartialResources>; /** Waits for an item fetch to settle and returns data or a fetch error. */
1251
+ awaitItemFetch: ListQueryAwaitItemFetchApi<ItemState, ItemPayload, TPartialResources>; /** Returns cached item data when usable, otherwise fetches it first. */
1252
+ getItemFromStateOrFetch: ListQueryGetItemFromStateOrFetchApi<ItemState, ItemPayload, TPartialResources>; /** Invalidates selected queries and items together. Defaults to `highPriority`. */
1253
+ invalidateQueryAndItems: (args: ListQueryInvalidateQueryAndItemsArgs<ItemState, QueryPayload, ItemPayload>) => void; /** Marks cached items stale and schedules refetches for active subscriptions. Defaults to `highPriority`. */
1254
+ invalidateItem: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>, /** Fetch priority used for refetches triggered by this invalidation. Defaults to `highPriority`. */
399
1255
 
400
- export { type CollectionInitialStateItem, type CollectionUseMultipleItemsQuery, type FetchListFnReturn, type FetchListFnReturnItem, type ListQueryStoreInitialData, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type OnCollectionItemInvalidate, type OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type TSDFCollectionStore, type TSDFDocumentStore, type TSDFDocumentStoreState, type TSDFItemQuery, type TSDFStatus, type TSDFUseDocumentReturn, type TSFDCollectionItem, type TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, type TSFDListQueryStore, type TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type ValidPayload, type ValidStoreState, getCacheId, newTSDFCollectionStore, newTSDFDocumentStore, newTSDFListQueryStore, useListItemIsDeleted, useListItemIsLoading };
1256
+ priority?: FetchType) => void; /** Marks one or more items as mutating and returns a function that ends the mutation. */
1257
+ startItemMutation: (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => () => void; /** Applies an immutable update to one or more cached list-query items. */
1258
+ updateItemState: ListQueryUpdateItemStateApi<ItemState, ItemPayload>; /** Adds or replaces one cached item directly in state. */
1259
+ addItemToState: ListQueryAddItemToStateApi<ItemState, QueryPayload, ItemPayload>; /** Deletes one cached item directly from state and query membership. */
1260
+ deleteItemState: ListQueryDeleteItemStateApi<ItemState, ItemPayload>;
1261
+ /**
1262
+ * Runs the full mutation lifecycle: optional optimistic update, async
1263
+ * mutation, rollback/error handling, revalidation, and offline queue fallback.
1264
+ */
1265
+ performMutation: ListQueryPerformMutationApi<ItemState, QueryPayload, ItemPayload, TOfflineOperations>; /** React hook for subscribing to many list queries at once. */
1266
+ useMultipleListQueries: ListQueryUseMultipleListQueriesApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** React hook for subscribing to one list query. */
1267
+ useListQuery: ListQueryUseListQueryApi<ItemState, QueryPayload, ItemPayload, TPartialResources>; /** React hook for subscribing to many list-query items at once. */
1268
+ useMultipleItems: ListQueryUseMultipleItemsApi<ItemState, ItemPayload, TPartialResources>; /** React hook for subscribing to one list-query item. */
1269
+ useItem: ListQueryUseItemApi<ItemState, ItemPayload, TPartialResources>; /** React hook for selecting the first cached item matching a predicate. */
1270
+ useFindItem: <SelectedItem = ItemState | null>(findItemFn: (item: ItemState, itemPayload: ItemPayload) => boolean, options?: {
1271
+ /** Maps the matched item before it is returned from the hook. */selector?: (data: ItemState, id: ItemPayload) => SelectedItem;
1272
+ }) => SelectedItem | null; /** Notifies the store that a shared transport reconnected and should revalidate active data. */
1273
+ onTransportReconnect: () => void;
1274
+ };
1275
+ /** Details passed when list-query cache-limit cleanup evicts cached items or queries. */
1276
+ type ListQueryStateCleanup<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
1277
+ /** Cleanup trigger that removed these records. */reason: 'cacheLimitEviction'; /** Item store keys removed from state. */
1278
+ itemKeys: string[]; /** Original item payloads removed from state. */
1279
+ itemPayloads: ItemPayload[]; /** Query store keys removed from state. */
1280
+ queryKeys: string[]; /** Original query payloads removed from state. */
1281
+ queryPayloads: QueryPayload[];
1282
+ };
1283
+ type FetchListFnSizeMode<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (payload: QueryPayload, size: number, options: {
1284
+ signal: AbortSignal;
1285
+ fields?: string[];
1286
+ }) => Promise<MaybeTSDFResult<FetchListFnReturn<ItemState, ItemPayload>>>;
1287
+ type FetchListFnOffsetMode<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (payload: QueryPayload, pagination: {
1288
+ offset: number;
1289
+ limit: number;
1290
+ }, options: {
1291
+ signal: AbortSignal;
1292
+ fields?: string[];
1293
+ }) => Promise<MaybeTSDFResult<FetchListFnReturn<ItemState, ItemPayload>>>;
1294
+ type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown> = {
1295
+ /**
1296
+ * Stable id for this logical list-query store. Used for debug labels,
1297
+ * persistence namespaces, and browser tab sync.
1298
+ */
1299
+ id: string; /** Shared global store manager providing session scoping and error normalization. */
1300
+ storeManager: StoreManager; /** Fetches one item by payload. Required when items can be loaded outside list pages. */
1301
+ fetchItemFn?: (payload: ItemPayload, options: {
1302
+ signal: AbortSignal;
1303
+ fields?: string[];
1304
+ }) => Promise<MaybeTSDFResult<ItemState>>; /** Optional batch fetch function for fetching multiple items at once. */
1305
+ batchFetchItemFn?: (requests: {
1306
+ payload: ItemPayload;
1307
+ fields?: string[];
1308
+ }[], options: {
1309
+ signal: AbortSignal;
1310
+ batchKey: string;
1311
+ }) => Promise<MaybeTSDFResult<Map<ItemPayload, MaybeTSDFResult<ItemState> | Error>>>; /** Optional function to group item batch fetches by key. When omitted, all batched items share one default batch key. Return false to fetch individually. */
1312
+ getItemsBatchKey?: (payload: ItemPayload) => string | false; /** Default number of items requested by list-query fetches. Defaults to 50. */
1313
+ defaultQuerySize?: number; /** Max items per item batch. Defaults to 50. Triggers an immediate fetch when reached. */
1314
+ maxItemBatchSize?: number; /** Maximum number of cached items kept in memory. Defaults to 5,000. Item pressure may evict whole inactive queries to avoid leaving cached queries partially loaded. */
1315
+ maxItems?: number; /** Maximum number of cached queries kept in memory. Defaults to 1,000. Inactive queries are evicted in LRU order while mounted hook queries stay protected. */
1316
+ maxQueries?: number; /** Called when cache-limit eviction removes items or queries from in-memory state. */
1317
+ onStateCleanup?: (cleanup: ListQueryStateCleanup<QueryPayload, ItemPayload>) => void; /** Treats refetches as real-time driven, disabling stale mount refetches by default. Defaults to `false`. */
1318
+ usesRealTimeUpdates?: boolean; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
1319
+ lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
1320
+ baseCoalescingWindowMs?: number; /** Delay applied to medium-priority requests before they enter the scheduler. */
1321
+ mediumPriorityDelayMs?: number; /** Computes a per-fetch throttle for real-time updates using recent fetch cost and focus state. */
1322
+ dynamicRealtimeThrottleMs?: (params: {
1323
+ lastFetchDuration: number;
1324
+ windowIsNotFocused: boolean;
1325
+ }) => number; /** Store-level focus revalidation policy. Overrides the manager default. */
1326
+ revalidateOnWindowFocus?: boolean | (() => boolean);
1327
+ /** Reconnect-specific cooldown. Defaults to 2,000ms. The first reconnect revalidates immediately;
1328
+ * additional reconnects within the cooldown are coalesced into one trailing
1329
+ * revalidation. Set to `0` to disable this cooldown. */
1330
+ transportReconnectCooldownMs?: number; /** Rules that keep cached query membership in sync after item updates. */
1331
+ optimisticListUpdates?: OptimisticListUpdate<ItemState, QueryPayload, ItemPayload>[]; /** Called when an already-loaded query is invalidated. */
1332
+ onInvalidateQuery?: OnListQueryInvalidate<QueryPayload>; /** Called when an already-loaded item is invalidated. */
1333
+ onInvalidateItem?: OnListQueryItemInvalidate<ItemState, ItemPayload>; /** Observes request scheduler lifecycle events for this store. */
1334
+ onSchedulerEvent?: (event: RequestSchedulerEvents, data?: RequestSchedulerEventData) => void;
1335
+ /**
1336
+ * Store-specific mutation error handler.
1337
+ *
1338
+ * Overrides the manager fallback. Use `null` to disable inherited mutation
1339
+ * error handling for this store.
1340
+ */
1341
+ onMutationError?: ((error: unknown, options: StoreMutationErrorOptions) => void) | null; /** Opt-in hook-level query derivation from locally materialized items. */
1342
+ derivedQueries?: DerivedQueriesConfig<ItemState, QueryPayload, ItemPayload>; /** Converts a query payload to the stable cache key used by this store. */
1343
+ getQueryKey?: (params: QueryPayload) => ValidPayload | unknown[]; /** Converts an item payload to the stable cache key used by this store. */
1344
+ getItemKey?: (params: ItemPayload) => ValidPayload | unknown[];
1345
+ /** Opt-in persistent storage configuration. When provided, cached items and queries
1346
+ * are loaded from storage on first read and saved back on successful fetches.
1347
+ * Session scoping always reuses this store manager's `getSessionKey`, and the
1348
+ * persisted namespace always reuses this store's `id`. */
1349
+ persistentStorage?: ListQueryPersistentStorageConfig<ItemState, QueryPayload, ItemPayload, StorageState, TOfflineOperations>;
1350
+ } & ([TPartialResources] extends [true] ? {
1351
+ partialResources: PartialResourcesConfig<ItemState>;
1352
+ } : {
1353
+ partialResources?: undefined;
1354
+ });
1355
+ /** Options used to create a list-query store. */
1356
+ type ListQueryStoreOptions<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOffsetPagination extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown> = ListQueryStoreOptionsBase<ItemState, QueryPayload, ItemPayload, TPartialResources, TOfflineOperations, StorageState> & ([TOffsetPagination] extends [true] ? {
1357
+ /** Fetches one offset-paginated list query page. */fetchListFn: FetchListFnOffsetMode<ItemState, QueryPayload, ItemPayload>; /** Enables offset-pagination behavior and invalidation sizing. */
1358
+ offsetPagination: OffsetPaginationConfig;
1359
+ } : {
1360
+ /** Fetches one size-based list query page. */fetchListFn: FetchListFnSizeMode<ItemState, QueryPayload, ItemPayload>; /** Not allowed unless offset pagination is enabled. */
1361
+ offsetPagination?: undefined;
1362
+ });
1363
+ declare function createListQueryStore<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOffsetPagination extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown>(storeOptions: ListQueryStoreOptions<ItemState, QueryPayload, ItemPayload, TPartialResources, TOffsetPagination, TOfflineOperations, StorageState>): ListQueryStore<ItemState, QueryPayload, ItemPayload, TPartialResources, TOfflineOperations>;
1364
+ //#endregion
1365
+ //#region src/invalidationUtils.d.ts
1366
+ /**
1367
+ * Predicate that matches every currently known payload.
1368
+ *
1369
+ * Use it with APIs that accept payload filters, such as
1370
+ * `invalidateQueryAndItems`, `invalidateItem`, `getItemState`, and
1371
+ * `getQueriesState`.
1372
+ */
1373
+ declare const GET_ALL: (...args: unknown[]) => true;
1374
+ //#endregion
1375
+ //#region src/isOffScreenContext.d.ts
1376
+ /**
1377
+ * Context to set `isOffScreen` for all TSDF hooks within a subtree.
1378
+ *
1379
+ * When `true`, hooks wrapped by this context will not trigger data fetching or
1380
+ * respond to invalidation events, unless overridden by an explicit `isOffScreen`
1381
+ * option passed directly to the hook.
1382
+ *
1383
+ * @example
1384
+ * ```tsx
1385
+ * <IsOffScreenContext.Provider value={!isTabActive}>
1386
+ * <MyComponent />
1387
+ * </IsOffScreenContext.Provider>
1388
+ * ```
1389
+ */
1390
+ declare const IsOffScreenContext: Context<boolean>;
1391
+ //#endregion
1392
+ //#region src/persistentStorage/offline/sessionCoordinator.d.ts
1393
+ /**
1394
+ * Returns the latest offline status for a session. If the session has not been
1395
+ * initialized yet, this returns a default "online" status with empty recovery data.
1396
+ */
1397
+ declare function getGlobalOfflineStatus(sessionKey: string): GlobalOfflineStatus;
1398
+ /**
1399
+ * Returns the latest list of offline entities for a session.
1400
+ * Useful to render pending sync state badges or pending-item indicators.
1401
+ */
1402
+ declare function getGlobalOfflineEntities(sessionKey: string): GlobalOfflineEntity[];
1403
+ /**
1404
+ * Returns the latest list of offline conflict/retry resolutions for a session.
1405
+ * Useful to render conflict-resolution trays or retry-required queues.
1406
+ */
1407
+ declare function getGlobalOfflineResolutions(sessionKey: string): OfflineResolutionRecord[];
1408
+ /**
1409
+ * React hook that subscribes to the offline status stream for a session.
1410
+ */
1411
+ declare function useGlobalOfflineStatus(sessionKey: string): GlobalOfflineStatus;
1412
+ /**
1413
+ * React hook that subscribes to the offline entities stream for a session.
1414
+ */
1415
+ declare function useGlobalOfflineEntities(sessionKey: string): readonly GlobalOfflineEntity[];
1416
+ /**
1417
+ * React hook returning global offline conflict/retry resolutions for a session.
1418
+ */
1419
+ declare function useGlobalOfflineResolutions(sessionKey: string): readonly OfflineResolutionRecord[];
1420
+ //#endregion
1421
+ //#region src/persistentStorage/localStorageMetadata.d.ts
1422
+ type ManagedLocalStorageIo = {
1423
+ getItem(key: string): string | null;
1424
+ setItem(key: string, value: string): void;
1425
+ removeItem(key: string): void;
1426
+ listKeys(): string[];
1427
+ queueManifestWrite?(key: string, value: string | null): void;
1428
+ };
1429
+ type StoredManagedLocalStorageManifestEntry = {
1430
+ entryKey: string | undefined;
1431
+ lastAccessAt: number;
1432
+ sizeBytes?: number;
1433
+ meta?: unknown;
1434
+ };
1435
+ type ManagedLocalStorageManifestEntry<TMeta = unknown> = {
1436
+ entryKey: string | undefined;
1437
+ payloadKey: string;
1438
+ lastAccessAt: number;
1439
+ sizeBytes?: number;
1440
+ meta?: TMeta;
1441
+ };
1442
+ type ManagedLocalStorageNamespaceManifestEntry<TMeta = unknown> = ManagedLocalStorageManifestEntry<TMeta> & {
1443
+ entryKey: string;
1444
+ };
1445
+ declare function readManagedLocalStorageManifestEntriesByPrefix(prefix: string, io?: ManagedLocalStorageIo): ManagedLocalStorageNamespaceManifestEntry[];
1446
+ declare function readManagedLocalStorageSingleEntryByPayload(payloadKey: string, io?: ManagedLocalStorageIo): ManagedLocalStorageManifestEntry | null;
1447
+ declare function readManagedLocalStorageNamespaceEntryByPayload(payloadKey: string, storagePrefix: string, io?: ManagedLocalStorageIo): ManagedLocalStorageManifestEntry | null;
1448
+ type UpsertSingleEntryParams = {
1449
+ storageKey: string;
1450
+ lastAccessAt?: number;
1451
+ clearSizeBytes?: boolean;
1452
+ sizeBytes?: number;
1453
+ mergeMeta?: (currentMeta: StoredManagedLocalStorageManifestEntry['meta']) => unknown;
1454
+ meta?: unknown;
1455
+ };
1456
+ declare function upsertManagedLocalStorageSingleEntry(params: UpsertSingleEntryParams, io?: ManagedLocalStorageIo): string;
1457
+ type UpsertNamespaceEntryParams = {
1458
+ storagePrefix: string;
1459
+ entryKey: string;
1460
+ lastAccessAt?: number;
1461
+ sizeBytes?: number;
1462
+ mergeMeta?: (currentMeta: StoredManagedLocalStorageManifestEntry['meta']) => unknown;
1463
+ meta?: unknown;
1464
+ };
1465
+ declare function upsertManagedLocalStorageNamespaceEntry(params: UpsertNamespaceEntryParams, io?: ManagedLocalStorageIo): string;
1466
+ //#endregion
1467
+ //#region src/persistentStorage/storageAdapter.d.ts
1468
+ type LocalStorageMetadataOptions = {
1469
+ metadata: 'single';
1470
+ } | {
1471
+ metadata: 'namespace';
1472
+ namespacePrefix: string;
1473
+ };
1474
+ type LocalPersistentStorage = {
1475
+ kind: 'local-sync';
1476
+ runLocked<T>(callback: () => T | Promise<T>): Promise<T>;
1477
+ readRaw(key: string): string | null;
1478
+ write<T>(key: string, value: T): {
1479
+ rawValue: string;
1480
+ sizeBytes: number;
1481
+ };
1482
+ remove(key: string, options?: LocalStorageMetadataOptions): void;
1483
+ removeByPrefix(prefix: string): void;
1484
+ listKeys(prefix: string): string[];
1485
+ listRawKeys(prefix: string): string[];
1486
+ getManifestKeyForSingle(storageKey: string): string;
1487
+ getManifestKeyForPrefix(storagePrefix: string): string;
1488
+ readSingleEntryMetadataByPayload(payloadKey: string): ReturnType<typeof readManagedLocalStorageSingleEntryByPayload>;
1489
+ readNamespaceEntryMetadataByPayload(payloadKey: string, namespacePrefix: string): ReturnType<typeof readManagedLocalStorageNamespaceEntryByPayload>;
1490
+ listManifestEntries(prefix: string): ReturnType<typeof readManagedLocalStorageManifestEntriesByPrefix>;
1491
+ upsertSingleEntry(args: Parameters<typeof upsertManagedLocalStorageSingleEntry>[0]): string;
1492
+ upsertNamespaceEntry(args: Parameters<typeof upsertManagedLocalStorageNamespaceEntry>[0]): string;
1493
+ touchSingleEntry(payloadKey: string): boolean;
1494
+ touchNamespaceEntry(payloadKey: string, namespacePrefix: string): boolean;
1495
+ clearManifest(manifestKey: string): void;
1496
+ clearSession(sessionKey: string): void;
1497
+ registerMaintenanceCallback(manifestKey: string, callback: () => Promise<void>): void;
1498
+ unregisterMaintenanceCallback(manifestKey: string): void;
1499
+ runMaintenance(forceManifestKeys?: Iterable<string>): Promise<void>;
1500
+ readProtectedStorageKeys(sessionKey: string): Set<string>;
1501
+ syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>): void;
1502
+ };
1503
+ declare const localPersistentStorage: LocalPersistentStorage;
1504
+ //#endregion
1505
+ //#region src/persistentStorage/persistentStorageManager.d.ts
1506
+ /** Clears all persistent storage entries for a given session key and adapter. */
1507
+ declare function clearSessionStorage(sessionKey: string, adapter: StorageAdapter): Promise<void>;
1508
+ /** Clears all persistent storage entries for a given session key across built-in adapters. */
1509
+ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
1510
+ //#endregion
1511
+ //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
1512
+ declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
1513
+ //#endregion
1514
+ export { type AsyncStorageAdapter, type AsyncStorageDiscoveredScope, type AsyncStorageDriver, type AsyncStorageDriverSetEntry, type AsyncStorageMetadataOrder, type AsyncStorageNamespaceCommitArgs, type AsyncStorageNamespaceCommitTouch, type AsyncStorageNamespaceCommitUpsert, type AsyncStorageNamespaceGetResult, type AsyncStorageNamespaceHandle, type AsyncStorageNamespaceKind, type AsyncStorageNamespaceScope, type AsyncStorageReadOptions, type BlockWindowCloseHandler, CollectionItemStatus, type CollectionOfflineEntityRef, type CollectionOfflineOperationDefinition, type CollectionPersistentStorageConfig, CollectionStateCleanup, CollectionStore, CollectionStoreEvents, CollectionStoreOptions, CollectionStoreStoreEvents, CollectionUseMultipleItemsQuery, type ConvertedPersistentStorageDataSchema, type CreateStoreManagerOptions, type DefineCollectionOfflineOperations, type DefineDocumentOfflineOperations, type DefineListQueryOfflineOperations, type DefineOfflineOperation, type DerivedQueriesConfig, type DerivedQueryContext, type DerivedQuerySource, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type DynamicRealtimeThrottleMs, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, type MaybeTSDFResult, type MutationDebounce, type MutationSkipped, type OfflineAccumulationConfig, type OfflineAccumulationMergeContext, type OfflineConflictResolutionAction, type OfflineEntityMutationKind, type OfflineMutationDescriptor, type OfflineMutationInput, type OfflineMutationQueueingCause, type OfflineMutationQueueingConfig, type OfflineMutationQueueingPolicy, type OfflineMutationResult, type OfflineMutationUploadsInput, type OfflineOperationKind, type OfflineOperationUploadsContext, type OfflineQueueEntry, type OfflineReplayRetryConfig, type OfflineResolutionAction, type OfflineResolutionActionForOperation, type OfflineResolutionConflictParseError, type OfflineResolutionConflictParseErrorCode, type OfflineResolutionRecord, type OfflineResolutionRecordForOperation, type OfflineResolutionRecordForStore, type OfflineRetryExhaustedResolutionAction, type OfflineRuntimeConfig, type OfflineRuntimeConfigUpdate, type OfflineSession, type OfflineSessionConfig, type OfflineSessionUploadsConfig, type OfflineStoredUploadRecord, type OfflineSupersedeConfig, type OfflineSyncState, type OfflineTempEntitiesConfig, type OfflineTempEntitiesReconciliation, type OfflineTempEntityConfig, type OfflineTempEntityPendingEntry, type OfflineUpload, type OfflineUploadAdapter, type OfflineUploadProgress, type OfflineUploadSource, type OfflineUploadState, type OfflineUploadTransportContext, type OffsetPaginationConfig, OnCollectionItemInvalidate, OnDocumentInvalidate, type OnListQueryInvalidate, type OnListQueryItemInvalidate, type OperationConflict, type OperationResult, type OptimisticListUpdate, type ParsedOfflineResolutionConflictResultForOperation, type PartialResourcesConfig, type PayloadDebounce, type PersistentStorageBaseConfig, type PersistentStorageDataSchema, type PersistentStoragePreloadResult, type PersistentStorageSchema, type QueryFetchPayload, type QueryStatus, type StorageAdapter, type StoreError, StoreFetchError, type StoreManager, StoreMutationError, type StoreMutationErrorOptions, type TSDFDebugLogArea, type TSDFDebugLogEntry, type TSDFDebugLogLevel, type TSDFDebugLogger, type TSDFDebugOptions, type TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createCollectionStore, createDocumentStore, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };