tsdf 17.0.0-alpha.6 → 17.0.0-alpha.8

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.
package/dist/main.d.ts CHANGED
@@ -1,1411 +1,10 @@
1
+ import { $ as OfflineResolutionRecord, A as DefineListQueryOfflineOperations, At as StoreError, B as OfflineEntityMutationKind, Bt as RequestSchedulerEventData, C as PersistentStorageSchema, Ct as OfflineUploadAdapter, D as CollectionOfflineOperationDefinition, Dt as OfflineUploadTransportContext, E as CollectionOfflineEntityRef, Et as OfflineUploadState, F as ListQueryOfflineEntityRef, Ft as ValidPayload, G as OfflineMutationQueueingPolicy, H as OfflineMutationInput, Ht as ScheduleFetchOptions, I as ListQueryOfflineOperationDefinition, It as ValidStoreState, J as OfflineReplayRetryConfig, K as OfflineOperationKind, L as OfflineAccumulationConfig, Lt as fetchTypePriority, M as DocumentOfflineOperationDefinition, Mt as StoreMutationError, N as GlobalOfflineEntity, Nt as StoreMutationErrorOptions, O as DefineCollectionOfflineOperations, Ot as MutationSkipped, P as GlobalOfflineStatus, Pt as TSDFStatus, Q as OfflineResolutionConflictParseErrorCode, R as OfflineAccumulationMergeContext, Rt as mutationSkipped, S as PersistentStoragePreloadResult, St as OfflineUpload, T as AnyOfflineOperationDefinition, Tt as OfflineUploadSource, U as OfflineMutationQueueingCause, Ut as ScheduleFetchResults, V as OfflineMutationDescriptor, Vt as RequestSchedulerEvents, W as OfflineMutationQueueingConfig, X as OfflineResolutionActionForOperation, Y as OfflineResolutionAction, 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 StoreFetchError, k as DefineDocumentOfflineOperations, kt as PayloadDebounce, 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, 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 FetchType } from "./types-DkNgE_f9.js";
1
2
  import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
2
3
  import { Emitter } from "evtmitter";
3
4
  import { Context } from "react";
4
5
  import { Result } from "t-result";
5
6
  import { Store } from "t-state";
6
- import { RcType } from "runcheck";
7
- import { StandardSchemaV1 } from "@standard-schema/spec";
8
7
 
9
- //#region src/requestScheduler.d.ts
10
- type RequestSchedulerEvents = 'scheduled-fetch-started' | 'rt-fetch-scheduled' | 'rt-fetch-cancelled' | 'scheduled-rt-fetch-started' | 'medium-priority-scheduled' | 'medium-priority-fetch-started' | 'medium-priority-cancelled' | 'batch-size-triggered';
11
- type RequestSchedulerEventData = {
12
- /** Delay in ms for scheduled events (medium-priority-scheduled, rt-fetch-scheduled) */delayMs?: number;
13
- };
14
- type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled' | 'triggered' | 'coalesced' | 'medium-scheduled' | 'added-to-batch' | 'batch-triggered';
15
- type FetchType = 'lowPriority' | 'mediumPriority' | 'highPriority' | 'realtimeUpdate';
16
- type ScheduleFetchOptions = {
17
- mediumPriorityDelayMs?: number;
18
- };
19
- //#endregion
20
- //#region src/utils/storeShared.d.ts
21
- type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
22
- type ValidPayload = number | string | Record<string, unknown>;
23
- type ValidStoreState = Record<string, unknown> | unknown[];
24
- /**
25
- * Debounce settings for payload-driven automatic fetches in store hooks.
26
- *
27
- * The hook still reads data from state using the latest payload immediately.
28
- * Only the automatic fetch side is delayed. Single hooks do not support
29
- * combining this with `ensureIsLoaded`.
30
- */
31
- type PayloadDebounce = {
32
- /** Debounce window in milliseconds before the latest payload is fetched. */ms: number;
33
- /**
34
- * Maximum time a burst may stay deferred before the latest payload is
35
- * fetched, even if changes keep happening within the debounce window.
36
- */
37
- maxWait?: number;
38
- /**
39
- * When true, the first payload in a burst may fetch immediately, and later
40
- * changes within the same burst stay debounced until the wait window ends.
41
- */
42
- leading?: boolean;
43
- };
44
- type StoreError = {
45
- code: number;
46
- id: string;
47
- message: string;
48
- path?: string;
49
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
50
- };
51
- declare const fetchTypePriority: Record<FetchType, number>;
52
- type MutationSkipped = {
53
- kind: 'skipped';
54
- };
55
- declare const mutationSkipped: MutationSkipped;
56
- /** Options passed to mutation error handlers. */
57
- type StoreMutationErrorOptions = {
58
- /**
59
- * True when the mutation caller asked the shared error handler to stay quiet.
60
- *
61
- * Handlers are still called so apps can keep centralized logging, metrics, or
62
- * custom recovery behavior while suppressing user-facing noise such as toast
63
- * notifications.
64
- */
65
- silentErrors?: boolean;
66
- };
67
- declare class StoreMutationError extends Error {
68
- readonly kind = "error";
69
- code: number;
70
- id: string;
71
- path?: string;
72
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
73
- constructor(error: StoreError, options?: ErrorOptions);
74
- }
75
- declare class StoreFetchError extends Error {
76
- code: number;
77
- id: string;
78
- type: 'fetch' | 'aborted' | 'timeout';
79
- path?: string;
80
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
81
- constructor(error: StoreError, type: 'fetch' | 'aborted' | 'timeout');
82
- }
83
- //#endregion
84
- //#region src/persistentStorage/offlineUploadTypes.d.ts
85
- type OfflineUploadState = 'pending' | 'uploading' | 'uploaded' | 'failed';
86
- type OfflineUploadSource = 'manual' | 'mutation';
87
- type OfflineUploadProgress = {
88
- progress: number;
89
- loadedBytes?: number;
90
- totalBytes?: number;
91
- };
92
- type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
93
- id: string;
94
- sessionKey: string;
95
- source: OfflineUploadSource;
96
- state: OfflineUploadState;
97
- fileName: string;
98
- mimeType: string;
99
- sizeBytes: number;
100
- createdAt: number;
101
- updatedAt: number;
102
- resolvedRef?: TResolvedRef;
103
- progress?: OfflineUploadProgress;
104
- lastError?: {
105
- message: string;
106
- };
107
- };
108
- type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
109
- file: File;
110
- lastOnlineSessionStartedAt?: number;
111
- lastModified: number;
112
- };
113
- type OfflineUploadAdapter = {
114
- save<TResolvedRef extends ValidPayload>(sessionKey: string, id: string, record: OfflineStoredUploadRecord<TResolvedRef>): Promise<void>;
115
- load<TResolvedRef extends ValidPayload>(sessionKey: string, id: string): Promise<OfflineStoredUploadRecord<TResolvedRef> | null>;
116
- list<TResolvedRef extends ValidPayload>(sessionKey: string): Promise<OfflineStoredUploadRecord<TResolvedRef>[]>;
117
- remove(sessionKey: string, id: string): Promise<void>;
118
- clearSession(sessionKey: string): Promise<void>;
119
- resetForTests?(): void;
120
- };
121
- type OfflineUploadTransportContext = {
122
- id: string;
123
- sessionKey: string;
124
- file: File;
125
- onProgress: (progress: OfflineUploadProgress) => void;
126
- };
127
- type OfflineSessionUploadsConfig<TResolvedRef extends ValidPayload = ValidPayload> = {
128
- adapter: OfflineUploadAdapter;
129
- upload: (ctx: OfflineUploadTransportContext) => Promise<TResolvedRef>;
130
- concurrency?: number;
131
- };
132
- type OfflineMutationUploadsInput = Record<string, Blob | File>;
133
- type OfflineAttachedUploadIds = Record<string, string>;
134
- type OfflineOperationUploadsContext<TResolvedRef extends ValidPayload = ValidPayload> = {
135
- filesById: Record<string, File>;
136
- resolvedRefsById: Record<string, TResolvedRef>;
137
- };
138
- //#endregion
139
- //#region src/persistentStorage/types.d.ts
140
- type AsyncStorageNamespaceKind = 'document' | 'collection.item' | 'listQuery.item' | 'listQuery.query' | 'offline.queue' | 'offline.conflict' | 'offline.entity' | '__internal.protected';
141
- type AsyncStorageNamespaceScope = {
142
- sessionKey: string;
143
- storeName: string;
144
- kind: AsyncStorageNamespaceKind;
145
- };
146
- type AsyncStorageTouchMode = 'never' | 'coarse' | 'force';
147
- type AsyncStorageReadOptions = {
148
- touch?: AsyncStorageTouchMode;
149
- };
150
- type AsyncStorageMetadataOrder = 'key' | 'lru-asc' | 'lru-desc';
151
- type AsyncStorageEntryMetadataBase = {
152
- key: string;
153
- payloadRef: string;
154
- writtenAt: number;
155
- lastAccessAt: number; /** Serialized JSON size used for persistence budgeting for this entry. */
156
- sizeBytes?: number;
157
- version: number;
158
- };
159
- type AsyncStorageEntryMetadata<TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = AsyncStorageEntryMetadataBase & {
160
- customMetadata: TCustomMetadata;
161
- };
162
- type AsyncStorageNamespaceGetResult<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
163
- value: TValue;
164
- metadata: AsyncStorageEntryMetadata<TCustomMetadata>;
165
- };
166
- type AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
167
- key: string;
168
- value: TValue;
169
- serializedValue?: string;
170
- sizeBytes?: number;
171
- version: number;
172
- metadata?: TCustomMetadata;
173
- };
174
- type AsyncStorageNamespaceCommitTouch = {
175
- key: string;
176
- lastAccessAt?: number;
177
- };
178
- type AsyncStorageNamespaceStaticPolicy = {
179
- maxBytes?: number;
180
- pinnedKeys?: string[];
181
- };
182
- type AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
183
- upserts?: AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata>[];
184
- removes?: string[];
185
- staticPolicy?: AsyncStorageNamespaceStaticPolicy | null;
186
- touches?: AsyncStorageNamespaceCommitTouch[];
187
- };
188
- type AsyncStorageDriverSetEntry = {
189
- key: string;
190
- value: unknown;
191
- serializedValue?: string;
192
- sizeBytes?: number;
193
- };
194
- type AsyncStorageDiscoveredScope = {
195
- /** Known raw record keys for this scope. `null` if keys were not enumerated during discovery. */knownRecordKeys: string[] | null;
196
- scope: AsyncStorageNamespaceScope;
197
- };
198
- /** Low-level async backend contract implemented by custom storage drivers. */
199
- type AsyncStorageDriver = {
200
- /** Read a single raw record from a logical namespace. */get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
201
- set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
202
- remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
203
- listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
204
- clear(scope: AsyncStorageNamespaceScope): Promise<void>; /** Namespace discovery used for cold cleanup, protected-key restore, and session clearing. */
205
- listScopes(sessionKey?: string): Promise<AsyncStorageNamespaceScope[]>; /** Returns discovered scopes together with known raw record keys. Used for cleanup. */
206
- listScopesWithKnownRecordKeys(sessionKey?: string): Promise<AsyncStorageDiscoveredScope[]>; /** Bulk read for multiple keys in a single call. */
207
- getMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<unknown[]>; /** Bulk write for multiple entries in a single call. */
208
- setMany(scope: AsyncStorageNamespaceScope, entries: AsyncStorageDriverSetEntry[]): Promise<void>; /** Bulk remove for multiple keys in a single call. */
209
- removeMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<void>;
210
- };
211
- type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
212
- get(key: string, options?: AsyncStorageReadOptions): Promise<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>;
213
- getMany(keys: string[], options?: AsyncStorageReadOptions): Promise<Array<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>>;
214
- listKeys(): Promise<string[]>;
215
- commit(args: AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata>): Promise<void>;
216
- listMetadata(args?: {
217
- order?: AsyncStorageMetadataOrder;
218
- }): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
219
- listMetadataByFilter?(args: {
220
- filter: {
221
- equals: unknown;
222
- key: string;
223
- };
224
- order?: AsyncStorageMetadataOrder;
225
- }): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>;
226
- clear(): Promise<void>;
227
- };
228
- /** Managed async adapter consumed by TSDF persistence internals. */
229
- type AsyncStorageAdapter = {
230
- /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
231
- openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
232
- readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
233
- syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
234
- clearSession(sessionKey: string): Promise<void>; /** Test-only reset hook used by TSDF internals. */
235
- resetForTests?(): void;
236
- };
237
- /** Injected persistent storage adapter. */
238
- type StorageAdapter = 'local-sync' | AsyncStorageAdapter;
239
- /** Standard Schema v1 (zod, valibot, arktype, etc.). */
240
- type StandardSchemaLike<T> = StandardSchemaV1<unknown, T>;
241
- /** Union of supported schema types for persistent storage validation. */
242
- type PersistentStorageSchema<T> = RcType<T> | StandardSchemaLike<T>;
243
- /**
244
- * Converts between the in-memory store data shape and the persisted storage shape.
245
- * Use this when the cached representation should differ from the API store format.
246
- */
247
- type ConvertedPersistentStorageDataSchema<TFinal, TStorage> = {
248
- /** Schema for the final in-memory store data after hydration. */storeSchema: PersistentStorageSchema<TFinal>; /** Schema for the raw persisted storage representation. */
249
- storageSchema: PersistentStorageSchema<TStorage>; /** Converts in-memory store data into the persisted storage representation. */
250
- convertToStorage: (value: TFinal) => TStorage; /** Converts persisted storage data into the final in-memory store representation. */
251
- convertFromStorage: (value: TStorage) => TFinal;
252
- };
253
- /**
254
- * Schema configuration for persisted store data.
255
- * Accept either the final store schema directly or a converted storage format.
256
- */
257
- type PersistentStorageDataSchema<TFinal, TStorage = unknown> = PersistentStorageSchema<TFinal> | ConvertedPersistentStorageDataSchema<TFinal, TStorage>;
258
- /** Result entry returned by explicit persistent-storage preload APIs. */
259
- type PersistentStoragePreloadResult<Payload extends ValidPayload = ValidPayload> = {
260
- /** Payload loaded from storage or fresh store initialization result. */payload: Payload; /** `true` when payload came from storage cache, `false` when loaded from source. */
261
- preloaded: boolean;
262
- };
263
- type PersistentStorageErrorHandler = (error: unknown) => void;
264
- /** Base config shared by all store types. */
265
- type PersistentStorageBaseConfig<TFinal, TStorage = unknown> = {
266
- /** Unique storage namespace used internally for this store's persisted entries. Must not contain `.`. */storeName: string; /** Injected adapter used to save and restore persistent data. Use `'local-sync'` for built-in localStorage or provide a custom async adapter. */
267
- adapter: StorageAdapter; /** Schema used to validate cached data on load and optionally convert persisted data. */
268
- schema: PersistentStorageDataSchema<TFinal, TStorage>; /** Optional version number for cache invalidation. When omitted, no version is persisted or checked. */
269
- version?: number;
270
- /**
271
- * Returns a session key scoping storage per org/tenant.
272
- * Return `false` to indicate the session is not ready — all storage
273
- * operations (load, save, clear) will be skipped until it returns a string.
274
- */
275
- getSessionKey: () => string | false;
276
- /**
277
- * Called when a storage write operation fails (e.g. quota exceeded, OPFS write error).
278
- * Use this to log or report persistence failures to your error tracking service.
279
- */
280
- onPersistentStorageError?: PersistentStorageErrorHandler | null;
281
- };
282
- /** Store-level persistent storage config. Session scoping comes from the parent store. */
283
- type StorePersistentStorageBaseConfig<TFinal, TStorage = unknown> = Omit<PersistentStorageBaseConfig<TFinal, TStorage>, 'getSessionKey' | 'storeName'>;
284
- type InternalDocumentOfflineOperations$1<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
285
- type DocumentOfflineOperationsConfig$1<State extends ValidStoreState> = InternalDocumentOfflineOperations$1<State> | null;
286
- type PublicStoreOfflineConfig<TOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> = Record<never, never>> = {
287
- /** Store-local offline operation definitions. Optional when only session-level offline controls are used. */operations?: TOperations;
288
- };
289
- type PublicStoreOfflineConfigField<TOfflineOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> | null> = {
290
- /** Optional offline sync/replay configuration for mutations. */offline?: TOfflineOperations extends null ? PublicStoreOfflineConfig : PublicStoreOfflineConfig<Exclude<TOfflineOperations, null>>;
291
- };
292
- /** Persistent storage config for DocumentStore. */
293
- type DocumentPersistentStorageConfig<State extends ValidStoreState, StorageState = unknown, TOfflineOperations extends DocumentOfflineOperationsConfig$1<State> = null> = StorePersistentStorageBaseConfig<State, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations>;
294
- type InternalCollectionOfflineOperations$1<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
295
- getEntityRefs: (ctx: {
296
- input: __LEGIT_ANY__;
297
- }) => CollectionOfflineEntityRef<ItemPayload>[];
298
- dependsOn?: (ctx: {
299
- input: __LEGIT_ANY__;
300
- }) => CollectionOfflineEntityRef<ItemPayload>[];
301
- }> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
302
- type CollectionOfflineOperationsConfig$1<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations$1<ItemState, ItemPayload> | null;
303
- type CollectionPersistentStorageFields<ItemPayload extends ValidPayload> = {
304
- /** Schema used to validate cached item payloads on load. */payloadSchema: PersistentStorageSchema<ItemPayload>;
305
- /**
306
- * Maximum serialized JSON size to persist for collection items. Budgeting
307
- * uses the serialized string length, not browser quota bytes. Items are
308
- * evicted via LRU. Defaults to 64 KB in `local-sync` and 128 KB in async
309
- * adapters.
310
- */
311
- maxBytes?: number; /** Item payloads that should never be evicted from storage. */
312
- pinnedItems?: ItemPayload[];
313
- /**
314
- * Item payloads that should never be persisted or restored.
315
- * Accepts either an explicit payload list or a predicate function.
316
- * Takes precedence over `pinnedItems`.
317
- */
318
- ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
319
- };
320
- /** Persistent storage config for CollectionStore. */
321
- type CollectionPersistentStorageConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends CollectionOfflineOperationsConfig$1<ItemState, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & CollectionPersistentStorageFields<ItemPayload>;
322
- type InternalListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
323
- getEntityRefs: (ctx: {
324
- input: __LEGIT_ANY__;
325
- }) => ListQueryOfflineEntityRef<ItemPayload>[];
326
- dependsOn?: (ctx: {
327
- input: __LEGIT_ANY__;
328
- }) => ListQueryOfflineEntityRef<ItemPayload>[];
329
- }> & ([ItemState | QueryPayload | ItemPayload] extends [never] ? never : unknown);
330
- type ListQueryOfflineOperationsConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = InternalListQueryOfflineOperations<ItemState, QueryPayload, ItemPayload> | null;
331
- type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
332
- /** Schema used to validate cached item payloads on load. */itemPayloadSchema: PersistentStorageSchema<ItemPayload>; /** Schema used to validate cached query payloads on load. */
333
- queryPayloadSchema: PersistentStorageSchema<QueryPayload>;
334
- /**
335
- * Maximum serialized JSON size to persist for list items. Budgeting uses the
336
- * serialized string length, not browser quota bytes. Defaults to 64 KB in
337
- * `local-sync` and 128 KB in async adapters.
338
- */
339
- maxItemBytes?: number;
340
- /**
341
- * Maximum serialized JSON size to persist for list queries. Budgeting uses
342
- * the serialized string length, not browser quota bytes. Defaults to 32 KB
343
- * in `local-sync` and 64 KB in async adapters.
344
- */
345
- maxQueryBytes?: number; /** Maximum number of items per query to persist. Defaults to 100. */
346
- maxQuerySize?: number; /** Item payloads that should never be evicted from storage. */
347
- pinnedItems?: ItemPayload[]; /** Query payloads that should never be evicted from storage. */
348
- pinnedQueries?: QueryPayload[];
349
- /**
350
- * Item payloads that should never be persisted or restored.
351
- * Accepts either an explicit payload list or a predicate function.
352
- * Takes precedence over `pinnedItems`.
353
- */
354
- ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
355
- };
356
- /** Persistent storage config for ListQueryStore. */
357
- type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
358
- //#endregion
359
- //#region src/persistentStorage/validateWithSchema.d.ts
360
- type SchemaValidationError = readonly string[] | StandardSchemaV1.FailureResult['issues'];
361
- //#endregion
362
- //#region src/persistentStorage/offline/types.d.ts
363
- /** Store kinds supported by offline replay and sync state tracking. */
364
- type OfflineStoreType = 'document' | 'collection' | 'listQuery';
365
- /** Phase where a failure occurred during offline-enabled operation flow. */
366
- type OfflineFailurePhase = 'fetch' | 'mutation' | 'sync';
367
- /** High-level classification used by outage detection. */
368
- type OfflineFailureClassification = 'outage' | 'network' | 'ignore';
369
- /** Kinds of entities participating in offline conflict/sync tracking. */
370
- type OfflineEntityKind = 'document' | 'item' | 'query';
371
- /** Lifecycle declared per offline operation definition. */
372
- type OfflineOperationKind = 'create' | 'update' | 'delete';
373
- /** Effective lifecycle derived for an offline entity across queued work. */
374
- type OfflineEntityMutationKind = 'create' | 'createAndUpdate' | 'update' | 'delete';
375
- /** Connectivity cause currently governing offline mutation queueing. */
376
- type OfflineMutationQueueingCause = 'network' | 'outage';
377
- /** Root policy value for whether offline-enabled mutations may queue. */
378
- type OfflineMutationQueueingPolicy = 'allow' | 'disallow';
379
- /** Root mutation queueing policy shared by all configured offline operations. */
380
- type OfflineMutationQueueingConfig = {
381
- /**
382
- * Controls whether offline-enabled mutations may queue while network mode is
383
- * active, including browser-detected offline and classified network failures.
384
- * @default 'allow'
385
- */
386
- network?: OfflineMutationQueueingPolicy;
387
- /**
388
- * Controls whether offline-enabled mutations may queue while outage mode is
389
- * active.
390
- * @default 'allow'
391
- */
392
- outage?: OfflineMutationQueueingPolicy;
393
- };
394
- /**
395
- * Effective runtime offline controls exposed through an offline session.
396
- *
397
- * All fields are session-scoped and affect every store attached to the same
398
- * offline session.
399
- */
400
- type OfflineRuntimeConfig = {
401
- /** Whether future operations may enter network offline handling. */network: {
402
- enabled: boolean;
403
- }; /** Whether future operations may enter outage offline handling. */
404
- outage: {
405
- enabled: boolean;
406
- }; /** Effective queue admission policy for offline-enabled mutations. */
407
- mutationQueueing: {
408
- network: OfflineMutationQueueingPolicy;
409
- outage: OfflineMutationQueueingPolicy;
410
- };
411
- };
412
- /** Default runtime config when offline is not configured or no session exists. */
413
- declare const defaultOfflineRuntimeConfig: OfflineRuntimeConfig;
414
- /**
415
- * Partial runtime offline control update accepted by an offline session.
416
- *
417
- * Provided fields shallow-merge into the current runtime config.
418
- */
419
- type OfflineRuntimeConfigUpdate = {
420
- /** Optional session-scoped update for network mode enablement. */network?: {
421
- enabled?: boolean;
422
- }; /** Optional session-scoped update for outage mode enablement. */
423
- outage?: {
424
- enabled?: boolean;
425
- }; /** Optional session-scoped update for offline mutation queue admission policy. */
426
- mutationQueueing?: {
427
- network?: OfflineMutationQueueingPolicy;
428
- outage?: OfflineMutationQueueingPolicy;
429
- };
430
- };
431
- /** Context passed into offline failure classification hooks. */
432
- type OfflineFailureContext = {
433
- /** Phase in which the failure was detected. */phase: OfflineFailurePhase; /** Store type affected by the failure. */
434
- storeType: OfflineStoreType; /** Optional operation name associated with the failure. */
435
- operationName?: string; /** Session key used by browser tab and persistence scoping. */
436
- sessionKey: string;
437
- };
438
- /** Re-check strategy for recovery probing. Omitted fields use built-in defaults (which differ between network and outage modes). */
439
- type OfflineRecoveryProbeConfig = {
440
- /**
441
- * Initial recovery check delay, in milliseconds.
442
- * @default 5_000 (network) / 30_000 (outage)
443
- */
444
- initialIntervalMs?: number;
445
- /**
446
- * Maximum recovery check delay, in milliseconds.
447
- * @default 60_000 (network) / 300_000 (outage)
448
- */
449
- maxIntervalMs?: number;
450
- /**
451
- * Multiplicative backoff between recovery probes.
452
- * @default 2
453
- */
454
- backoffMultiplier?: number;
455
- /**
456
- * Jitter ratio (0-1) applied to the recovery probe delay.
457
- * @default 0.2
458
- */
459
- jitterRatio?: number;
460
- };
461
- /** Network availability mode configuration for offline controls. */
462
- type OfflineNetworkModeConfig = {
463
- /** Enable network connectivity detection and tracking. */enabled: boolean;
464
- /**
465
- * If true, subscribe to browser `online` / `offline` events.
466
- * @default true
467
- */
468
- listenToBrowserEvents?: boolean;
469
- /**
470
- * Optional override for network connectivity checks.
471
- * Return `true` when network should be considered offline.
472
- */
473
- getIsOffline?: () => boolean | Promise<boolean>;
474
- /**
475
- * Probe whether classified network recovery has completed.
476
- * Return `true` when the session should leave network offline mode.
477
- */
478
- recoveryCheck?: (ctx: {
479
- sessionKey: string;
480
- }) => Promise<boolean> | boolean; /** Optional probe config to tune classified network recovery behavior. */
481
- recoveryProbe?: OfflineRecoveryProbeConfig;
482
- };
483
- /** Server outage detection and recovery configuration. */
484
- type OfflineOutageModeConfig = {
485
- /** Enable outage mode logic and confirmation retry flow. */enabled: boolean; /** Probe the remote service to confirm outage recovery. */
486
- recoveryCheck: (ctx: {
487
- sessionKey: string;
488
- }) => Promise<boolean> | boolean; /** Optional probe config to tune recovery behavior. */
489
- recoveryProbe?: OfflineRecoveryProbeConfig;
490
- };
491
- /** Fixed replay retry policy for healthy online replay failures. Omitted fields use built-in defaults. */
492
- type OfflineReplayRetryConfig = {
493
- /**
494
- * Max counted failures before manual resolution is required.
495
- * @default 3
496
- */
497
- maxFailures?: number;
498
- /**
499
- * Fixed delay between replay retries, in milliseconds.
500
- * @default 5000
501
- */
502
- intervalMs?: number;
503
- };
504
- /** Shared offline/session policy reused by every store in the same session. */
505
- type OfflineSessionConfig<TUploadRef extends ValidPayload = ValidPayload> = {
506
- /**
507
- * Classify a remote failure as `outage`, `network`, or `ignore`.
508
- * `outage` activates outage recovery behavior.
509
- * `network` activates network offline handling for future operations only
510
- * when `network.enabled` is true. Existing offline recovery may keep using
511
- * classifications until already-active work finishes recovering.
512
- */
513
- classifyFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<OfflineFailureClassification> | OfflineFailureClassification;
514
- /**
515
- * Optional replay-only classifier for ambiguous sync failures that stayed
516
- * online (`classifyFailure(...) === 'ignore'`).
517
- *
518
- * Return `true` only when automatically re-sending the replayed mutation is
519
- * known to be safe. Return `false` to avoid auto-replay retries; in that
520
- * case the entry still enters `needs-confirmation` so `shouldSkipSync` /
521
- * conflict checks can run before the mutation is promoted to manual
522
- * resolution.
523
- */
524
- classifyRetryableFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<boolean> | boolean; /** Network detection strategy and browser integration. */
525
- network?: OfflineNetworkModeConfig; /** Outage detection and recovery strategy for remote failures. */
526
- outage?: OfflineOutageModeConfig; /** Fixed retry policy for healthy online replay failures. */
527
- replayRetry?: OfflineReplayRetryConfig;
528
- /**
529
- * Root policy controlling whether offline-enabled mutations may enter the
530
- * durable offline queue for each active offline cause.
531
- * @default undefined
532
- */
533
- mutationQueueing?: OfflineMutationQueueingConfig; /** Optional upload transport/storage config shared by the whole session. */
534
- uploads?: OfflineSessionUploadsConfig<TUploadRef>;
535
- };
536
- /** Per-session offline status snapshot shared across tabs. */
537
- type GlobalOfflineStatus = {
538
- /** Session key for this status bucket. */sessionKey: string;
539
- /**
540
- * Network mode admission enablement plus the last observed network-offline
541
- * state for this session. `active` is preserved even while new admission is
542
- * disabled so existing offline work can recover and sync safely.
543
- */
544
- network: {
545
- enabled: boolean;
546
- active: boolean;
547
- };
548
- /**
549
- * Outage mode admission enablement plus the last observed outage-active
550
- * state for this session. `active` is preserved even while new admission is
551
- * disabled so existing offline work can recover and sync safely.
552
- */
553
- outage: {
554
- enabled: boolean;
555
- active: boolean;
556
- }; /** Whether the session currently has any active offline cause. */
557
- isOfflineMode: boolean; /** Whether this tab currently acts as leader for this session. */
558
- isLeader: boolean; /** Timestamp when this status entry was last updated. */
559
- updatedAt: number; /** Timestamp of the last failure, if any. */
560
- lastFailureAt: number | null; /** Timestamp of last recovery probe execution, if any. */
561
- lastRecoveryCheckAt: number | null;
562
- };
563
- /** Queue state of an offline mutation entry. */
564
- type OfflineSyncState = 'pending' | 'syncing' | 'needs-confirmation';
565
- /** Aggregated offline status for a tracked document/item/query entity. */
566
- type GlobalOfflineEntity = {
567
- /** Internal entity identifier tracked by offline machinery. */id: string; /** Session key for this offline entity. */
568
- sessionKey: string; /** Store name where the entity is defined. */
569
- storeName: string; /** Store type this entity belongs to. */
570
- storeType: OfflineStoreType; /** Entity key used for deduping and conflict scoping. */
571
- entityKey: string; /** Entity kind used in queue partitioning. */
572
- entityKind: OfflineEntityKind; /** Effective lifecycle derived from queued operations targeting this entity. */
573
- kind: OfflineEntityMutationKind; /** Number of pending mutations waiting for sync. */
574
- pendingMutations: number; /** Current sync state for the entity. */
575
- syncState: OfflineSyncState | 'resolution-required'; /** Whether the entity currently requires manual resolution. */
576
- requiresResolution: boolean; /** Resolution ids currently blocking this entity from being resolved/applied. */
577
- blockedByResolutionIds: string[]; /** Child resolution ids currently derived from this entity's dependency chain. */
578
- childResolutionIds: string[]; /** Number of blocking parent resolutions currently affecting this entity. */
579
- blockedResolutionCount: number; /** Number of child resolutions currently derived from this entity's dependency chain. */
580
- childResolutionCount: number; /** Creation timestamp for lifecycle bookkeeping. */
581
- createdAt: number; /** Last mutation/update timestamp. */
582
- updatedAt: number; /** Optional temporary ID for optimistic create flows. */
583
- tempId?: ValidPayload;
584
- };
585
- /** Reference to an entity participating in offline sync tracking. */
586
- type OfflineEntityRef = {
587
- entityKey: string;
588
- entityKind: OfflineEntityKind;
589
- };
590
- /**
591
- * Persisted offline conflict payload.
592
- *
593
- * @typeParam TConflict - Conflict payload stored for later resolution.
594
- * @typeParam TInput - Original mutation input associated with the conflict.
595
- */
596
- type OfflineConflictResolutionRecordBase<TConflict = unknown, TInput = unknown> = {
597
- /** Resolution record identifier. */id: string; /** Resolution kind. */
598
- kind: 'conflict'; /** Queue entry identifier that produced this conflict. */
599
- entryId: string; /** Session key that owns this conflict record. */
600
- sessionKey: string; /** Store name associated with the conflict. */
601
- storeName: string; /** Store type associated with the conflict. */
602
- storeType: OfflineStoreType; /** Operation name linked to the conflict. */
603
- operation: string; /** Input value that triggered the conflict. */
604
- input: TInput; /** Conflict payload returned by the resolver. */
605
- conflict: TConflict; /** Timestamp when the original queued mutation was enqueued. */
606
- enqueuedAt: number; /** Entity references involved in the conflict. */
607
- entityRefs: OfflineEntityRef[]; /** Conflict creation timestamp. */
608
- createdAt: number; /** Conflict update timestamp. */
609
- updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
610
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
611
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
612
- dependencyUploadIds?: string[];
613
- };
614
- /** Derived dependency metadata exposed for offline manual resolutions. */
615
- type OfflineResolutionDependencyMetadata = {
616
- /** Parent resolution ids that must be cleared before this resolution can be retried or discarded. */blockedByResolutionIds: string[]; /** Child manual resolutions currently derived from this resolution's dependency chain. */
617
- childResolutionIds: string[]; /** Number of blocking parent resolutions affecting this resolution. */
618
- blockedResolutionCount: number; /** Number of child manual resolutions currently derived from this resolution. */
619
- childResolutionCount: number;
620
- };
621
- /**
622
- * Persisted offline conflict payload with derived dependency metadata.
623
- *
624
- * @typeParam TConflict - Conflict payload stored for later resolution.
625
- * @typeParam TInput - Original mutation input associated with the conflict.
626
- */
627
- type OfflineConflictResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecordBase<TConflict, TInput> & OfflineResolutionDependencyMetadata;
628
- /**
629
- * Persisted resolution record created when replay retries are exhausted.
630
- *
631
- * @typeParam TInput - Original mutation input associated with the replay failure.
632
- */
633
- type OfflineRetryExhaustedResolutionRecordBase<TInput = unknown> = {
634
- /** Resolution record identifier. */id: string; /** Resolution kind. */
635
- kind: 'retry-exhausted'; /** Queue entry identifier that exhausted replay retries. */
636
- entryId: string; /** Session key that owns this resolution record. */
637
- sessionKey: string; /** Store name associated with the resolution. */
638
- storeName: string; /** Store type associated with the resolution. */
639
- storeType: OfflineStoreType; /** Operation name linked to the replay failure. */
640
- operation: string; /** Input value that exhausted replay retries. */
641
- input: TInput; /** Timestamp when the original queued mutation was enqueued. */
642
- enqueuedAt: number; /** Entity references involved in the resolution. */
643
- entityRefs: OfflineEntityRef[]; /** Last replay error snapshot captured before exhaustion. */
644
- lastReplayError: {
645
- message: string;
646
- }; /** Resolution creation timestamp. */
647
- createdAt: number; /** Resolution update timestamp. */
648
- updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
649
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
650
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
651
- dependencyUploadIds?: string[];
652
- };
653
- /**
654
- * Persisted resolution record created when replay retries are exhausted, plus
655
- * derived dependency metadata.
656
- *
657
- * @typeParam TInput - Original mutation input associated with the replay failure.
658
- */
659
- type OfflineRetryExhaustedResolutionRecord<TInput = unknown> = OfflineRetryExhaustedResolutionRecordBase<TInput> & OfflineResolutionDependencyMetadata;
660
- /**
661
- * Persisted offline resolution payload.
662
- *
663
- * @typeParam TConflict - Conflict payload stored for later resolution.
664
- * @typeParam TInput - Original mutation input associated with the resolution.
665
- */
666
- type OfflineResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecord<TConflict, TInput> | OfflineRetryExhaustedResolutionRecord<TInput>;
667
- /** Session-scoped offline controller shared across stores in the same session. */
668
- type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
669
- /** Returns the active session key used to scope shared offline state. */getSessionKey: () => string | false; /** Shared static session configuration used by attached stores. */
670
- getConfig: () => OfflineSessionConfig<TUploadRef>; /** Latest effective runtime config for this session. */
671
- getOfflineRuntimeConfig: () => OfflineRuntimeConfig; /** Updates runtime controls for this session. */
672
- setOfflineRuntimeConfig: (update: OfflineRuntimeConfigUpdate) => void; /** Resets runtime controls back to the static session config. */
673
- resetOfflineRuntimeConfig: () => void; /** Returns the latest global offline status for the session. */
674
- getOfflineStatus: () => GlobalOfflineStatus; /** Returns the latest aggregated offline entities for the session. */
675
- getOfflineEntities: () => readonly GlobalOfflineEntity[]; /** Returns the latest aggregated conflict/retry resolutions for the session. */
676
- getOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns the latest session-scoped offline uploads for the session. */
677
- getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
678
- resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
679
- resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
680
- saveOfflineUpload: (args: {
681
- id: string;
682
- file: Blob | File;
683
- }) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
684
- replaceOfflineUpload: (args: {
685
- id: string;
686
- file: Blob | File;
687
- }) => Promise<void>; /** Loads a previously stored session-scoped upload. */
688
- loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
689
- deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
690
- useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
691
- useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to the session's aggregated conflict/retry resolutions. */
692
- useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the session's upload list. */
693
- useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
694
- };
695
- /**
696
- * Persisted offline mutation queue entry.
697
- *
698
- * @typeParam TInput - Serialized input payload for the queued mutation.
699
- * @typeParam TConflict - Conflict payload that may be attached while waiting for confirmation or resolution.
700
- */
701
- type OfflineQueueEntry<TInput = unknown, TConflict = unknown> = {
702
- /** Queue entry identifier. */id: string; /** Session key for queue scoping. */
703
- sessionKey: string; /** Store name where operation is defined. */
704
- storeName: string; /** Store type for this queued operation. */
705
- storeType: OfflineStoreType; /** Operation name registered in offline configuration. */
706
- operation: string; /** Operation input payload persisted with the entry. */
707
- input: TInput; /** Stable ordering key used to replay queued operations deterministically. */
708
- queueOrder: number; /** Entity references tied to this mutation. */
709
- entityRefs: OfflineEntityRef[]; /** Number of execution attempts so far. */
710
- attempts: number; /** Queue entry creation timestamp. */
711
- createdAt: number; /** Last entry update timestamp. */
712
- updatedAt: number; /** Timestamp of last execution attempt, if any. */
713
- lastAttemptAt: number | null; /** Synchronization state for this entry. */
714
- syncState: OfflineSyncState; /** Optional temporary IDs for optimistic create operations. */
715
- tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
716
- attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
717
- dependencyUploadIds?: string[]; /** Last recorded sync error if replay failed. */
718
- lastError?: {
719
- message: string;
720
- };
721
- /**
722
- * Whether a `needs-confirmation` entry may auto-resend during healthy replay
723
- * retries after confirmation checks finish.
724
- */
725
- allowReplayRetry?: boolean; /** Pending conflict payload when confirmation or resolution is required. */
726
- pendingConflict?: TConflict;
727
- };
728
- /** Built-in resolution actions for retry exhaustion records. */
729
- type OfflineRetryExhaustedResolutionAction = {
730
- action: 'retry';
731
- /**
732
- * Controls whether retrying a resolution should also requeue retryable
733
- * descendants from the same temp-lifecycle dependency chain.
734
- * @default 'self-and-descendants'
735
- */
736
- scope?: 'self' | 'self-and-descendants';
737
- } | {
738
- action: 'discard';
739
- };
740
- /**
741
- * Built-in resolution actions for persisted conflict records.
742
- *
743
- * `commit` is intended for flows where the final API call has already been made
744
- * externally and the store only needs to clear bookkeeping plus reconcile any
745
- * temp-entity lifecycle using the accepted server result.
746
- *
747
- * @typeParam TInput - Input type expected when requeueing a replacement mutation.
748
- * @typeParam TResult - Result shape returned by the external conflict resolution call.
749
- */
750
- type OfflineConflictResolutionAction<TInput = unknown, TResult = unknown> = {
751
- action: 'discard';
752
- } | {
753
- action: 'requeue';
754
- input: TInput;
755
- } | {
756
- action: 'commit';
757
- result?: TResult;
758
- };
759
- /**
760
- * Built-in resolution actions accepted by `resolveOfflineResolution(...)`.
761
- *
762
- * @typeParam TInput - Input type expected when requeueing a replacement mutation.
763
- * @typeParam TResult - Result shape returned by an externally completed conflict resolution call.
764
- */
765
- type OfflineResolutionAction<TInput = unknown, TResult = unknown> = OfflineRetryExhaustedResolutionAction | OfflineConflictResolutionAction<TInput, TResult>;
766
- /**
767
- * Extracts operation input type from a schema map.
768
- *
769
- * @typeParam TOperations - Operation registry to inspect.
770
- * @typeParam TName - Operation name whose input type should be extracted.
771
- */
772
- type OperationInput<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
773
- inputSchema: PersistentStorageSchema<infer TInput>;
774
- } ? TInput : never;
775
- /**
776
- * A typed operation descriptor for an offline mutation queue entry.
777
- *
778
- * @typeParam TOperations - Operation registry that defines valid operation names and input schemas.
779
- * @typeParam TName - Operation name to describe. Defaults to all operation names in the registry.
780
- */
781
- type OfflineMutationDescriptor<TOperations extends Record<string, {
782
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
783
- }>, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: {
784
- /** Operation key from the offline operations registry. */operation: K; /** Input resolved from the registered operation schema. */
785
- input: OperationInput<TOperations, K>;
786
- } }[TName];
787
- /**
788
- * Public offline mutation input accepted by store mutation APIs.
789
- *
790
- * Callers queue exactly one descriptor per mutation fallback.
791
- */
792
- type OfflineMutationInput<TOperations extends Record<string, {
793
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
794
- }>, TName extends keyof TOperations & string = keyof TOperations & string> = OfflineMutationDescriptor<TOperations, TName>;
795
- /**
796
- * Extracts operation result type from a registered operation map.
797
- *
798
- * @typeParam TOperations - Operation registry to inspect.
799
- * @typeParam TName - Operation name whose result type should be extracted.
800
- */
801
- type OperationResult<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
802
- execute: (...args: __LEGIT_ANY__[]) => infer TResult;
803
- } ? Awaited<TResult> : never;
804
- /**
805
- * Resolution action accepted for a specific registered offline operation.
806
- *
807
- * @typeParam TOperations - Operation registry to inspect.
808
- * @typeParam TName - Operation name whose resolution payload should be extracted.
809
- */
810
- type OfflineResolutionActionForOperation<TOperations, TName extends keyof TOperations> = OfflineResolutionAction<OperationInput<TOperations, TName>, OperationResult<TOperations, TName>>;
811
- /**
812
- * Context passed into offline mutation accumulation hooks.
813
- *
814
- * @typeParam TInput - Input type shared by the existing and incoming queued mutations.
815
- */
816
- type OfflineAccumulationMergeContext<TInput> = {
817
- /** Session key used to isolate queued mutations. */sessionKey: string; /** Existing input already present in queue. */
818
- existingInput: TInput; /** Incoming input for merge attempt. */
819
- incomingInput: TInput;
820
- };
821
- /**
822
- * Optional in-memory accumulation strategy for queued offline mutations.
823
- *
824
- * @typeParam TInput - Input type that will be merged and revalidated before persisting.
825
- */
826
- type OfflineAccumulationConfig<TInput> = {
827
- /** Merge function for combining existing and incoming mutation inputs. */mergeInput: (ctx: OfflineAccumulationMergeContext<TInput>) => Promise<TInput> | TInput;
828
- };
829
- /**
830
- * Optional queue-pruning strategy for queued offline mutations.
831
- *
832
- * `same-entity` only applies to operations that resolve exactly one entity ref.
833
- * When enabled, the new operation may remove earlier unattempted pending entries
834
- * targeting that same single entity before the new entry is persisted.
835
- */
836
- type OfflineSupersedeConfig = {
837
- /** Drop earlier unattempted pending entries for the same single entity. */scope: 'same-entity';
838
- /**
839
- * Limits which earlier operations may be pruned for that entity.
840
- *
841
- * Omit this to prune every earlier pending operation for the entity,
842
- * use `'self'` to prune only earlier entries of the current operation,
843
- * or provide explicit operation names to target a specific related set.
844
- */
845
- operations?: 'self' | readonly string[];
846
- /**
847
- * When the pruned entries include a temp-entity lifecycle, drop the current
848
- * operation itself instead of persisting a replacement entry.
849
- */
850
- dropSelfIfTempLifecycleCancelled?: boolean;
851
- };
852
- /** Shared context passed to offline replay lifecycle hooks. */
853
- type OperationBaseContext<TInput> = {
854
- /** Input payload for the queued mutation currently being processed. */input: TInput; /** Timestamp when the operation was originally enqueued. */
855
- enqueuedAt: number; /** Timestamp when the queued entry or conflict record was last updated. */
856
- updatedAt: number;
857
- /**
858
- * Resolves a previously temp-backed entity ref to its latest known final ref
859
- * when one has been reconciled.
860
- */
861
- resolveEntityRef: <TEntityRef extends ValidPayload>(entityRef: TEntityRef) => TEntityRef;
862
- };
863
- type OperationExecuteContext<TInput, TUploadRef extends ValidPayload = ValidPayload> = OperationBaseContext<TInput> & {
864
- uploads: OfflineOperationUploadsContext<TUploadRef>;
865
- };
866
- /** Context passed to the post-replay success hook after `execute(...)` settles. */
867
- type OfflineOperationExecuteSuccessContext<TInput, TResult> = OperationBaseContext<TInput> & {
868
- /** Replay result returned by `execute(...)`. */result: TResult;
869
- };
870
- /**
871
- * Optional callback used to synchronize UI/cache state after a successful
872
- * offline replay execute.
873
- */
874
- type OfflineOperationExecuteSuccessHandler<TInput, TResult> = (ctx: OfflineOperationExecuteSuccessContext<TInput, TResult>) => Promise<void> | void;
875
- type IsUnknown<T> = unknown extends T ? [keyof T] extends [never] ? true : false : false;
876
- /** Context passed to replay checks that may use a fresh server snapshot. */
877
- type OperationReplayCheckContext<TInput, TServerSnapshot> = OperationBaseContext<TInput> & {
878
- /**
879
- * Optional snapshot fetched immediately before `shouldSkipSync` and
880
- * `detectConflict`.
881
- */
882
- serverSnapshot: IsUnknown<TServerSnapshot> extends true ? undefined : TServerSnapshot;
883
- };
884
- /**
885
- * Conflict hook configuration for a queued offline operation.
886
- *
887
- * @typeParam TInput - Input type of the queued operation being checked and potentially requeued.
888
- * @typeParam TConflict - Conflict payload produced by detection and persisted for later external resolution.
889
- */
890
- type OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot = unknown> = {
891
- /** Schema used to validate and sanitize persisted conflict payloads. */schema: PersistentStorageSchema<TConflict>;
892
- /**
893
- * Inspect remote state before replaying the mutation and return conflict payload
894
- * when the queued mutation can no longer be applied safely.
895
- */
896
- detectConflict: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<TConflict | false | null> | TConflict | false | null;
897
- };
898
- type ConflictHandlingField<TInput, TConflict, TServerSnapshot> = IsUnknown<TConflict> extends true ? {
899
- /**
900
- * Optional conflict strategy when a queued operation diverges from remote state.
901
- */
902
- conflictHandling?: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
903
- } : {
904
- /**
905
- * Conflict strategy required when the operation declares a concrete
906
- * conflict payload type.
907
- */
908
- conflictHandling: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
909
- };
910
- type ServerSnapshotField<TInput, TServerSnapshot> = IsUnknown<TServerSnapshot> extends true ? {
911
- /**
912
- * Optionally loads a fresh server-side snapshot before replay checks run.
913
- * The result is passed to `shouldSkipSync` and `detectConflict` as
914
- * `ctx.serverSnapshot`.
915
- */
916
- getServerSnapshot?: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
917
- } : {
918
- /**
919
- * Required when the operation declares a concrete server snapshot type.
920
- * The result is passed to `shouldSkipSync` and `detectConflict` as
921
- * `ctx.serverSnapshot`.
922
- */
923
- getServerSnapshot: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
924
- };
925
- /**
926
- * Replacement data returned by `tempEntity.reconcileServerEntity(...)`.
927
- *
928
- * @typeParam TFinalPayload - Final payload that should replace the temporary one.
929
- * @typeParam TFinalData - Optional replacement entity data for the final payload.
930
- */
931
- type OfflineTempEntityReconciliation<TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
932
- /** Final payload that should replace the temporary optimistic one. */finalPayload: TFinalPayload;
933
- /**
934
- * Optional replacement data for the final payload.
935
- * Omit this to keep the current optimistic entity data and only swap the
936
- * payload/identity.
937
- */
938
- finalData?: TFinalData;
939
- };
940
- /**
941
- * Replacement data returned by `tempEntities.reconcileServerEntities(...)`.
942
- *
943
- * @typeParam TTempId - Temporary payload that should be reconciled.
944
- * @typeParam TFinalPayload - Final payload that should replace the temporary one.
945
- * @typeParam TFinalData - Optional replacement entity data for the final payload.
946
- */
947
- type OfflineTempEntitiesReconciliation<TTempId extends ValidPayload = ValidPayload, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = OfflineTempEntityReconciliation<TFinalPayload, TFinalData> & {
948
- /** Temporary payload that should be reconciled. */tempId: TTempId;
949
- };
950
- /**
951
- * Pending temp-entity returned by `tempEntities.buildPendingEntities(...)`.
952
- *
953
- * @typeParam TTempId - Temporary payload used to track the optimistic entity.
954
- * @typeParam TPendingEntity - Pending entity snapshot to insert locally.
955
- */
956
- type OfflineTempEntityPendingEntry<TTempId extends ValidPayload = ValidPayload, TPendingEntity = unknown> = {
957
- /** Temporary payload that identifies the optimistic entity. */tempId: TTempId; /** Pending entity snapshot inserted while the mutation is queued. */
958
- pendingEntity: TPendingEntity;
959
- };
960
- /**
961
- * Optional temp-id lifecycle for optimistic offline create flows.
962
- *
963
- * @typeParam TInput - Input type used to derive the temporary entity and identifier.
964
- * @typeParam TTempResult - Result returned by `execute`, used only by `tempEntity.reconcileServerEntity(...)`.
965
- * @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
966
- */
967
- type OfflineTempEntityConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
968
- /**
969
- * Builds the optimistic entity inserted into local state while the mutation
970
- * is queued offline.
971
- *
972
- * `tempId` is the temporary payload used to identify the optimistic entity
973
- * until replay succeeds and the final server entity can replace it.
974
- */
975
- buildPendingEntity: (input: TInput, tempId: TTempId) => TPendingEntity;
976
- /**
977
- * Reconciles the optimistic temp entity with the successful replay result.
978
- */
979
- reconcileServerEntity: (result: TTempResult, tempId: TTempId) => OfflineTempEntityReconciliation<TFinalPayload, TFinalData>;
980
- };
981
- /**
982
- * Optional temp-id lifecycle for optimistic offline batch-create flows.
983
- *
984
- * @typeParam TInput - Input type used to derive the temporary entities and identifiers.
985
- * @typeParam TTempResult - Result returned by `execute`, used only by `tempEntities.reconcileServerEntities(...)`.
986
- * @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
987
- */
988
- type OfflineTempEntitiesConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
989
- /**
990
- * Builds the optimistic entities inserted into local state while the mutation
991
- * is queued offline.
992
- *
993
- * `tempIds` are the temporary payloads derived from the operation entity refs
994
- * and used until replay succeeds and the final server entities can replace them.
995
- */
996
- buildPendingEntities: (input: TInput, tempIds: readonly TTempId[]) => readonly OfflineTempEntityPendingEntry<TTempId, TPendingEntity>[];
997
- /**
998
- * Reconciles the optimistic temp entities with the successful replay result.
999
- */
1000
- reconcileServerEntities: (result: TTempResult, tempIds: readonly TTempId[]) => readonly OfflineTempEntitiesReconciliation<TTempId, TFinalPayload, TFinalData>[];
1001
- };
1002
- type NoTempEntityFields = {
1003
- tempEntity?: never;
1004
- tempEntities?: never;
1005
- };
1006
- type ConfiguredTempEntityFields<TInput, TTempResult, TTempId extends ValidPayload, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
1007
- tempEntity: OfflineTempEntityConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
1008
- tempEntities?: never;
1009
- } | {
1010
- tempEntity?: never;
1011
- tempEntities: OfflineTempEntitiesConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
1012
- };
1013
- /**
1014
- * Shape used by `persistentStorage.offline.operations` for each operation name.
1015
- *
1016
- * @typeParam TInput - The persisted input payload for the queued offline operation.
1017
- * @typeParam TConflict - The conflict payload produced by pre-execution conflict detection.
1018
- * @typeParam TTempResult - Result returned by `execute`, used only when `tempEntity` or `tempEntities` needs to reconcile the final server entity. Defaults to `void`.
1019
- */
1020
- type OfflineOperationDefinition<TInput, TConflict, TTempResult = void, TServerSnapshot = unknown, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown, TUploadRef extends ValidPayload = ValidPayload> = {
1021
- /** Schema used to validate incoming operation input. */inputSchema: PersistentStorageSchema<TInput>; /** Lifecycle classification for the queued operation. */
1022
- kind: OfflineOperationKind;
1023
- /**
1024
- * Optional queue pruning for newer operations that supersede older queued work.
1025
- *
1026
- * This is mutually exclusive with `accumulation`.
1027
- */
1028
- supersedes?: OfflineSupersedeConfig;
1029
- /**
1030
- * Executes the queued mutation against the remote source during replay.
1031
- * This may run multiple times when transient failures occur.
1032
- */
1033
- execute: (ctx: OperationExecuteContext<TInput, TUploadRef>) => Promise<TTempResult> | TTempResult;
1034
- /**
1035
- * Optional check executed before retrying a previously failed sync attempt.
1036
- * Return `true` to drop the queued entry because the remote side already reflects it.
1037
- * Return `false` to continue with normal replay.
1038
- */
1039
- shouldSkipSync?: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<boolean> | boolean;
1040
- } & ConflictHandlingField<TInput, TConflict, TServerSnapshot> & ServerSnapshotField<TInput, TServerSnapshot> & (({
1041
- /**
1042
- * Explicit store-sync step that runs after `execute(...)` succeeds during
1043
- * offline replay.
1044
- *
1045
- * Provide a callback when replay should update the live store after the
1046
- * server-side execute succeeds.
1047
- */
1048
- onSuccessExecute: OfflineOperationExecuteSuccessHandler<TInput, TTempResult>;
1049
- /**
1050
- * Optional queue compaction for consecutive mutations with same refs.
1051
- */
1052
- accumulation?: OfflineAccumulationConfig<TInput>;
1053
- } & NoTempEntityFields) | ({
1054
- /**
1055
- * Temp-entity operations already reconcile the live store through
1056
- * `tempEntity` / `tempEntities`, so they must not declare an extra
1057
- * success sync callback.
1058
- */
1059
- onSuccessExecute?: undefined; /** Temp-entity operations cannot compact multiple queued creates. */
1060
- accumulation?: never;
1061
- } & ConfiguredTempEntityFields<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>));
1062
- type WithoutTempEntity<T extends {
1063
- tempEntity?: unknown;
1064
- tempEntities?: unknown;
1065
- }> = Omit<T, 'tempEntity' | 'tempEntities'> & {
1066
- /** Document stores do not support optimistic temp entities. */tempEntity?: never; /** Document stores do not support optimistic batch temp entities. */
1067
- tempEntities?: never;
1068
- };
1069
- /** Context used to resolve which entities a queued mutation affects. */
1070
- type OperationEntityRefsContext<TInput> = {
1071
- /** Input payload for the queued mutation. */input: TInput;
1072
- };
1073
- /** Non-store-specific offline operation definition alias. */
1074
- type AnyOfflineOperationDefinition<TUploadRef extends ValidPayload = ValidPayload> = {
1075
- inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
1076
- kind: OfflineOperationKind;
1077
- conflictHandling?: {
1078
- schema: PersistentStorageSchema<__LEGIT_ANY__>;
1079
- detectConflict: (ctx: __LEGIT_ANY__) => unknown;
1080
- };
1081
- accumulation?: OfflineAccumulationConfig<__LEGIT_ANY__>;
1082
- supersedes?: OfflineSupersedeConfig;
1083
- tempEntity?: OfflineTempEntityConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
1084
- tempEntities?: OfflineTempEntitiesConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
1085
- getServerSnapshot?: (ctx: OperationBaseContext<__LEGIT_ANY__>) => unknown;
1086
- execute: (ctx: OperationExecuteContext<__LEGIT_ANY__, TUploadRef>) => unknown;
1087
- onSuccessExecute?: OfflineOperationExecuteSuccessHandler<__LEGIT_ANY__, __LEGIT_ANY__>;
1088
- shouldSkipSync?: (ctx: OperationReplayCheckContext<__LEGIT_ANY__, __LEGIT_ANY__>) => Promise<boolean> | boolean;
1089
- } & {
1090
- getEntityRefs?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => unknown[];
1091
- dependsOn?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => __LEGIT_ANY__[];
1092
- dependsOnUploads?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => string[];
1093
- };
1094
- /**
1095
- * Compact type-spec helper for a single offline operation.
1096
- *
1097
- * Use this helper with {@link DefineDocumentOfflineOperations} to describe each
1098
- * operation using generic parameters instead of inline object literals.
1099
- *
1100
- * The generic order is `input`, `conflict`, `temp result`, then `server snapshot`.
1101
- *
1102
- * @typeParam TInput - Input payload accepted by the operation.
1103
- * @typeParam TConflict - Conflict payload produced by optional conflict handling.
1104
- * @typeParam TTempResult - Result returned by `execute`, also reused when externally committed conflict resolution needs temp-entity reconciliation.
1105
- *
1106
- * @example
1107
- * ```ts
1108
- * type UpdateName = DefineOfflineOperation<
1109
- * { name: string },
1110
- * { remoteName: string },
1111
- * { name: string }
1112
- * >;
1113
- * ```
1114
- */
1115
- type DefineOfflineOperation<TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown> = {
1116
- /** Input type accepted by the operation. */input?: TInput; /** Conflict payload type produced by the optional conflict handler. */
1117
- conflict?: TConflict; /** Result returned by `execute`, also reused by externally committed conflict resolution for temp-entity reconciliation. */
1118
- result?: TTempResult; /** Snapshot type returned by `getServerSnapshot` and exposed to replay checks. */
1119
- serverSnapshot?: TServerSnapshot;
1120
- };
1121
- type DocumentOperationInput<TOptions extends DefineOfflineOperation> = TOptions extends {
1122
- input?: infer TInput;
1123
- } ? TInput : unknown;
1124
- type DocumentOperationConflict<TOptions extends DefineOfflineOperation> = TOptions extends {
1125
- conflict?: infer TConflict;
1126
- } ? TConflict : unknown;
1127
- type DocumentOperationResult<TOptions extends DefineOfflineOperation> = TOptions extends {
1128
- result?: infer TTempResult;
1129
- } ? TTempResult : unknown;
1130
- type DocumentOperationServerSnapshot<TOptions extends DefineOfflineOperation> = TOptions extends {
1131
- serverSnapshot?: infer TServerSnapshot;
1132
- } ? TServerSnapshot : unknown;
1133
- /**
1134
- * Document-store specific offline operation definition.
1135
- *
1136
- * Prefer this alias when manually typing a single operation inside
1137
- * `persistentStorage.offline.operations` for a document store.
1138
- *
1139
- * `TOptions` is usually provided with {@link DefineOfflineOperation}, which lets
1140
- * callers specify the queued `input`, replay `result`, and optional `conflict`
1141
- * payload concisely. Document stores do not support `tempEntity`.
1142
- *
1143
- * Omitted properties default to `unknown`.
1144
- *
1145
- * @typeParam State - Document state type for the owning store.
1146
- * @typeParam TOptions - Operation typing options, usually created with {@link DefineOfflineOperation}.
1147
- *
1148
- * @example
1149
- * ```ts
1150
- * type RenameOperation = DocumentOfflineOperationDefinition<
1151
- * UserDoc,
1152
- * DefineOfflineOperation<
1153
- * { name: string },
1154
- * { remoteName: string },
1155
- * { name: string }
1156
- * >
1157
- * >;
1158
- * ```
1159
- */
1160
- type DocumentOfflineOperationDefinition<State extends ValidStoreState, TOptions extends DefineOfflineOperation = DefineOfflineOperation, TUploadRef extends ValidPayload = ValidPayload> = WithoutTempEntity<OfflineOperationDefinition<DocumentOperationInput<TOptions>, DocumentOperationConflict<TOptions>, DocumentOperationResult<TOptions>, DocumentOperationServerSnapshot<TOptions>, string, unknown, ValidPayload, unknown, TUploadRef>> & {
1161
- /** Declares which upload ids must finish before replaying this operation. */dependsOnUploads?: (ctx: OperationEntityRefsContext<DocumentOperationInput<TOptions>>) => string[];
1162
- } & ([State] extends [never] ? never : unknown);
1163
- /**
1164
- * Builds a document offline operations map from a compact operation spec.
1165
- *
1166
- * This is the recommended way to type a document store's full offline operation map.
1167
- * Each operation key is typically described with {@link DefineOfflineOperation},
1168
- * and this helper expands that into the full
1169
- * {@link DocumentOfflineOperationDefinition} map expected by the store.
1170
- *
1171
- * @typeParam State - Document state type for the owning store.
1172
- * @typeParam TOperations - Operation map where each key declares its input, replay result, and optional conflict payload.
1173
- *
1174
- * @example
1175
- * ```ts
1176
- * type Operations = DefineDocumentOfflineOperations<
1177
- * UserDoc,
1178
- * {
1179
- * updateName: DefineOfflineOperation<
1180
- * { name: string },
1181
- * unknown,
1182
- * { name: string }
1183
- * >;
1184
- * archive: DefineOfflineOperation<
1185
- * { reason: string },
1186
- * { code: string }
1187
- * >;
1188
- * }
1189
- * >;
1190
- * ```
1191
- *
1192
- * Then use the resulting type as the `operations` object contract:
1193
- *
1194
- * ```ts
1195
- * const operations: Operations = {
1196
- * updateName: {
1197
- * inputSchema: z.object({ name: z.string() }),
1198
- * kind: 'update',
1199
- * execute: ({ input }) => ({ name: input.name }),
1200
- * },
1201
- * archive: {
1202
- * inputSchema: z.object({ reason: z.string() }),
1203
- * kind: 'delete',
1204
- * conflictHandling: {
1205
- * schema: z.object({ code: z.string() }),
1206
- * detectConflict: () => false,
1207
- * },
1208
- * execute: () => undefined,
1209
- * },
1210
- * };
1211
- * ```
1212
- */
1213
- type DefineDocumentOfflineOperations<State extends ValidStoreState, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: DocumentOfflineOperationDefinition<State, TOperations[TName], TUploadRef> };
1214
- /**
1215
- * Collection offline entity reference.
1216
- *
1217
- * Collection operations return raw item payloads, which are normalized to the
1218
- * internal item key by the store.
1219
- *
1220
- * @typeParam ItemPayload - Collection item payload type for the owning store.
1221
- */
1222
- type CollectionOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
1223
- /**
1224
- * Collection-store specific offline operation definition.
1225
- *
1226
- * @typeParam ItemState - Collection item state type for the owning store.
1227
- * @typeParam ItemPayloadUnused - Collection payload type used to anchor the operation to the owning store type.
1228
- * @typeParam TInput - Input type accepted by the offline operation.
1229
- * @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
1230
- * @typeParam TTempResult - Result returned by `execute`.
1231
- * When `tempEntity` or `tempEntities` is provided, the pending builders must
1232
- * return `ItemState`, and the reconciliation hooks must return an
1233
- * `ItemPayload` plus optional `ItemState` replacement data.
1234
- */
1235
- type CollectionOfflineOperationDefinition<ItemState extends ValidStoreState, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
1236
- /**
1237
- * Declares which collection items are affected by this queued mutation.
1238
- *
1239
- * Return the raw collection payloads for the affected items. The store will
1240
- * convert each payload with the configured item key logic.
1241
- */
1242
- getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[];
1243
- /**
1244
- * Declares which collection item refs must resolve before replaying this
1245
- * operation.
1246
- */
1247
- dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
1248
- dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
1249
- } & ([ItemState | ItemPayloadUnused] extends [never] ? never : unknown);
1250
- /**
1251
- * Builds a collection offline operations map from a compact operation spec.
1252
- *
1253
- * Use this helper to define the full `persistentStorage.offline.operations` contract for a
1254
- * collection store while keeping each operation's type declaration short.
1255
- *
1256
- * Each operation key is described with {@link DefineOfflineOperation}, and this
1257
- * helper expands it into the corresponding
1258
- * {@link CollectionOfflineOperationDefinition}. The runtime operation object
1259
- * still needs to provide `getEntityRefs(...)`.
1260
- *
1261
- * @typeParam ItemState - Collection item state type for the owning store.
1262
- * @typeParam ItemPayload - Collection payload type for the owning store.
1263
- * @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
1264
- *
1265
- * @example
1266
- * ```ts
1267
- * type Operations = DefineCollectionOfflineOperations<
1268
- * TodoItem,
1269
- * string,
1270
- * {
1271
- * renameTodo: DefineOfflineOperation<
1272
- * { id: string; title: string }
1273
- * >;
1274
- * createTodo: DefineOfflineOperation<
1275
- * { title: string },
1276
- * unknown,
1277
- * { id: string; title: string }
1278
- * >;
1279
- * }
1280
- * >;
1281
- * ```
1282
- */
1283
- type DefineCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: CollectionOfflineOperationDefinition<ItemState, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
1284
- /**
1285
- * List-query offline entity reference.
1286
- *
1287
- * List-query operations return raw item payloads, which are normalized to the
1288
- * internal item key by the store.
1289
- *
1290
- * @typeParam ItemPayload - Item payload type for the owning list-query store.
1291
- */
1292
- type ListQueryOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
1293
- /**
1294
- * List-query-store specific offline operation definition.
1295
- *
1296
- * @typeParam ItemState - List item state type for the owning store.
1297
- * @typeParam QueryPayload - Query payload type used by the list store.
1298
- * @typeParam ItemPayloadUnused - Item payload type used to anchor the operation to the owning store type.
1299
- * @typeParam TInput - Input type accepted by the offline operation.
1300
- * @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
1301
- * @typeParam TTempResult - Result returned by `execute`.
1302
- * When `tempEntity` or `tempEntities` is provided, the pending builders must
1303
- * return `ItemState`, and the reconciliation hooks must return an
1304
- * `ItemPayload` plus optional `ItemState` replacement data.
1305
- */
1306
- type ListQueryOfflineOperationDefinition<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayloadUnused extends ValidPayload, TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown, TUploadRef extends ValidPayload = ValidPayload> = OfflineOperationDefinition<TInput, TConflict, TTempResult, TServerSnapshot, ItemPayloadUnused, ItemState, ItemPayloadUnused, ItemState, TUploadRef> & {
1307
- /**
1308
- * Declares which list-query entities are affected by this queued mutation.
1309
- *
1310
- * Return the raw item payloads for the affected items. The store will
1311
- * convert each payload with the configured item key logic.
1312
- */
1313
- getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[];
1314
- /**
1315
- * Declares which list item refs must resolve before replaying this
1316
- * operation.
1317
- */
1318
- dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
1319
- dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
1320
- } & ([ItemState | QueryPayload | ItemPayloadUnused] extends [never] ? never : unknown);
1321
- /**
1322
- * Builds a list-query offline operations map from a compact operation spec.
1323
- *
1324
- * Use this helper to define the full `persistentStorage.offline.operations` contract for a
1325
- * list-query store while keeping each operation's type declaration short.
1326
- *
1327
- * Each operation key is described with {@link DefineOfflineOperation}, and this
1328
- * helper expands it into the corresponding
1329
- * {@link ListQueryOfflineOperationDefinition}. The runtime operation object
1330
- * still needs to provide `getEntityRefs(...)`.
1331
- *
1332
- * @typeParam ItemState - List item state type for the owning store.
1333
- * @typeParam QueryPayload - Query payload type used by the list store.
1334
- * @typeParam ItemPayload - Item payload type used by the list store.
1335
- * @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
1336
- *
1337
- * @example
1338
- * ```ts
1339
- * type Operations = DefineListQueryOfflineOperations<
1340
- * User,
1341
- * { tableId: 'users' },
1342
- * { tableId: 'users'; id: number } | string,
1343
- * {
1344
- * renameUser: DefineOfflineOperation<
1345
- * { id: number; name: string }
1346
- * >;
1347
- * createUser: DefineOfflineOperation<
1348
- * { name: string },
1349
- * unknown,
1350
- * { id: number; name: string }
1351
- * >;
1352
- * }
1353
- * >;
1354
- * ```
1355
- */
1356
- type DefineListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: ListQueryOfflineOperationDefinition<ItemState, QueryPayload, ItemPayload, DocumentOperationInput<TOperations[TName]>, DocumentOperationConflict<TOperations[TName]>, DocumentOperationResult<TOperations[TName]>, DocumentOperationServerSnapshot<TOperations[TName]>, TUploadRef> };
1357
- /**
1358
- * Extracts operation conflict payload from a registered operation map.
1359
- *
1360
- * @typeParam TOperations - Operation registry to inspect.
1361
- * @typeParam TName - Operation name whose conflict payload should be extracted.
1362
- */
1363
- type OperationConflict<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
1364
- conflictHandling?: OfflineConflictHandlingConfig<__LEGIT_ANY__, infer TConflict>;
1365
- } ? TConflict : never;
1366
- /**
1367
- * Result returned when decoding a stored offline conflict payload.
1368
- *
1369
- * `ok: true` contains the typed conflict payload. `ok: false` contains a
1370
- * machine-readable parse error describing why decoding was not possible.
1371
- */
1372
- type ParsedOfflineResolutionConflictResultForOperation<TOperations, TName extends keyof TOperations & string> = Result<OperationConflict<TOperations, TName>, OfflineResolutionConflictParseError>;
1373
- type ParsedOfflineResolutionConflictResultForStore<TOperations> = ParsedOfflineResolutionConflictResultForOperation<TOperations, keyof TOperations & string>;
1374
- /**
1375
- * Operation-aware offline resolution record for a specific registered operation.
1376
- *
1377
- * @typeParam TOperations - Operation registry to inspect.
1378
- * @typeParam TName - Operation name whose stored resolution shape should be extracted.
1379
- */
1380
- type OfflineResolutionRecordForOperation<TOperations, TName extends keyof TOperations & string> = (OfflineConflictResolutionRecord<OperationConflict<TOperations, TName>, OperationInput<TOperations, TName>> & {
1381
- operation: TName;
1382
- }) | (OfflineRetryExhaustedResolutionRecord<OperationInput<TOperations, TName>> & {
1383
- operation: TName;
1384
- });
1385
- /**
1386
- * Union of operation-aware offline resolution records for an operation registry.
1387
- *
1388
- * @typeParam TOperations - Operation registry to inspect.
1389
- * @typeParam TName - Optional subset of operation names to include.
1390
- */
1391
- type OfflineResolutionRecordForStore<TOperations, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: OfflineResolutionRecordForOperation<TOperations, K> }[TName];
1392
- type OfflineResolutionConflictParseErrorCode = 'not-conflict' | 'offline-not-configured' | 'operation-not-found' | 'conflict-handling-missing' | 'invalid-conflict-payload';
1393
- /** Error returned when decoding a stored offline conflict payload fails. */
1394
- declare class OfflineResolutionConflictParseError extends Error {
1395
- code: OfflineResolutionConflictParseErrorCode;
1396
- operation: string;
1397
- kind?: OfflineResolutionRecord['kind'];
1398
- rawValue?: unknown;
1399
- validationError?: SchemaValidationError;
1400
- constructor(args: {
1401
- code: OfflineResolutionConflictParseErrorCode;
1402
- operation: string;
1403
- kind?: OfflineResolutionRecord['kind'];
1404
- rawValue?: unknown;
1405
- validationError?: SchemaValidationError;
1406
- });
1407
- }
1408
- //#endregion
1409
8
  //#region src/persistentStorage/offline/mutationRuntime.d.ts
1410
9
  /**
1411
10
  * Successful result of an offline-enabled mutation attempt.
@@ -1492,48 +91,18 @@ type CreateStoreManagerOptions<TUploadRef extends ValidPayload = ValidPayload> =
1492
91
  };
1493
92
  declare function createStoreManager<TUploadRef extends ValidPayload = ValidPayload>(options: CreateStoreManagerOptions<TUploadRef>): StoreManager<TUploadRef>;
1494
93
  //#endregion
1495
- //#region src/utils/browserTabsPriority.d.ts
1496
- type BrowserTabsPriorityTimings = {
1497
- heartbeatMs?: number;
1498
- presenceTtlMs?: number;
1499
- fetchLeaseMs?: number | ((lastFetchDuration: number) => number);
1500
- };
1501
- type BrowserTabsTabStatusMessage = {
1502
- kind: 'tab-status';
1503
- isFocused: boolean;
1504
- lastFocusedAt: number;
1505
- lastPresenceAt: number;
1506
- };
1507
- //#endregion
1508
- //#region src/utils/browserTabsSync.d.ts
1509
- type BrowserTabsStoreType = 'document' | 'collection' | 'listQuery' | 'offline';
1510
- type BrowserTabsTransport = {
1511
- postMessage: (message: unknown) => void;
1512
- close: () => void;
1513
- };
1514
- type BrowserTabsTransportFactory = (options: {
1515
- channelName: string;
1516
- onMessage: (message: unknown) => void;
1517
- }) => BrowserTabsTransport | null;
1518
- type BrowserTabsMessageMeta = {
1519
- protocolVersion: 1;
1520
- messageId: string;
1521
- storeType: BrowserTabsStoreType;
1522
- sessionKey: string;
1523
- tabId: string;
1524
- seq: number;
1525
- sentAt: number;
1526
- };
1527
- type SnapshotConsistency = 'optimistic' | 'confirmed';
1528
- //#endregion
1529
94
  //#region src/collectionStore/useMultipleItems.d.ts
1530
95
  type UseMultipleItemsOptions$1<ItemState extends ValidStoreState, Selected> = {
1531
- selector?: (data: ItemState | null) => Selected;
1532
- returnIdleStatus?: boolean;
1533
- returnRefetchingStatus?: boolean;
1534
- omitPayload?: boolean; /** Only loads the data if it is not already loaded and skip any other refetches */
1535
- disableRefetches?: boolean;
1536
- disableRefetchOnMount?: boolean;
96
+ /** 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. */
97
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
98
+ returnRefetchingStatus?: boolean; /** Omits `payload` from each query result unless overridden per item. */
99
+ omitPayload?: boolean;
100
+ /**
101
+ * Only fetches when an item is missing from state, skipping stale-state and
102
+ * invalidation refetches.
103
+ */
104
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
105
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
1537
106
  isOffScreen?: boolean;
1538
107
  /**
1539
108
  * Debounces automatic fetches caused by payload changes, while selection
@@ -1575,13 +144,17 @@ type TSFDUseCollectionItemReturn<Selected, ItemPayload, QueryMetadata extends un
1575
144
  queryMetadata: QueryMetadata;
1576
145
  };
1577
146
  type CollectionUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
1578
- payload: ItemPayload;
1579
- queryMetadata?: QueryMetadata;
1580
- omitPayload?: boolean; /** Only loads the data if it is not already loaded and skip any other refetches */
1581
- disableRefetches?: boolean;
1582
- disableRefetchOnMount?: boolean;
1583
- returnIdleStatus?: boolean;
1584
- returnRefetchingStatus?: boolean;
147
+ /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload; /** Metadata returned with this query result for caller-side bookkeeping. */
148
+ queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
149
+ omitPayload?: boolean;
150
+ /**
151
+ * Only fetches when the item is missing from state, skipping stale-state and
152
+ * invalidation refetches.
153
+ */
154
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
155
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the item has not been fetched. */
156
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
157
+ returnRefetchingStatus?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
1585
158
  isOffScreen?: boolean;
1586
159
  };
1587
160
  type OnCollectionItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
@@ -1589,10 +162,6 @@ type OnCollectionItemInvalidate<ItemState extends ValidStoreState, ItemPayload e
1589
162
  payload: ItemPayload;
1590
163
  priority: FetchType;
1591
164
  }) => void;
1592
- type CollectionInitialStateItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
1593
- payload: ItemPayload;
1594
- data: ItemState;
1595
- };
1596
165
  type CollectionStoreStoreEvents<ItemPayload extends ValidPayload> = {
1597
166
  /** Emitted when a mutation begins executing */mutationStart: {
1598
167
  mutationId: number;
@@ -1613,23 +182,6 @@ type CollectionStateCleanup<ItemPayload extends ValidPayload> = {
1613
182
  itemKeys: string[];
1614
183
  payloads: ItemPayload[];
1615
184
  };
1616
- type CollectionBrowserTabsMessage<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
1617
- kind: 'collection-item-snapshot';
1618
- itemKey: string;
1619
- consistency: SnapshotConsistency;
1620
- item: TSFDCollectionItem<ItemState, ItemPayload> | null;
1621
- }) | (BrowserTabsMessageMeta & {
1622
- kind: 'fetch-start';
1623
- targetKey: string;
1624
- requestIds: string[];
1625
- startedAt: number;
1626
- }) | (BrowserTabsMessageMeta & {
1627
- kind: 'fetch-success';
1628
- targetKey: string;
1629
- requestIds: string[];
1630
- startedAt: number;
1631
- duration: number;
1632
- });
1633
185
  type InternalCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition & {
1634
186
  getEntityRefs: (ctx: {
1635
187
  input: __LEGIT_ANY__;
@@ -1752,22 +304,22 @@ type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends Vali
1752
304
  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>[];
1753
305
  useItem: <Selected = ItemState | null>(payload: ItemPayload | undefined | false | null, options?: UseItemOptions$1<ItemState, Selected>) => TSFDUseCollectionItemReturn<Selected, ItemPayload>;
1754
306
  useListItemIsLoading: (payload: ItemPayload, args: {
1755
- itemId: string;
1756
- selector: (data: ItemState | null) => unknown;
1757
- loadItemFallback?: () => void;
307
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
308
+ selector: (data: ItemState | null) => unknown; /** Called if the sub-item is still missing and no refetch is in progress. */
309
+ loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1758
310
  ensureIsLoaded?: boolean;
1759
311
  }) => boolean;
1760
312
  useListItemIsDeleted: (payload: ItemPayload, args: {
1761
- itemId: string;
1762
- selector: (data: ItemState | null) => unknown;
1763
- onDelete?: () => void;
313
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts the sub-item from the collection item data. */
314
+ selector: (data: ItemState | null) => unknown; /** Called once when deletion is detected. */
315
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1764
316
  ensureIsLoaded?: boolean;
1765
317
  }) => boolean;
1766
318
  useListItem: <Selected>(payload: ItemPayload, args: {
1767
- itemId: string;
1768
- selector: (data: ItemState | null) => Selected;
1769
- loadItemFallback?: () => void;
1770
- onDelete?: () => void;
319
+ /** Unique identifier of the sub-item within the collection item. */itemId: string; /** Extracts and maps the sub-item from the collection item data. */
320
+ selector: (data: ItemState | null) => Selected; /** Called if the sub-item is still missing and no refetch is in progress. */
321
+ loadItemFallback?: () => void; /** Called once when deletion is detected. */
322
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1771
323
  ensureIsLoaded?: boolean;
1772
324
  }) => {
1773
325
  isLoading: boolean;
@@ -1798,29 +350,7 @@ type CollectionStore<ItemState extends ValidStoreState, ItemPayload extends Vali
1798
350
  performMutation: CollectionPerformMutation<ItemState, ItemPayload, TOfflineOperations>;
1799
351
  onTransportReconnect: () => void;
1800
352
  };
1801
- declare function createCollectionStore<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null, StorageState = unknown>({
1802
- id,
1803
- storeManager,
1804
- fetchFn,
1805
- batchFetchFn,
1806
- getItemsBatchKey,
1807
- maxBatchSize,
1808
- maxItems,
1809
- onStateCleanup,
1810
- lowPriorityThrottleMs: storeLowPriorityThrottleMs,
1811
- baseCoalescingWindowMs: storeBaseCoalescingWindowMs,
1812
- mediumPriorityDelayMs,
1813
- dynamicRealtimeThrottleMs,
1814
- revalidateOnWindowFocus,
1815
- transportReconnectCooldownMs,
1816
- getCollectionItemKey: filterCollectionItemObjKey,
1817
- onInvalidate,
1818
- onSchedulerEvent,
1819
- onMutationError,
1820
- usesRealTimeUpdates,
1821
- persistentStorage: persistentStorageConfig,
1822
- '~test': testOptions
1823
- }: CollectionStoreOptions<ItemState, ItemPayload, TOfflineOperations, StorageState>): CollectionStore<ItemState, ItemPayload, TOfflineOperations>;
353
+ 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>;
1824
354
  //#endregion
1825
355
  //#region src/documentStore.d.ts
1826
356
  type DocumentStatus = 'idle' | TSDFStatus;
@@ -1850,22 +380,6 @@ type DocumentStoreStoreEvents = {
1850
380
  status: 'success' | 'error' | 'skipped';
1851
381
  };
1852
382
  };
1853
- type DocumentBrowserTabsMessage<State extends ValidStoreState> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
1854
- kind: 'document-snapshot';
1855
- consistency: SnapshotConsistency;
1856
- data: State | null;
1857
- }) | (BrowserTabsMessageMeta & {
1858
- kind: 'fetch-start';
1859
- targetKey: 'document';
1860
- requestIds: string[];
1861
- startedAt: number;
1862
- }) | (BrowserTabsMessageMeta & {
1863
- kind: 'fetch-success';
1864
- targetKey: 'document';
1865
- requestIds: string[];
1866
- startedAt: number;
1867
- duration: number;
1868
- });
1869
383
  type InternalDocumentOfflineOperations<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
1870
384
  type DocumentOfflineOperationsConfig<State extends ValidStoreState> = InternalDocumentOfflineOperations<State> | null;
1871
385
  type DocumentStoreOptions<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown> = {
@@ -1977,32 +491,40 @@ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends Doc
1977
491
  parseOfflineResolutionConflict: (resolution: OfflineResolutionRecord) => ParsedOfflineResolutionConflictResultForStore<ResolvedDocumentOfflineOperations<TOfflineOperations>>;
1978
492
  resolveOfflineResolution: <TName extends keyof ResolvedDocumentOfflineOperations<TOfflineOperations> & string>(resolutionId: string, operationName: TName, resolution: OfflineResolutionActionForOperation<ResolvedDocumentOfflineOperations<TOfflineOperations>, TName>) => Promise<void> | void;
1979
493
  useDocument: <Selected = State | null>(args?: {
1980
- selector?: (data: State | null) => Selected;
1981
- disabled?: boolean;
494
+ /** Maps the document data before it is returned from the hook. */selector?: (data: State | null) => Selected; /** Disables this hook subscription and prevents automatic fetches. */
495
+ disabled?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
1982
496
  isOffScreen?: boolean;
1983
- disableRefetches?: boolean;
1984
- disableRefetchOnMount?: boolean;
497
+ /**
498
+ * Only fetches when the document is missing from state, skipping stale-state
499
+ * and invalidation refetches.
500
+ */
501
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
502
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the document has not been fetched. */
1985
503
  returnIdleStatus?: boolean;
1986
- ensureIsLoaded?: boolean;
504
+ /**
505
+ * Forces a high-priority fetch on mount and keeps the hook in `loading`
506
+ * until the document finishes loading.
507
+ */
508
+ ensureIsLoaded?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
1987
509
  returnRefetchingStatus?: boolean;
1988
510
  }) => TSDFUseDocumentReturn<Selected>;
1989
511
  useListItemIsLoading: (args: {
1990
- itemId: string;
1991
- selector: (data: State | null) => unknown;
1992
- loadItemFallback?: () => void;
512
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
513
+ selector: (data: State | null) => unknown; /** Called if the item is still missing and no refetch is in progress. */
514
+ loadItemFallback?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1993
515
  ensureIsLoaded?: boolean;
1994
516
  }) => boolean;
1995
517
  useListItemIsDeleted: (args: {
1996
- itemId: string;
1997
- selector: (data: State | null) => unknown;
1998
- onDelete?: () => void;
518
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts the item from the document data. */
519
+ selector: (data: State | null) => unknown; /** Called once when deletion is detected. */
520
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
1999
521
  ensureIsLoaded?: boolean;
2000
522
  }) => boolean;
2001
523
  useListItem: <Selected>(args: {
2002
- itemId: string;
2003
- selector: (data: State | null) => Selected;
2004
- loadItemFallback?: () => void;
2005
- onDelete?: () => void;
524
+ /** Unique identifier of the item within the document. */itemId: string; /** Extracts and maps the item from the document data. */
525
+ selector: (data: State | null) => Selected; /** Called if the item is still missing and no refetch is in progress. */
526
+ loadItemFallback?: () => void; /** Called once when deletion is detected. */
527
+ onDelete?: () => void; /** Forces a high-priority fetch and keeps the hook loading until data is loaded. */
2006
528
  ensureIsLoaded?: boolean;
2007
529
  }) => {
2008
530
  isLoading: boolean;
@@ -2012,33 +534,7 @@ type DocumentStore<State extends ValidStoreState, TOfflineOperations extends Doc
2012
534
  performMutation: DocumentPerformMutation<State, TOfflineOperations>;
2013
535
  onTransportReconnect: () => void;
2014
536
  };
2015
- declare function createDocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown>({
2016
- id,
2017
- storeManager,
2018
- fetchFn,
2019
- lowPriorityThrottleMs: storeLowPriorityThrottleMs,
2020
- baseCoalescingWindowMs: storeBaseCoalescingWindowMs,
2021
- dynamicRealtimeThrottleMs,
2022
- revalidateOnWindowFocus,
2023
- transportReconnectCooldownMs,
2024
- mediumPriorityDelayMs,
2025
- onSchedulerEvent,
2026
- onMutationError,
2027
- usesRealTimeUpdates,
2028
- persistentStorage: persistentStorageConfig,
2029
- '~test': testOptions
2030
- }: DocumentStoreOptions<State, TOfflineOperations, StorageState>): DocumentStore<State, TOfflineOperations>;
2031
- //#endregion
2032
- //#region src/internal/testTimelineTypes.d.ts
2033
- type TestTimelineSessionKey = string | false;
2034
- type TestSessionKeyChangedEvent = {
2035
- previousSessionKey: TestTimelineSessionKey;
2036
- sessionKey: TestTimelineSessionKey;
2037
- };
2038
- type TestOfflineTimelineEvent = {
2039
- operation: string;
2040
- phase: 'queued' | 'replay-started' | 'replay-finished' | 'replay-failed';
2041
- };
537
+ declare function createDocumentStore<State extends ValidStoreState, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null, StorageState = unknown>(storeOptions: DocumentStoreOptions<State, TOfflineOperations, StorageState>): DocumentStore<State, TOfflineOperations>;
2042
538
  //#endregion
2043
539
  //#region src/listQueryStore/types.d.ts
2044
540
  type QueryStatus = TSDFStatus | 'loadingMore';
@@ -2065,6 +561,12 @@ type TSFDListQueryState<ItemState extends ValidStoreState, QueryPayload extends
2065
561
  itemLoadedFields: Record<string, string[]>;
2066
562
  itemFieldInvalidationFields: Record<string, string[]>;
2067
563
  };
564
+ /**
565
+ * Partial-resource fields to request.
566
+ *
567
+ * Pass a field-name array to load only those fields, or `'*'` to load the
568
+ * complete item.
569
+ */
2068
570
  type FieldsInput = string[] | '*';
2069
571
  type TSFDUseListQueryReturn<Selected, QueryPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined, HasPartialResources extends boolean = false> = {
2070
572
  items: Selected[];
@@ -2104,47 +606,56 @@ type FetchListFnReturn<ItemState extends ValidStoreState, ItemPayload extends Va
2104
606
  items: FetchListFnReturnItem<ItemPayload, ItemState>[];
2105
607
  hasMore: boolean;
2106
608
  };
2107
- type ListQueryStoreInitialData<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2108
- items: {
2109
- payload: ItemPayload;
2110
- data: ItemState;
2111
- }[];
2112
- queries: {
2113
- payload: QueryPayload;
2114
- items: string[];
2115
- hasMore: boolean;
2116
- }[];
2117
- };
2118
609
  type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
2119
- payload: ItemPayload;
2120
- fields?: FieldsInput;
2121
- queryMetadata?: QueryMetadata; /** Only loads the data if it is not already loaded and skip any other refetches */
2122
- disableRefetches?: boolean;
2123
- disableRefetchOnMount?: boolean;
2124
- returnIdleStatus?: boolean;
610
+ /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload;
611
+ /**
612
+ * Partial-resource fields to request for this item.
613
+ *
614
+ * Pass `'*'` to fetch the complete item. This option is required when
615
+ * `partialResources` is enabled and optional otherwise.
616
+ */
617
+ fields?: FieldsInput; /** Metadata returned with this item result for caller-side bookkeeping. */
618
+ queryMetadata?: QueryMetadata;
619
+ /**
620
+ * Only fetches when the item is missing from state, skipping stale-state and
621
+ * invalidation refetches.
622
+ */
623
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
624
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the item has not been fetched. */
625
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
2125
626
  returnRefetchingStatus?: boolean;
2126
627
  /**
2127
628
  * When requested fields are missing but cached partial data exists, return
2128
629
  * `refetching` instead of `loading`.
2129
630
  */
2130
- showPartialAsRefetching?: boolean;
631
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
2131
632
  isOffScreen?: boolean;
2132
633
  };
2133
634
  type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
2134
- payload: QueryPayload;
2135
- fields?: FieldsInput;
2136
- queryMetadata?: QueryMetadata;
2137
- omitPayload?: boolean; /** Only loads the data if it is not already loaded and skip any other refetches */
2138
- disableRefetches?: boolean;
2139
- disableRefetchOnMount?: boolean;
2140
- returnIdleStatus?: boolean;
635
+ /** Query payload to subscribe to and fetch when needed. */payload: QueryPayload;
636
+ /**
637
+ * Partial-resource fields to request for each item in this query.
638
+ *
639
+ * Pass `'*'` to fetch complete items. This option is required when
640
+ * `partialResources` is enabled and optional otherwise.
641
+ */
642
+ fields?: FieldsInput; /** Metadata returned with this query result for caller-side bookkeeping. */
643
+ queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
644
+ omitPayload?: boolean;
645
+ /**
646
+ * Only fetches when the query is missing from state, skipping stale-state and
647
+ * invalidation refetches.
648
+ */
649
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
650
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the query has not been fetched. */
651
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
2141
652
  returnRefetchingStatus?: boolean;
2142
653
  /**
2143
654
  * When requested fields are missing but cached partial data exists, return
2144
655
  * `refetching` instead of `loading`.
2145
656
  */
2146
- showPartialAsRefetching?: boolean;
2147
- isOffScreen?: boolean;
657
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
658
+ isOffScreen?: boolean; /** Number of items to request when fetching this query page. */
2148
659
  loadSize?: number;
2149
660
  };
2150
661
  type OnListQueryInvalidate<QueryPayload extends ValidPayload> = (query: QueryPayload, priority: FetchType) => void;
@@ -2164,10 +675,10 @@ type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extend
2164
675
  };
2165
676
  };
2166
677
  type QueryFetchPayload<QueryPayload extends ValidPayload> = {
2167
- type: 'load' | 'loadMore';
2168
- payload: QueryPayload;
2169
- offset: number;
2170
- limit: number;
678
+ /** Whether this request loads the first page or a later page. */type: 'load' | 'loadMore'; /** Query payload being fetched. */
679
+ payload: QueryPayload; /** Offset used for offset-paginated fetches. */
680
+ offset: number; /** Maximum number of items requested. */
681
+ limit: number; /** Partial-resource fields requested for each item in the fetched query. */
2171
682
  fields?: string[];
2172
683
  };
2173
684
  type OffsetPaginationConfig = {
@@ -2218,24 +729,40 @@ type DerivedQueriesConfig<ItemState extends ValidStoreState, QueryPayload extend
2218
729
  deriveQuery: (queryPayload: QueryPayload, items: DerivedQueryItem<ItemState>[], context: DerivedQueryContext) => string[] | false;
2219
730
  };
2220
731
  type FieldsOption<HasPartialResources extends boolean> = HasPartialResources extends true ? {
732
+ /**
733
+ * Partial-resource fields to request.
734
+ *
735
+ * Pass `'*'` to fetch complete items. This option is required when
736
+ * `partialResources` is enabled.
737
+ */
2221
738
  fields: FieldsInput;
2222
739
  } : {
740
+ /**
741
+ * Partial-resource fields to request.
742
+ *
743
+ * Pass `'*'` to fetch complete items. This option is optional when
744
+ * `partialResources` is not enabled.
745
+ */
2223
746
  fields?: FieldsInput;
2224
747
  };
2225
748
  //#endregion
2226
749
  //#region src/listQueryStore/useMultipleItems.d.ts
2227
750
  type UseMultipleItemsOptions<ItemState extends ValidStoreState, Selected> = {
2228
- selector?: (data: ItemState | null, payload: ValidPayload | null) => Selected;
2229
- loadFromStateOnly?: boolean;
2230
- returnIdleStatus?: boolean;
751
+ /** 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. */
752
+ loadFromStateOnly?: boolean; /** Returns `idle` instead of `loading` while items have not been fetched. */
753
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
2231
754
  returnRefetchingStatus?: boolean;
2232
755
  /**
2233
756
  * When requested fields are missing but cached partial data exists, return
2234
757
  * `refetching` instead of `loading`.
2235
758
  */
2236
- showPartialAsRefetching?: boolean; /** Only loads the data if it is not already loaded and skip any other refetches */
2237
- disableRefetches?: boolean;
2238
- disableRefetchOnMount?: boolean;
759
+ showPartialAsRefetching?: boolean;
760
+ /**
761
+ * Only fetches when an item is missing from state, skipping stale-state and
762
+ * invalidation refetches.
763
+ */
764
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
765
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
2239
766
  isOffScreen?: boolean;
2240
767
  /**
2241
768
  * Debounces automatic fetches caused by payload changes, while selection
@@ -2253,6 +780,12 @@ type UseItemOptions<ItemState extends ValidStoreState, Selected> = UseMultipleIt
2253
780
  * `debouncePayload`.
2254
781
  */
2255
782
  ensureIsLoaded?: boolean;
783
+ /**
784
+ * Partial-resource fields to request for this item.
785
+ *
786
+ * Pass `'*'` to fetch the complete item. This option is required when
787
+ * `partialResources` is enabled and optional otherwise.
788
+ */
2256
789
  fields?: FieldsInput;
2257
790
  /**
2258
791
  * When requested fields are missing but cached partial data exists, return
@@ -2263,18 +796,22 @@ type UseItemOptions<ItemState extends ValidStoreState, Selected> = UseMultipleIt
2263
796
  //#endregion
2264
797
  //#region src/listQueryStore/useMultipleListQueries.d.ts
2265
798
  type UseMultipleListQueriesOptions<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, SelectedItem> = {
2266
- itemSelector?: (data: ItemState, itemPayload: ItemPayload, itemKey: string) => SelectedItem;
2267
- returnIdleStatus?: boolean;
799
+ /** 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. */
800
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
2268
801
  returnRefetchingStatus?: boolean;
2269
802
  /**
2270
803
  * When requested fields are missing but cached partial data exists, return
2271
804
  * `refetching` instead of `loading`.
2272
805
  */
2273
- showPartialAsRefetching?: boolean;
2274
- omitPayload?: boolean; /** Only loads the data if it is not already loaded and skip any other refetches */
2275
- disableRefetches?: boolean;
2276
- disableRefetchOnMount?: boolean;
2277
- isOffScreen?: boolean;
806
+ showPartialAsRefetching?: boolean; /** Omits `payload` from each query result unless overridden per query. */
807
+ omitPayload?: boolean;
808
+ /**
809
+ * Only fetches when a query is missing from state, skipping stale-state and
810
+ * invalidation refetches.
811
+ */
812
+ disableRefetches?: boolean; /** Prevents automatic mount refetches for stale loaded data. */
813
+ disableRefetchOnMount?: boolean; /** Marks these subscriptions as off-screen, lowering automatic fetch priority. */
814
+ isOffScreen?: boolean; /** Number of items to request when fetching each query page. */
2278
815
  loadSize?: number;
2279
816
  /**
2280
817
  * Debounces automatic fetches caused by payload changes, while selection
@@ -2292,6 +829,12 @@ type UseListQueryOptions<ItemState extends ValidStoreState, ItemPayload extends
2292
829
  * `debouncePayload`.
2293
830
  */
2294
831
  ensureIsLoaded?: boolean;
832
+ /**
833
+ * Partial-resource fields to request for each item in this query.
834
+ *
835
+ * Pass `'*'` to fetch complete items. This option is required when
836
+ * `partialResources` is enabled and optional otherwise.
837
+ */
2295
838
  fields?: FieldsInput;
2296
839
  /**
2297
840
  * When requested fields are missing but cached partial data exists, return
@@ -2337,8 +880,20 @@ type ListQueryStoreStoreEvents<ItemPayload extends ValidPayload> = {
2337
880
  type ResolvedListQueryOfflineOperations<TOfflineOperations> = TOfflineOperations extends null ? Record<never, never> : Exclude<TOfflineOperations, null>;
2338
881
  type ListQueryHasPartialResources<TPartialResources extends boolean> = [TPartialResources] extends [true] ? true : false;
2339
882
  type ListQueryFetchFieldsOption<TPartialResources extends boolean> = ListQueryHasPartialResources<TPartialResources> extends true ? {
883
+ /**
884
+ * Partial-resource fields to request.
885
+ *
886
+ * Pass `'*'` to fetch complete items. This option is required when
887
+ * `partialResources` is enabled.
888
+ */
2340
889
  fields: FieldsInput;
2341
890
  } : {
891
+ /**
892
+ * Partial-resource fields to request.
893
+ *
894
+ * Pass `'*'` to fetch complete items. This option is optional when
895
+ * `partialResources` is not enabled.
896
+ */
2342
897
  fields?: FieldsInput;
2343
898
  };
2344
899
  type ListQueryScheduleFetchWithFieldsOption<TPartialResources extends boolean> = ScheduleFetchOptions & ListQueryFetchFieldsOption<TPartialResources>;
@@ -2402,18 +957,14 @@ type ListQueryUseMultipleListQueriesApi<ItemState extends ValidStoreState, Query
2402
957
  <S = ItemState>(queries: ListQueryUseMultipleListQueriesQuery<QueryPayload, undefined>[], options: UseMultipleListQueriesOptions<ItemState, ItemPayload, S>): readonly TSFDUseListQueryReturn<S, QueryPayload, undefined>[];
2403
958
  };
2404
959
  type ListQueryUseListQueryApi<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
2405
- <SelectedItem = ItemState>(payload: QueryPayload | false | null | undefined, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: UseListQueryOptions<ItemState, ItemPayload, SelectedItem> & {
2406
- fields: FieldsInput;
2407
- }] : [options?: UseListQueryOptions<ItemState, ItemPayload, SelectedItem>]): TSFDUseListQueryReturn<SelectedItem, QueryPayload, undefined>;
960
+ <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>;
2408
961
  };
2409
962
  type ListQueryUseMultipleItemsApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
2410
963
  <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>[];
2411
964
  <S = ItemState | null>(items: ListQueryUseMultipleItemsQuery<ItemPayload, undefined>[], options: UseMultipleItemsOptions<ItemState, S>): readonly TSFDUseListItemReturn<S, ItemPayload, undefined>[];
2412
965
  };
2413
966
  type ListQueryUseItemApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload, TPartialResources extends boolean> = {
2414
- <Selected = ItemState | null>(itemPayload: ItemPayload | false | null | undefined, ...args: ListQueryHasPartialResources<TPartialResources> extends true ? [options: UseItemOptions<ItemState, Selected> & {
2415
- fields: FieldsInput;
2416
- }] : [options?: UseItemOptions<ItemState, Selected>]): TSFDUseListItemReturn<Selected, ItemPayload>;
967
+ <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>;
2417
968
  };
2418
969
  type ListQueryUsePendingOfflineItemsApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
2419
970
  <SelectedItem = ItemState>(options?: UsePendingOfflineItemsOptions<ItemState, ItemPayload, SelectedItem>): TSFDUsePendingOfflineItemsReturn<SelectedItem, ItemPayload>;
@@ -2465,16 +1016,38 @@ type ListQueryAddItemToStateApi<ItemState extends ValidStoreState, QueryPayload
2465
1016
  }) => void;
2466
1017
  type ListQueryDeleteItemStateApi<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (itemId: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload>) => void;
2467
1018
  type ListQueryInvalidateQueryAndItemsArgs<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
2468
- /** Invalidate every cached query and every cached item. */all: true;
1019
+ /** Invalidate every cached query and every cached item. */all: true; /** Fetch priority used for refetches triggered by this invalidation. */
2469
1020
  type?: FetchType;
2470
- fields?: string[];
2471
- itemPayload?: undefined;
1021
+ /**
1022
+ * Partial-resource fields to invalidate on matching items.
1023
+ *
1024
+ * Omit to invalidate the full item data.
1025
+ */
1026
+ fields?: string[]; /** Not allowed when invalidating every query and item. */
1027
+ itemPayload?: undefined; /** Not allowed when invalidating every query and item. */
2472
1028
  queryPayload?: undefined;
2473
1029
  } | {
2474
- all?: undefined;
1030
+ /** Leave unset when invalidating selected queries or items. */all?: undefined;
1031
+ /**
1032
+ * Items to invalidate.
1033
+ *
1034
+ * Pass one payload, many payloads, a predicate over cached items, or
1035
+ * `false` to skip item invalidation.
1036
+ */
2475
1037
  itemPayload: ItemPayload | ItemPayload[] | ListQueryFilterItem<ItemState, ItemPayload> | false;
2476
- queryPayload: QueryPayload | QueryPayload[] | ListQueryFilterQuery<QueryPayload> | false;
1038
+ /**
1039
+ * Queries to invalidate.
1040
+ *
1041
+ * Pass one payload, many payloads, a predicate over cached queries, or
1042
+ * `false` to skip query invalidation.
1043
+ */
1044
+ queryPayload: QueryPayload | QueryPayload[] | ListQueryFilterQuery<QueryPayload> | false; /** Fetch priority used for refetches triggered by this invalidation. */
2477
1045
  type?: FetchType;
1046
+ /**
1047
+ * Partial-resource fields to invalidate on matching items.
1048
+ *
1049
+ * Omit to invalidate the full item data.
1050
+ */
2478
1051
  fields?: string[];
2479
1052
  };
2480
1053
  type ListQueryStore<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = {
@@ -2531,7 +1104,7 @@ type ListQueryStore<ItemState extends ValidStoreState, QueryPayload extends Vali
2531
1104
  useMultipleItems: ListQueryUseMultipleItemsApi<ItemState, ItemPayload, TPartialResources>;
2532
1105
  useItem: ListQueryUseItemApi<ItemState, ItemPayload, TPartialResources>;
2533
1106
  useFindItem: <SelectedItem = ItemState | null>(findItemFn: (item: ItemState, itemPayload: ItemPayload) => boolean, options?: {
2534
- selector?: (data: ItemState, id: ItemPayload) => SelectedItem;
1107
+ /** Maps the matched item before it is returned from the hook. */selector?: (data: ItemState, id: ItemPayload) => SelectedItem;
2535
1108
  }) => SelectedItem | null;
2536
1109
  onTransportReconnect: () => void;
2537
1110
  };
@@ -2553,37 +1126,6 @@ type FetchListFnOffsetMode<ItemState extends ValidStoreState, QueryPayload exten
2553
1126
  signal: AbortSignal;
2554
1127
  fields?: string[];
2555
1128
  }) => Promise<FetchListFnReturn<ItemState, ItemPayload>>;
2556
- type ListQuerySnapshotItemEntry<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
2557
- itemKey: string;
2558
- item: ItemState | null;
2559
- itemQuery: TSDFItemQuery<ItemPayload> | null;
2560
- loadedFields: string[];
2561
- };
2562
- type ListQueryBrowserTabsMessage<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = (BrowserTabsMessageMeta & BrowserTabsTabStatusMessage) | (BrowserTabsMessageMeta & {
2563
- kind: 'list-query-snapshot';
2564
- queryKey: string;
2565
- consistency: SnapshotConsistency;
2566
- query: TSFDListQuery<QueryPayload>;
2567
- items: ListQuerySnapshotItemEntry<ItemState, ItemPayload>[];
2568
- }) | (BrowserTabsMessageMeta & {
2569
- kind: 'list-item-snapshot';
2570
- itemKey: string;
2571
- consistency: SnapshotConsistency;
2572
- item: ItemState | null;
2573
- itemQuery: TSDFItemQuery<ItemPayload> | null;
2574
- loadedFields: string[];
2575
- }) | (BrowserTabsMessageMeta & {
2576
- kind: 'fetch-start';
2577
- targetKey: string;
2578
- requestIds: string[];
2579
- startedAt: number;
2580
- }) | (BrowserTabsMessageMeta & {
2581
- kind: 'fetch-success';
2582
- targetKey: string;
2583
- requestIds: string[];
2584
- startedAt: number;
2585
- duration: number;
2586
- });
2587
1129
  type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload, TPartialResources extends boolean = false, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null, StorageState = unknown> = {
2588
1130
  /**
2589
1131
  * Stable id for this logical list-query store. Used for debug labels,
@@ -2608,21 +1150,7 @@ type ListQueryStoreOptionsBase<ItemState extends ValidStoreState, QueryPayload e
2608
1150
  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. */
2609
1151
  maxQueries?: number; /** Called when cache-limit eviction removes items or queries from in-memory state. */
2610
1152
  onStateCleanup?: (cleanup: ListQueryStateCleanup<QueryPayload, ItemPayload>) => void;
2611
- usesRealTimeUpdates?: boolean;
2612
- '~test'?: {
2613
- initialData?: ListQueryStoreInitialData<ItemState, QueryPayload, ItemPayload>;
2614
- initialRefetchOnMount?: FetchType | false;
2615
- initialLastFetchStartTime?: number;
2616
- getWindowIsFocused?: () => boolean;
2617
- onWindowFocus?: (handler: () => void) => () => void;
2618
- onWindowFocusChange?: (handler: () => void) => () => void;
2619
- browserTabsTransportFactory?: BrowserTabsTransportFactory;
2620
- browserTabsPriorityTimings?: BrowserTabsPriorityTimings;
2621
- browserTabsLeadershipTimings?: BrowserTabsPriorityTimings;
2622
- onReceiveRemoteMsg?: (message: ListQueryBrowserTabsMessage<ItemState, QueryPayload, ItemPayload>) => void;
2623
- onSessionKeyChanged?: (event: TestSessionKeyChangedEvent) => void;
2624
- onOfflineTimelineEvent?: (event: TestOfflineTimelineEvent) => void;
2625
- }; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
1153
+ usesRealTimeUpdates?: boolean; /** Overrides the manager's default minimum interval between low-priority fetches for this store. */
2626
1154
  lowPriorityThrottleMs?: number; /** Overrides the manager's default coalescing window for this store. */
2627
1155
  baseCoalescingWindowMs?: number;
2628
1156
  mediumPriorityDelayMs?: number;
@@ -2724,14 +1252,6 @@ declare function useGlobalOfflineEntities(sessionKey: string): readonly GlobalOf
2724
1252
  */
2725
1253
  declare function useGlobalOfflineResolutions(sessionKey: string): readonly OfflineResolutionRecord[];
2726
1254
  //#endregion
2727
- //#region src/persistentStorage/asyncStorageAdapter.d.ts
2728
- declare function createAsyncStorageAdapter(driver: AsyncStorageDriver): AsyncStorageAdapter;
2729
- //#endregion
2730
- //#region src/persistentStorage/indexedDbAsyncStorageAdapter.d.ts
2731
- type IndexedDbPersistentStorageOptions$1 = {
2732
- databaseName?: string;
2733
- };
2734
- //#endregion
2735
1255
  //#region src/persistentStorage/localStorageMetadata.d.ts
2736
1256
  type ManagedLocalStorageIo = {
2737
1257
  getItem(key: string): string | null;
@@ -2815,10 +1335,6 @@ type LocalPersistentStorage = {
2815
1335
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>): void;
2816
1336
  };
2817
1337
  declare const localPersistentStorage: LocalPersistentStorage;
2818
- declare const opfsPersistentStorage: AsyncStorageAdapter;
2819
- declare const indexedDbPersistentStorage: AsyncStorageAdapter;
2820
- type IndexedDbPersistentStorageOptions = IndexedDbPersistentStorageOptions$1;
2821
- declare function createIndexedDbPersistentStorage(options?: IndexedDbPersistentStorageOptions): AsyncStorageAdapter;
2822
1338
  //#endregion
2823
1339
  //#region src/persistentStorage/persistentStorageManager.d.ts
2824
1340
  /** Clears all persistent storage entries for a given session key and adapter. */
@@ -2829,4 +1345,4 @@ declare function clearAllSessionStorage(sessionKey: string): Promise<void>;
2829
1345
  //#region src/persistentStorage/opfsOfflineUploadAdapter.d.ts
2830
1346
  declare const opfsOfflineUploadAdapter: OfflineUploadAdapter;
2831
1347
  //#endregion
2832
- 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, CollectionBrowserTabsMessage, CollectionInitialStateItem, 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, DocumentBrowserTabsMessage, type DocumentOfflineOperationDefinition, type DocumentPersistentStorageConfig, DocumentStatus, DocumentStore, DocumentStoreOptions, DocumentStoreState, DocumentStoreStoreEvents, type FetchListFnReturn, type FetchListFnReturnItem, type FieldsInput, type FieldsOption, GET_ALL, type GlobalOfflineEntity, type GlobalOfflineStatus, type IndexedDbPersistentStorageOptions, IsOffScreenContext, type ListQueryOfflineEntityRef, type ListQueryOfflineOperationDefinition, type ListQueryPersistentStorageConfig, type ListQueryStore, type ListQueryStoreEvents, type ListQueryStoreInitialData, type ListQueryStoreOptions, type ListQueryUseMultipleItemsQuery, type ListQueryUseMultipleListQueriesQuery, 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 TSDFItemQuery, type TSDFStatus, TSDFUseDocumentReturn, TSFDCollectionItem, TSFDCollectionState, type TSFDListQuery, type TSFDListQueryState, TSFDUseCollectionItemReturn, type TSFDUseListItemReturn, type TSFDUseListQueryReturn, type TSFDUsePendingOfflineItemsReturn, type ValidPayload, type ValidStoreState, clearAllSessionStorage, clearSessionStorage, createAsyncStorageAdapter, createCollectionStore, createDocumentStore, createIndexedDbPersistentStorage, createListQueryStore, createStoreManager, defaultOfflineRuntimeConfig, fetchTypePriority, getGlobalOfflineEntities, getGlobalOfflineResolutions, getGlobalOfflineStatus, indexedDbPersistentStorage, localPersistentStorage, mutationSkipped, opfsOfflineUploadAdapter, opfsPersistentStorage, useGlobalOfflineEntities, useGlobalOfflineResolutions, useGlobalOfflineStatus };
1348
+ 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 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 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 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 };