tsdf 16.0.3 → 17.0.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +140 -0
- package/README.md +5 -0
- package/dist/async-storage.d.ts +2 -0
- package/dist/async-storage.js +2 -0
- package/dist/asyncStorageAdapter-BMYAF6rt.d.ts +6 -0
- package/dist/asyncStorageAdapter-BZSj1ZO5.js +1868 -0
- package/dist/asyncStorageAdapters-DbyKyARM.js +3 -0
- package/dist/indexed-db-storage.d.ts +14 -0
- package/dist/indexed-db-storage.js +2 -0
- package/dist/indexedDbPersistentStorage-DlUjN1qY.js +902 -0
- package/dist/main.d.ts +1487 -373
- package/dist/main.js +16146 -2475
- package/dist/opfs-storage.d.ts +2 -0
- package/dist/opfs-storage.js +2 -0
- package/dist/opfsPersistentStorage-BO_uDxe4.js +838 -0
- package/dist/opfsPersistentStorage-CBnUebnf.d.ts +6 -0
- package/dist/types-2zQlbxtw.d.ts +1475 -0
- package/docs/README.md +98 -0
- package/docs/batch-fetching.md +125 -0
- package/docs/browser-tabs-sync.md +61 -0
- package/docs/cache-limits.md +105 -0
- package/docs/collection-store.md +173 -0
- package/docs/document-store.md +149 -0
- package/docs/fetch-scheduling.md +93 -0
- package/docs/hooks.md +416 -0
- package/docs/invalidation.md +135 -0
- package/docs/list-query-store.md +352 -0
- package/docs/mutations.md +266 -0
- package/docs/offline.md +207 -0
- package/docs/offset-pagination.md +111 -0
- package/docs/optimistic-list-updates.md +180 -0
- package/docs/partial-resources.md +168 -0
- package/docs/persistent-storage.md +290 -0
- package/docs/real-time-updates.md +158 -0
- package/docs/shared-types.md +181 -0
- package/docs/store-manager.md +147 -0
- package/package.json +81 -47
- package/dist/main.cjs +0 -2511
- package/dist/main.d.cts +0 -400
|
@@ -0,0 +1,1475 @@
|
|
|
1
|
+
import { __LEGIT_ANY__ } from "@ls-stack/utils/saferTyping";
|
|
2
|
+
import { Result, ResultValidErrors } from "t-result";
|
|
3
|
+
import { RcType } from "runcheck";
|
|
4
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
5
|
+
|
|
6
|
+
//#region src/debug.d.ts
|
|
7
|
+
/** Debug log severity used to choose the default console method. */
|
|
8
|
+
type TSDFDebugLogLevel = 'log' | 'warn' | 'error';
|
|
9
|
+
/** Internal subsystem that emitted a debug log entry. */
|
|
10
|
+
type TSDFDebugLogArea = 'browser-tabs' | 'persistent-storage';
|
|
11
|
+
/** Operations emitted by the persistent storage subsystem. */
|
|
12
|
+
type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
|
|
13
|
+
/** Operations emitted by the browser-tab sync subsystem. */
|
|
14
|
+
type TSDFBrowserTabsDebugOperation = 'leader-change' | 'publish' | 'publish-skipped' | 'receive' | 'receive-skipped' | 'session-change' | 'transport-close' | 'transport-open' | 'transport-unavailable';
|
|
15
|
+
/** Structured debug log entry emitted by TSDF internals. */
|
|
16
|
+
type TSDFDebugLogEntry = {
|
|
17
|
+
/** Subsystem that emitted the entry. */area: TSDFDebugLogArea; /** Severity of the entry. */
|
|
18
|
+
level: TSDFDebugLogLevel; /** Human-readable summary of the operation. */
|
|
19
|
+
message: string; /** Stable operation id, such as `publish`, `load`, or `write`. */
|
|
20
|
+
operation: TSDFPersistentStorageDebugOperation | TSDFBrowserTabsDebugOperation; /** Structured operation metadata for filtering and diagnostics. */
|
|
21
|
+
details?: Readonly<Record<string, unknown>>;
|
|
22
|
+
};
|
|
23
|
+
/** Custom debug logger invoked for each emitted TSDF debug entry. */
|
|
24
|
+
type TSDFDebugLogger = (entry: TSDFDebugLogEntry) => void;
|
|
25
|
+
/** Enables manager-wide debug logging for browser-tab sync and persistence. */
|
|
26
|
+
type TSDFDebugOptions = boolean | TSDFDebugLogger;
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/requestScheduler.d.ts
|
|
29
|
+
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';
|
|
30
|
+
type RequestSchedulerEventData = {
|
|
31
|
+
/** Delay in ms for scheduled events (medium-priority-scheduled, rt-fetch-scheduled) */delayMs?: number;
|
|
32
|
+
};
|
|
33
|
+
type ScheduleFetchResults = 'skipped' | 'started' | 'scheduled' | 'rt-scheduled' | 'triggered' | 'coalesced' | 'medium-scheduled' | 'added-to-batch' | 'batch-triggered';
|
|
34
|
+
type FetchType = 'lowPriority' | 'mediumPriority' | 'highPriority' | 'realtimeUpdate';
|
|
35
|
+
type ScheduleFetchOptions = {
|
|
36
|
+
mediumPriorityDelayMs?: number;
|
|
37
|
+
};
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/utils/storeShared.d.ts
|
|
40
|
+
/** Shared fetch lifecycle status used by TSDF stores and hooks. */
|
|
41
|
+
type TSDFStatus = 'loading' | 'error' | 'refetching' | 'success';
|
|
42
|
+
/** Payload shapes supported by store keying and fetch APIs. */
|
|
43
|
+
type ValidPayload = number | string | Record<string, unknown>;
|
|
44
|
+
/** State shapes supported by TSDF caches. */
|
|
45
|
+
type ValidStoreState = Record<string, unknown> | unknown[];
|
|
46
|
+
type UnwrapTSDFResult<T> = T extends {
|
|
47
|
+
ok: true;
|
|
48
|
+
value: infer Value;
|
|
49
|
+
} ? Value : T extends {
|
|
50
|
+
ok: false;
|
|
51
|
+
error: ResultValidErrors;
|
|
52
|
+
} ? never : T;
|
|
53
|
+
type MaybeTSDFResult<T> = T | Result<T, ResultValidErrors>;
|
|
54
|
+
/**
|
|
55
|
+
* Debounce settings for payload-driven automatic fetches in store hooks.
|
|
56
|
+
*
|
|
57
|
+
* The hook still reads data from state using the latest payload immediately.
|
|
58
|
+
* Only the automatic fetch side is delayed. Single hooks do not support
|
|
59
|
+
* combining this with `ensureIsLoaded`.
|
|
60
|
+
*/
|
|
61
|
+
type PayloadDebounce = {
|
|
62
|
+
/** Debounce window in milliseconds before the latest payload is fetched. */ms: number;
|
|
63
|
+
/**
|
|
64
|
+
* Maximum time a burst may stay deferred before the latest payload is
|
|
65
|
+
* fetched, even if changes keep happening within the debounce window.
|
|
66
|
+
*/
|
|
67
|
+
maxWait?: number;
|
|
68
|
+
/**
|
|
69
|
+
* When true, the first payload in a burst may fetch immediately, and later
|
|
70
|
+
* changes within the same burst stay debounced until the wait window ends.
|
|
71
|
+
*/
|
|
72
|
+
leading?: boolean;
|
|
73
|
+
};
|
|
74
|
+
/** Normalized error shape used by fetch and mutation APIs. */
|
|
75
|
+
type StoreError = {
|
|
76
|
+
/** Numeric application or transport error code. */code: number; /** Stable machine-readable error id. */
|
|
77
|
+
id: string; /** Human-readable error message. */
|
|
78
|
+
message: string; /** Optional request path associated with the failure. */
|
|
79
|
+
path?: string; /** Optional HTTP method associated with the failure. */
|
|
80
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
81
|
+
};
|
|
82
|
+
declare const fetchTypePriority: Record<FetchType, number>;
|
|
83
|
+
/** Result error returned when a debounced or canceled mutation never runs. */
|
|
84
|
+
type MutationSkipped = {
|
|
85
|
+
/** Stable discriminator for skipped mutations. */kind: 'skipped';
|
|
86
|
+
};
|
|
87
|
+
declare const mutationSkipped: MutationSkipped;
|
|
88
|
+
/** Options passed to mutation error handlers. */
|
|
89
|
+
type StoreMutationErrorOptions = {
|
|
90
|
+
/**
|
|
91
|
+
* True when the mutation caller asked the shared error handler to stay quiet.
|
|
92
|
+
*
|
|
93
|
+
* Handlers are still called so apps can keep centralized logging, metrics, or
|
|
94
|
+
* custom recovery behavior while suppressing user-facing noise such as toast
|
|
95
|
+
* notifications.
|
|
96
|
+
*/
|
|
97
|
+
silentErrors?: boolean;
|
|
98
|
+
};
|
|
99
|
+
/** Error wrapper returned by mutation APIs after normalization. */
|
|
100
|
+
declare class StoreMutationError extends Error {
|
|
101
|
+
/** Stable discriminator matching result-style mutation errors. */
|
|
102
|
+
readonly kind = "error";
|
|
103
|
+
/** Numeric application or transport error code. */
|
|
104
|
+
code: number;
|
|
105
|
+
/** Stable machine-readable error id. */
|
|
106
|
+
id: string;
|
|
107
|
+
/** Optional request path associated with the failure. */
|
|
108
|
+
path?: string;
|
|
109
|
+
/** Optional HTTP method associated with the failure. */
|
|
110
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
111
|
+
constructor(error: StoreError, options?: ErrorOptions);
|
|
112
|
+
}
|
|
113
|
+
/** Error wrapper returned by fetch APIs after normalization. */
|
|
114
|
+
declare class StoreFetchError extends Error {
|
|
115
|
+
/** Numeric application or transport error code. */
|
|
116
|
+
code: number;
|
|
117
|
+
/** Stable machine-readable error id. */
|
|
118
|
+
id: string;
|
|
119
|
+
/** Fetch failure category. */
|
|
120
|
+
type: 'fetch' | 'aborted' | 'timeout';
|
|
121
|
+
/** Optional request path associated with the failure. */
|
|
122
|
+
path?: string;
|
|
123
|
+
/** Optional HTTP method associated with the failure. */
|
|
124
|
+
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
|
125
|
+
constructor(error: StoreError, type: 'fetch' | 'aborted' | 'timeout');
|
|
126
|
+
}
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/persistentStorage/offlineUploadTypes.d.ts
|
|
129
|
+
/** Lifecycle state for a session-scoped offline upload. */
|
|
130
|
+
type OfflineUploadState = 'pending' | 'uploading' | 'uploaded' | 'failed';
|
|
131
|
+
/** Source that created a staged offline upload. */
|
|
132
|
+
type OfflineUploadSource = 'manual' | 'mutation';
|
|
133
|
+
/** Progress snapshot reported while uploading a staged file. */
|
|
134
|
+
type OfflineUploadProgress = {
|
|
135
|
+
/** Normalized progress from `0` to `1`. */progress: number; /** Loaded byte count, when available from the transport. */
|
|
136
|
+
loadedBytes?: number; /** Total byte count, when available from the transport. */
|
|
137
|
+
totalBytes?: number;
|
|
138
|
+
};
|
|
139
|
+
/** Public metadata for a file staged for offline mutation replay. */
|
|
140
|
+
type OfflineUpload<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
141
|
+
/** Stable upload id used by offline operation inputs. */id: string; /** Session key that owns this upload. */
|
|
142
|
+
sessionKey: string; /** Source that created this upload. */
|
|
143
|
+
source: OfflineUploadSource; /** Current upload lifecycle state. */
|
|
144
|
+
state: OfflineUploadState; /** Original file name. */
|
|
145
|
+
fileName: string; /** MIME type recorded for the staged file. */
|
|
146
|
+
mimeType: string; /** File size in bytes. */
|
|
147
|
+
sizeBytes: number; /** Epoch timestamp when the upload was staged. */
|
|
148
|
+
createdAt: number; /** Epoch timestamp for the latest upload metadata change. */
|
|
149
|
+
updatedAt: number; /** Final server-side reference after upload completes. */
|
|
150
|
+
resolvedRef?: TResolvedRef; /** Latest upload progress snapshot. */
|
|
151
|
+
progress?: OfflineUploadProgress; /** Last upload failure message, when any. */
|
|
152
|
+
lastError?: {
|
|
153
|
+
message: string;
|
|
154
|
+
};
|
|
155
|
+
};
|
|
156
|
+
/** Persisted offline upload record including the staged file object. */
|
|
157
|
+
type OfflineStoredUploadRecord<TResolvedRef extends ValidPayload = ValidPayload> = OfflineUpload<TResolvedRef> & {
|
|
158
|
+
/** Staged file blob restored from the upload adapter. */file: File; /** Last online session start time seen before the upload was stored. */
|
|
159
|
+
lastOnlineSessionStartedAt?: number; /** File last-modified timestamp. */
|
|
160
|
+
lastModified: number;
|
|
161
|
+
};
|
|
162
|
+
/** Storage backend contract for session-scoped offline upload files. */
|
|
163
|
+
type OfflineUploadAdapter = {
|
|
164
|
+
/** Saves or replaces one staged upload record. */save<TResolvedRef extends ValidPayload>(sessionKey: string, id: string, record: OfflineStoredUploadRecord<TResolvedRef>): Promise<void>; /** Loads one staged upload record by id. */
|
|
165
|
+
load<TResolvedRef extends ValidPayload>(sessionKey: string, id: string): Promise<OfflineStoredUploadRecord<TResolvedRef> | null>; /** Lists all staged upload records for a session. */
|
|
166
|
+
list<TResolvedRef extends ValidPayload>(sessionKey: string): Promise<OfflineStoredUploadRecord<TResolvedRef>[]>; /** Removes one staged upload record. */
|
|
167
|
+
remove(sessionKey: string, id: string): Promise<void>; /** Removes all staged upload records for a session. */
|
|
168
|
+
clearSession(sessionKey: string): Promise<void>; /** Test-only reset hook used by TSDF internals. */
|
|
169
|
+
resetForTests?(): void;
|
|
170
|
+
};
|
|
171
|
+
/** Context passed to the configured offline upload transport. */
|
|
172
|
+
type OfflineUploadTransportContext = {
|
|
173
|
+
/** Stable upload id being transported. */id: string; /** Session key that owns this upload. */
|
|
174
|
+
sessionKey: string; /** File to upload. */
|
|
175
|
+
file: File; /** Reports upload progress back to TSDF. */
|
|
176
|
+
onProgress: (progress: OfflineUploadProgress) => void;
|
|
177
|
+
};
|
|
178
|
+
/** Upload handling config for an offline session. */
|
|
179
|
+
type OfflineSessionUploadsConfig<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
180
|
+
/** Adapter used to persist staged files until replay can upload them. */adapter: OfflineUploadAdapter; /** Upload transport that returns the final server-side file reference. */
|
|
181
|
+
upload: (ctx: OfflineUploadTransportContext) => Promise<TResolvedRef>; /** Maximum number of concurrent upload transports. */
|
|
182
|
+
concurrency?: number;
|
|
183
|
+
};
|
|
184
|
+
/** Files attached to an offline-capable mutation call, keyed by upload id. */
|
|
185
|
+
type OfflineMutationUploadsInput = Record<string, Blob | File>;
|
|
186
|
+
type OfflineAttachedUploadIds = Record<string, string>;
|
|
187
|
+
/** Resolved upload files and references available while an offline operation replays. */
|
|
188
|
+
type OfflineOperationUploadsContext<TResolvedRef extends ValidPayload = ValidPayload> = {
|
|
189
|
+
/** Locally staged files by upload id. */filesById: Record<string, File>; /** Final uploaded refs by upload id. */
|
|
190
|
+
resolvedRefsById: Record<string, TResolvedRef>;
|
|
191
|
+
};
|
|
192
|
+
//#endregion
|
|
193
|
+
//#region src/persistentStorage/validateWithSchema.d.ts
|
|
194
|
+
type SchemaValidationError = readonly string[] | StandardSchemaV1.FailureResult['issues'];
|
|
195
|
+
//#endregion
|
|
196
|
+
//#region src/persistentStorage/offline/types.d.ts
|
|
197
|
+
/** Store kinds supported by offline replay and sync state tracking. */
|
|
198
|
+
type OfflineStoreType = 'document' | 'collection' | 'listQuery';
|
|
199
|
+
/** Phase where a failure occurred during offline-enabled operation flow. */
|
|
200
|
+
type OfflineFailurePhase = 'fetch' | 'mutation' | 'sync';
|
|
201
|
+
/** High-level classification used by outage detection. */
|
|
202
|
+
type OfflineFailureClassification = 'outage' | 'network' | 'ignore';
|
|
203
|
+
/** Kinds of entities participating in offline conflict/sync tracking. */
|
|
204
|
+
type OfflineEntityKind = 'document' | 'item' | 'query';
|
|
205
|
+
/** Lifecycle declared per offline operation definition. */
|
|
206
|
+
type OfflineOperationKind = 'create' | 'update' | 'delete';
|
|
207
|
+
/** Effective lifecycle derived for an offline entity across queued work. */
|
|
208
|
+
type OfflineEntityMutationKind = 'create' | 'createAndUpdate' | 'update' | 'delete';
|
|
209
|
+
/** Connectivity cause currently governing offline mutation queueing. */
|
|
210
|
+
type OfflineMutationQueueingCause = 'network' | 'outage';
|
|
211
|
+
/** Root policy value for whether offline-enabled mutations may queue. */
|
|
212
|
+
type OfflineMutationQueueingPolicy = 'allow' | 'disallow';
|
|
213
|
+
/** Root mutation queueing policy shared by all configured offline operations. */
|
|
214
|
+
type OfflineMutationQueueingConfig = {
|
|
215
|
+
/**
|
|
216
|
+
* Controls whether offline-enabled mutations may queue while network mode is
|
|
217
|
+
* active, including browser-detected offline and classified network failures.
|
|
218
|
+
* @default 'allow'
|
|
219
|
+
*/
|
|
220
|
+
network?: OfflineMutationQueueingPolicy;
|
|
221
|
+
/**
|
|
222
|
+
* Controls whether offline-enabled mutations may queue while outage mode is
|
|
223
|
+
* active.
|
|
224
|
+
* @default 'allow'
|
|
225
|
+
*/
|
|
226
|
+
outage?: OfflineMutationQueueingPolicy;
|
|
227
|
+
};
|
|
228
|
+
/**
|
|
229
|
+
* Effective runtime offline controls exposed through an offline session.
|
|
230
|
+
*
|
|
231
|
+
* All fields are session-scoped and affect every store attached to the same
|
|
232
|
+
* offline session.
|
|
233
|
+
*/
|
|
234
|
+
type OfflineRuntimeConfig = {
|
|
235
|
+
/** Whether future operations may enter network offline handling. */network: {
|
|
236
|
+
enabled: boolean;
|
|
237
|
+
}; /** Whether future operations may enter outage offline handling. */
|
|
238
|
+
outage: {
|
|
239
|
+
enabled: boolean;
|
|
240
|
+
}; /** Effective queue admission policy for offline-enabled mutations. */
|
|
241
|
+
mutationQueueing: {
|
|
242
|
+
network: OfflineMutationQueueingPolicy;
|
|
243
|
+
outage: OfflineMutationQueueingPolicy;
|
|
244
|
+
};
|
|
245
|
+
};
|
|
246
|
+
/** Default runtime config when offline is not configured or no session exists. */
|
|
247
|
+
declare const defaultOfflineRuntimeConfig: OfflineRuntimeConfig;
|
|
248
|
+
/**
|
|
249
|
+
* Partial runtime offline control update accepted by an offline session.
|
|
250
|
+
*
|
|
251
|
+
* Provided fields shallow-merge into the current runtime config.
|
|
252
|
+
*/
|
|
253
|
+
type OfflineRuntimeConfigUpdate = {
|
|
254
|
+
/** Optional session-scoped update for network mode enablement. */network?: {
|
|
255
|
+
enabled?: boolean;
|
|
256
|
+
}; /** Optional session-scoped update for outage mode enablement. */
|
|
257
|
+
outage?: {
|
|
258
|
+
enabled?: boolean;
|
|
259
|
+
}; /** Optional session-scoped update for offline mutation queue admission policy. */
|
|
260
|
+
mutationQueueing?: {
|
|
261
|
+
network?: OfflineMutationQueueingPolicy;
|
|
262
|
+
outage?: OfflineMutationQueueingPolicy;
|
|
263
|
+
};
|
|
264
|
+
};
|
|
265
|
+
/** Context passed into offline failure classification hooks. */
|
|
266
|
+
type OfflineFailureContext = {
|
|
267
|
+
/** Phase in which the failure was detected. */phase: OfflineFailurePhase; /** Store type affected by the failure. */
|
|
268
|
+
storeType: OfflineStoreType; /** Optional operation name associated with the failure. */
|
|
269
|
+
operationName?: string; /** Session key used by browser tab and persistence scoping. */
|
|
270
|
+
sessionKey: string;
|
|
271
|
+
};
|
|
272
|
+
/** Re-check strategy for recovery probing. Omitted fields use built-in defaults (which differ between network and outage modes). */
|
|
273
|
+
type OfflineRecoveryProbeConfig = {
|
|
274
|
+
/**
|
|
275
|
+
* Initial recovery check delay, in milliseconds.
|
|
276
|
+
* @default 5_000 (network) / 30_000 (outage)
|
|
277
|
+
*/
|
|
278
|
+
initialIntervalMs?: number;
|
|
279
|
+
/**
|
|
280
|
+
* Maximum recovery check delay, in milliseconds.
|
|
281
|
+
* @default 60_000 (network) / 300_000 (outage)
|
|
282
|
+
*/
|
|
283
|
+
maxIntervalMs?: number;
|
|
284
|
+
/**
|
|
285
|
+
* Multiplicative backoff between recovery probes.
|
|
286
|
+
* @default 2
|
|
287
|
+
*/
|
|
288
|
+
backoffMultiplier?: number;
|
|
289
|
+
/**
|
|
290
|
+
* Jitter ratio (0-1) applied to the recovery probe delay.
|
|
291
|
+
* @default 0.2
|
|
292
|
+
*/
|
|
293
|
+
jitterRatio?: number;
|
|
294
|
+
};
|
|
295
|
+
/** Network availability mode configuration for offline controls. */
|
|
296
|
+
type OfflineNetworkModeConfig = {
|
|
297
|
+
/** Enable network connectivity detection and tracking. */enabled: boolean;
|
|
298
|
+
/**
|
|
299
|
+
* If true, subscribe to browser `online` / `offline` events.
|
|
300
|
+
* @default true
|
|
301
|
+
*/
|
|
302
|
+
listenToBrowserEvents?: boolean;
|
|
303
|
+
/**
|
|
304
|
+
* Optional override for network connectivity checks.
|
|
305
|
+
* Return `true` when network should be considered offline.
|
|
306
|
+
*/
|
|
307
|
+
getIsOffline?: () => boolean | Promise<boolean>;
|
|
308
|
+
/**
|
|
309
|
+
* Probe whether classified network recovery has completed.
|
|
310
|
+
* Return `true` when the session should leave network offline mode.
|
|
311
|
+
*/
|
|
312
|
+
recoveryCheck?: (ctx: {
|
|
313
|
+
sessionKey: string;
|
|
314
|
+
}) => Promise<boolean> | boolean; /** Optional probe config to tune classified network recovery behavior. */
|
|
315
|
+
recoveryProbe?: OfflineRecoveryProbeConfig;
|
|
316
|
+
};
|
|
317
|
+
/** Server outage detection and recovery configuration. */
|
|
318
|
+
type OfflineOutageModeConfig = {
|
|
319
|
+
/** Enable outage mode logic and confirmation retry flow. */enabled: boolean; /** Probe the remote service to confirm outage recovery. */
|
|
320
|
+
recoveryCheck: (ctx: {
|
|
321
|
+
sessionKey: string;
|
|
322
|
+
}) => Promise<boolean> | boolean; /** Optional probe config to tune recovery behavior. */
|
|
323
|
+
recoveryProbe?: OfflineRecoveryProbeConfig;
|
|
324
|
+
};
|
|
325
|
+
/** Fixed replay retry policy for healthy online replay failures. Omitted fields use built-in defaults. */
|
|
326
|
+
type OfflineReplayRetryConfig = {
|
|
327
|
+
/**
|
|
328
|
+
* Max counted failures before manual resolution is required.
|
|
329
|
+
* @default 3
|
|
330
|
+
*/
|
|
331
|
+
maxFailures?: number;
|
|
332
|
+
/**
|
|
333
|
+
* Fixed delay between replay retries, in milliseconds.
|
|
334
|
+
* @default 5000
|
|
335
|
+
*/
|
|
336
|
+
intervalMs?: number;
|
|
337
|
+
};
|
|
338
|
+
/** Shared offline/session policy reused by every store in the same session. */
|
|
339
|
+
type OfflineSessionConfig<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
340
|
+
/**
|
|
341
|
+
* Classify a remote failure as `outage`, `network`, or `ignore`.
|
|
342
|
+
* `outage` activates outage recovery behavior.
|
|
343
|
+
* `network` activates network offline handling for future operations only
|
|
344
|
+
* when `network.enabled` is true. Existing offline recovery may keep using
|
|
345
|
+
* classifications until already-active work finishes recovering.
|
|
346
|
+
*/
|
|
347
|
+
classifyFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<OfflineFailureClassification> | OfflineFailureClassification;
|
|
348
|
+
/**
|
|
349
|
+
* Optional replay-only classifier for ambiguous sync failures that stayed
|
|
350
|
+
* online (`classifyFailure(...) === 'ignore'`).
|
|
351
|
+
*
|
|
352
|
+
* Return `true` only when automatically re-sending the replayed mutation is
|
|
353
|
+
* known to be safe. Return `false` to avoid auto-replay retries; in that
|
|
354
|
+
* case the entry still enters `needs-confirmation` so `shouldSkipSync` /
|
|
355
|
+
* conflict checks can run before the mutation is promoted to manual
|
|
356
|
+
* resolution.
|
|
357
|
+
*/
|
|
358
|
+
classifyRetryableFailure?: (error: unknown, ctx: OfflineFailureContext) => Promise<boolean> | boolean; /** Network detection strategy and browser integration. */
|
|
359
|
+
network?: OfflineNetworkModeConfig; /** Outage detection and recovery strategy for remote failures. */
|
|
360
|
+
outage?: OfflineOutageModeConfig; /** Fixed retry policy for healthy online replay failures. */
|
|
361
|
+
replayRetry?: OfflineReplayRetryConfig;
|
|
362
|
+
/**
|
|
363
|
+
* Root policy controlling whether offline-enabled mutations may enter the
|
|
364
|
+
* durable offline queue for each active offline cause.
|
|
365
|
+
* @default undefined
|
|
366
|
+
*/
|
|
367
|
+
mutationQueueing?: OfflineMutationQueueingConfig; /** Optional upload transport/storage config shared by the whole session. */
|
|
368
|
+
uploads?: OfflineSessionUploadsConfig<TUploadRef>;
|
|
369
|
+
};
|
|
370
|
+
/** Per-session offline status snapshot shared across tabs. */
|
|
371
|
+
type GlobalOfflineStatus = {
|
|
372
|
+
/** Session key for this status bucket. */sessionKey: string;
|
|
373
|
+
/**
|
|
374
|
+
* Network mode admission enablement plus the last observed network-offline
|
|
375
|
+
* state for this session. `active` is preserved even while new admission is
|
|
376
|
+
* disabled so existing offline work can recover and sync safely.
|
|
377
|
+
*/
|
|
378
|
+
network: {
|
|
379
|
+
enabled: boolean;
|
|
380
|
+
active: boolean;
|
|
381
|
+
};
|
|
382
|
+
/**
|
|
383
|
+
* Outage mode admission enablement plus the last observed outage-active
|
|
384
|
+
* state for this session. `active` is preserved even while new admission is
|
|
385
|
+
* disabled so existing offline work can recover and sync safely.
|
|
386
|
+
*/
|
|
387
|
+
outage: {
|
|
388
|
+
enabled: boolean;
|
|
389
|
+
active: boolean;
|
|
390
|
+
}; /** Whether the session currently has any active offline cause. */
|
|
391
|
+
isOfflineMode: boolean; /** Whether this tab currently acts as leader for this session. */
|
|
392
|
+
isLeader: boolean; /** Timestamp when this status entry was last updated. */
|
|
393
|
+
updatedAt: number; /** Timestamp of the last failure, if any. */
|
|
394
|
+
lastFailureAt: number | null; /** Timestamp of last recovery probe execution, if any. */
|
|
395
|
+
lastRecoveryCheckAt: number | null;
|
|
396
|
+
};
|
|
397
|
+
/** Queue state of an offline mutation entry. */
|
|
398
|
+
type OfflineSyncState = 'pending' | 'syncing' | 'needs-confirmation';
|
|
399
|
+
/** Aggregated offline status for a tracked document/item/query entity. */
|
|
400
|
+
type GlobalOfflineEntity = {
|
|
401
|
+
/** Internal entity identifier tracked by offline machinery. */id: string; /** Session key for this offline entity. */
|
|
402
|
+
sessionKey: string; /** Store name where the entity is defined. */
|
|
403
|
+
storeName: string; /** Store type this entity belongs to. */
|
|
404
|
+
storeType: OfflineStoreType; /** Entity key used for deduping and conflict scoping. */
|
|
405
|
+
entityKey: string; /** Entity kind used in queue partitioning. */
|
|
406
|
+
entityKind: OfflineEntityKind; /** Effective lifecycle derived from queued operations targeting this entity. */
|
|
407
|
+
kind: OfflineEntityMutationKind; /** Number of pending mutations waiting for sync. */
|
|
408
|
+
pendingMutations: number; /** Current sync state for the entity. */
|
|
409
|
+
syncState: OfflineSyncState | 'resolution-required'; /** Whether the entity currently requires manual resolution. */
|
|
410
|
+
requiresResolution: boolean; /** Resolution ids currently blocking this entity from being resolved/applied. */
|
|
411
|
+
blockedByResolutionIds: string[]; /** Child resolution ids currently derived from this entity's dependency chain. */
|
|
412
|
+
childResolutionIds: string[]; /** Number of blocking parent resolutions currently affecting this entity. */
|
|
413
|
+
blockedResolutionCount: number; /** Number of child resolutions currently derived from this entity's dependency chain. */
|
|
414
|
+
childResolutionCount: number; /** Creation timestamp for lifecycle bookkeeping. */
|
|
415
|
+
createdAt: number; /** Last mutation/update timestamp. */
|
|
416
|
+
updatedAt: number; /** Optional temporary ID for optimistic create flows. */
|
|
417
|
+
tempId?: ValidPayload;
|
|
418
|
+
};
|
|
419
|
+
/** Reference to an entity participating in offline sync tracking. */
|
|
420
|
+
type OfflineEntityRef = {
|
|
421
|
+
entityKey: string;
|
|
422
|
+
entityKind: OfflineEntityKind;
|
|
423
|
+
};
|
|
424
|
+
/**
|
|
425
|
+
* Persisted offline conflict payload.
|
|
426
|
+
*
|
|
427
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
428
|
+
* @typeParam TInput - Original mutation input associated with the conflict.
|
|
429
|
+
*/
|
|
430
|
+
type OfflineConflictResolutionRecordBase<TConflict = unknown, TInput = unknown> = {
|
|
431
|
+
/** Resolution record identifier. */id: string; /** Resolution kind. */
|
|
432
|
+
kind: 'conflict'; /** Queue entry identifier that produced this conflict. */
|
|
433
|
+
entryId: string; /** Session key that owns this conflict record. */
|
|
434
|
+
sessionKey: string; /** Store name associated with the conflict. */
|
|
435
|
+
storeName: string; /** Store type associated with the conflict. */
|
|
436
|
+
storeType: OfflineStoreType; /** Operation name linked to the conflict. */
|
|
437
|
+
operation: string; /** Input value that triggered the conflict. */
|
|
438
|
+
input: TInput; /** Conflict payload returned by the resolver. */
|
|
439
|
+
conflict: TConflict; /** Timestamp when the original queued mutation was enqueued. */
|
|
440
|
+
enqueuedAt: number; /** Entity references involved in the conflict. */
|
|
441
|
+
entityRefs: OfflineEntityRef[]; /** Conflict creation timestamp. */
|
|
442
|
+
createdAt: number; /** Conflict update timestamp. */
|
|
443
|
+
updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
|
|
444
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
445
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
446
|
+
dependencyUploadIds?: string[];
|
|
447
|
+
};
|
|
448
|
+
/** Derived dependency metadata exposed for offline manual resolutions. */
|
|
449
|
+
type OfflineResolutionDependencyMetadata = {
|
|
450
|
+
/** 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. */
|
|
451
|
+
childResolutionIds: string[]; /** Number of blocking parent resolutions affecting this resolution. */
|
|
452
|
+
blockedResolutionCount: number; /** Number of child manual resolutions currently derived from this resolution. */
|
|
453
|
+
childResolutionCount: number;
|
|
454
|
+
};
|
|
455
|
+
/**
|
|
456
|
+
* Persisted offline conflict payload with derived dependency metadata.
|
|
457
|
+
*
|
|
458
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
459
|
+
* @typeParam TInput - Original mutation input associated with the conflict.
|
|
460
|
+
*/
|
|
461
|
+
type OfflineConflictResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecordBase<TConflict, TInput> & OfflineResolutionDependencyMetadata;
|
|
462
|
+
/**
|
|
463
|
+
* Persisted resolution record created when replay retries are exhausted.
|
|
464
|
+
*
|
|
465
|
+
* @typeParam TInput - Original mutation input associated with the replay failure.
|
|
466
|
+
*/
|
|
467
|
+
type OfflineRetryExhaustedResolutionRecordBase<TInput = unknown> = {
|
|
468
|
+
/** Resolution record identifier. */id: string; /** Resolution kind. */
|
|
469
|
+
kind: 'retry-exhausted'; /** Queue entry identifier that exhausted replay retries. */
|
|
470
|
+
entryId: string; /** Session key that owns this resolution record. */
|
|
471
|
+
sessionKey: string; /** Store name associated with the resolution. */
|
|
472
|
+
storeName: string; /** Store type associated with the resolution. */
|
|
473
|
+
storeType: OfflineStoreType; /** Operation name linked to the replay failure. */
|
|
474
|
+
operation: string; /** Input value that exhausted replay retries. */
|
|
475
|
+
input: TInput; /** Timestamp when the original queued mutation was enqueued. */
|
|
476
|
+
enqueuedAt: number; /** Entity references involved in the resolution. */
|
|
477
|
+
entityRefs: OfflineEntityRef[]; /** Last replay error snapshot captured before exhaustion. */
|
|
478
|
+
lastReplayError: {
|
|
479
|
+
message: string;
|
|
480
|
+
}; /** Resolution creation timestamp. */
|
|
481
|
+
createdAt: number; /** Resolution update timestamp. */
|
|
482
|
+
updatedAt: number; /** Optional temporary IDs associated with optimistic entity flow. */
|
|
483
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
484
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
485
|
+
dependencyUploadIds?: string[];
|
|
486
|
+
};
|
|
487
|
+
/**
|
|
488
|
+
* Persisted resolution record created when replay retries are exhausted, plus
|
|
489
|
+
* derived dependency metadata.
|
|
490
|
+
*
|
|
491
|
+
* @typeParam TInput - Original mutation input associated with the replay failure.
|
|
492
|
+
*/
|
|
493
|
+
type OfflineRetryExhaustedResolutionRecord<TInput = unknown> = OfflineRetryExhaustedResolutionRecordBase<TInput> & OfflineResolutionDependencyMetadata;
|
|
494
|
+
/**
|
|
495
|
+
* Persisted offline resolution payload.
|
|
496
|
+
*
|
|
497
|
+
* @typeParam TConflict - Conflict payload stored for later resolution.
|
|
498
|
+
* @typeParam TInput - Original mutation input associated with the resolution.
|
|
499
|
+
*/
|
|
500
|
+
type OfflineResolutionRecord<TConflict = unknown, TInput = unknown> = OfflineConflictResolutionRecord<TConflict, TInput> | OfflineRetryExhaustedResolutionRecord<TInput>;
|
|
501
|
+
/** Session-scoped offline controller shared across stores in the same session. */
|
|
502
|
+
type OfflineSession<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
503
|
+
/** Returns the active session key used to scope shared offline state. */getSessionKey: () => string | false; /** Shared static session configuration used by attached stores. */
|
|
504
|
+
getConfig: () => OfflineSessionConfig<TUploadRef>; /** Latest effective runtime config for this session. */
|
|
505
|
+
getOfflineRuntimeConfig: () => OfflineRuntimeConfig; /** Updates runtime controls for this session. */
|
|
506
|
+
setOfflineRuntimeConfig: (update: OfflineRuntimeConfigUpdate) => void; /** Resets runtime controls back to the static session config. */
|
|
507
|
+
resetOfflineRuntimeConfig: () => void; /** Returns the latest global offline status for the session. */
|
|
508
|
+
getOfflineStatus: () => GlobalOfflineStatus; /** Returns the latest aggregated offline entities for the session. */
|
|
509
|
+
getOfflineEntities: () => readonly GlobalOfflineEntity[]; /** Returns the latest aggregated conflict/retry resolutions for the session. */
|
|
510
|
+
getOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** Returns the latest session-scoped offline uploads for the session. */
|
|
511
|
+
getOfflineUploads: () => readonly OfflineUpload<TUploadRef>[]; /** Resolves a staged upload id to its latest final ref, uploading first if needed. */
|
|
512
|
+
resolveOfflineUpload: (id: string) => Promise<TUploadRef>; /** Resolves multiple staged upload ids to their latest final refs. */
|
|
513
|
+
resolveOfflineUploads: (ids: readonly string[]) => Promise<Record<string, TUploadRef>>; /** Saves a session-scoped upload locally for later dependency resolution or ref usage. */
|
|
514
|
+
saveOfflineUpload: (args: {
|
|
515
|
+
id: string;
|
|
516
|
+
file: Blob | File;
|
|
517
|
+
}) => Promise<void>; /** Replaces a previously stored session-scoped upload. */
|
|
518
|
+
replaceOfflineUpload: (args: {
|
|
519
|
+
id: string;
|
|
520
|
+
file: Blob | File;
|
|
521
|
+
}) => Promise<void>; /** Loads a previously stored session-scoped upload. */
|
|
522
|
+
loadOfflineUpload: (id: string) => Promise<File | null>; /** Deletes a stored upload when it is no longer referenced. */
|
|
523
|
+
deleteOfflineUpload: (id: string) => Promise<void>; /** React hook subscribing to the session's global offline status. */
|
|
524
|
+
useOfflineStatus: () => GlobalOfflineStatus; /** React hook subscribing to the session's aggregated offline entities. */
|
|
525
|
+
useOfflineEntities: () => readonly GlobalOfflineEntity[]; /** React hook subscribing to the session's aggregated conflict/retry resolutions. */
|
|
526
|
+
useOfflineResolutions: () => readonly OfflineResolutionRecord[]; /** React hook subscribing to the session's upload list. */
|
|
527
|
+
useOfflineUploads: () => readonly OfflineUpload<TUploadRef>[];
|
|
528
|
+
};
|
|
529
|
+
/**
|
|
530
|
+
* Persisted offline mutation queue entry.
|
|
531
|
+
*
|
|
532
|
+
* @typeParam TInput - Serialized input payload for the queued mutation.
|
|
533
|
+
* @typeParam TConflict - Conflict payload that may be attached while waiting for confirmation or resolution.
|
|
534
|
+
*/
|
|
535
|
+
type OfflineQueueEntry<TInput = unknown, TConflict = unknown> = {
|
|
536
|
+
/** Queue entry identifier. */id: string; /** Session key for queue scoping. */
|
|
537
|
+
sessionKey: string; /** Store name where operation is defined. */
|
|
538
|
+
storeName: string; /** Store type for this queued operation. */
|
|
539
|
+
storeType: OfflineStoreType; /** Operation name registered in offline configuration. */
|
|
540
|
+
operation: string; /** Operation input payload persisted with the entry. */
|
|
541
|
+
input: TInput; /** Stable ordering key used to replay queued operations deterministically. */
|
|
542
|
+
queueOrder: number; /** Entity references tied to this mutation. */
|
|
543
|
+
entityRefs: OfflineEntityRef[]; /** Number of execution attempts so far. */
|
|
544
|
+
attempts: number; /** Queue entry creation timestamp. */
|
|
545
|
+
createdAt: number; /** Last entry update timestamp. */
|
|
546
|
+
updatedAt: number; /** Timestamp of last execution attempt, if any. */
|
|
547
|
+
lastAttemptAt: number | null; /** Synchronization state for this entry. */
|
|
548
|
+
syncState: OfflineSyncState; /** Optional temporary IDs for optimistic create operations. */
|
|
549
|
+
tempIds?: ValidPayload[]; /** Maps original direct-upload keys to their persisted session upload ids. */
|
|
550
|
+
attachedUploadIds?: OfflineAttachedUploadIds; /** Session upload ids that must resolve before replaying the mutation. */
|
|
551
|
+
dependencyUploadIds?: string[]; /** Last recorded sync error if replay failed. */
|
|
552
|
+
lastError?: {
|
|
553
|
+
message: string;
|
|
554
|
+
};
|
|
555
|
+
/**
|
|
556
|
+
* Whether a `needs-confirmation` entry may auto-resend during healthy replay
|
|
557
|
+
* retries after confirmation checks finish.
|
|
558
|
+
*/
|
|
559
|
+
allowReplayRetry?: boolean; /** Pending conflict payload when confirmation or resolution is required. */
|
|
560
|
+
pendingConflict?: TConflict;
|
|
561
|
+
};
|
|
562
|
+
/** Built-in resolution actions for retry exhaustion records. */
|
|
563
|
+
type OfflineRetryExhaustedResolutionAction = {
|
|
564
|
+
/** Requeues the failed mutation for another replay attempt. */action: 'retry';
|
|
565
|
+
/**
|
|
566
|
+
* Controls whether retrying a resolution should also requeue retryable
|
|
567
|
+
* descendants from the same temp-lifecycle dependency chain.
|
|
568
|
+
* @default 'self-and-descendants'
|
|
569
|
+
*/
|
|
570
|
+
scope?: 'self' | 'self-and-descendants';
|
|
571
|
+
} | {
|
|
572
|
+
/** Discards the exhausted mutation and clears its resolution record. */action: 'discard';
|
|
573
|
+
};
|
|
574
|
+
/**
|
|
575
|
+
* Built-in resolution actions for persisted conflict records.
|
|
576
|
+
*
|
|
577
|
+
* `commit` is intended for flows where the final API call has already been made
|
|
578
|
+
* externally and the store only needs to clear bookkeeping plus reconcile any
|
|
579
|
+
* temp-entity lifecycle using the accepted server result.
|
|
580
|
+
*
|
|
581
|
+
* @typeParam TInput - Input type expected when requeueing a replacement mutation.
|
|
582
|
+
* @typeParam TResult - Result shape returned by the external conflict resolution call.
|
|
583
|
+
*/
|
|
584
|
+
type OfflineConflictResolutionAction<TInput = unknown, TResult = unknown> = {
|
|
585
|
+
/** Discards the conflict and clears its resolution record. */action: 'discard';
|
|
586
|
+
} | {
|
|
587
|
+
/** Requeues the operation with replacement input. */action: 'requeue'; /** Replacement operation input. */
|
|
588
|
+
input: TInput;
|
|
589
|
+
} | {
|
|
590
|
+
/** Commits an externally resolved conflict and clears bookkeeping. */action: 'commit'; /** Result returned by the external conflict resolution call, when needed for reconciliation. */
|
|
591
|
+
result?: TResult;
|
|
592
|
+
};
|
|
593
|
+
/**
|
|
594
|
+
* Built-in resolution actions accepted by `resolveOfflineResolution(...)`.
|
|
595
|
+
*
|
|
596
|
+
* @typeParam TInput - Input type expected when requeueing a replacement mutation.
|
|
597
|
+
* @typeParam TResult - Result shape returned by an externally completed conflict resolution call.
|
|
598
|
+
*/
|
|
599
|
+
type OfflineResolutionAction<TInput = unknown, TResult = unknown> = OfflineRetryExhaustedResolutionAction | OfflineConflictResolutionAction<TInput, TResult>;
|
|
600
|
+
/**
|
|
601
|
+
* Extracts operation input type from a schema map.
|
|
602
|
+
*
|
|
603
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
604
|
+
* @typeParam TName - Operation name whose input type should be extracted.
|
|
605
|
+
*/
|
|
606
|
+
type OperationInput<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
607
|
+
inputSchema: PersistentStorageSchema<infer TInput>;
|
|
608
|
+
} ? TInput : never;
|
|
609
|
+
/**
|
|
610
|
+
* A typed operation descriptor for an offline mutation queue entry.
|
|
611
|
+
*
|
|
612
|
+
* @typeParam TOperations - Operation registry that defines valid operation names and input schemas.
|
|
613
|
+
* @typeParam TName - Operation name to describe. Defaults to all operation names in the registry.
|
|
614
|
+
*/
|
|
615
|
+
type OfflineMutationDescriptor<TOperations extends Record<string, {
|
|
616
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
617
|
+
}>, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: {
|
|
618
|
+
/** Operation key from the offline operations registry. */operation: K; /** Input resolved from the registered operation schema. */
|
|
619
|
+
input: OperationInput<TOperations, K>;
|
|
620
|
+
} }[TName];
|
|
621
|
+
/**
|
|
622
|
+
* Public offline mutation input accepted by store mutation APIs.
|
|
623
|
+
*
|
|
624
|
+
* Callers queue exactly one descriptor per mutation fallback.
|
|
625
|
+
*/
|
|
626
|
+
type OfflineMutationInput<TOperations extends Record<string, {
|
|
627
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
628
|
+
}>, TName extends keyof TOperations & string = keyof TOperations & string> = OfflineMutationDescriptor<TOperations, TName>;
|
|
629
|
+
/**
|
|
630
|
+
* Extracts operation result type from a registered operation map.
|
|
631
|
+
*
|
|
632
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
633
|
+
* @typeParam TName - Operation name whose result type should be extracted.
|
|
634
|
+
*/
|
|
635
|
+
type OperationResult<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
636
|
+
execute: (...args: __LEGIT_ANY__[]) => infer TResult;
|
|
637
|
+
} ? Awaited<TResult> : never;
|
|
638
|
+
/**
|
|
639
|
+
* Resolution action accepted for a specific registered offline operation.
|
|
640
|
+
*
|
|
641
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
642
|
+
* @typeParam TName - Operation name whose resolution payload should be extracted.
|
|
643
|
+
*/
|
|
644
|
+
type OfflineResolutionActionForOperation<TOperations, TName extends keyof TOperations> = OfflineResolutionAction<OperationInput<TOperations, TName>, OperationResult<TOperations, TName>>;
|
|
645
|
+
/**
|
|
646
|
+
* Context passed into offline mutation accumulation hooks.
|
|
647
|
+
*
|
|
648
|
+
* @typeParam TInput - Input type shared by the existing and incoming queued mutations.
|
|
649
|
+
*/
|
|
650
|
+
type OfflineAccumulationMergeContext<TInput> = {
|
|
651
|
+
/** Session key used to isolate queued mutations. */sessionKey: string; /** Existing input already present in queue. */
|
|
652
|
+
existingInput: TInput; /** Incoming input for merge attempt. */
|
|
653
|
+
incomingInput: TInput;
|
|
654
|
+
};
|
|
655
|
+
/**
|
|
656
|
+
* Optional in-memory accumulation strategy for queued offline mutations.
|
|
657
|
+
*
|
|
658
|
+
* @typeParam TInput - Input type that will be merged and revalidated before persisting.
|
|
659
|
+
*/
|
|
660
|
+
type OfflineAccumulationConfig<TInput> = {
|
|
661
|
+
/** Merge function for combining existing and incoming mutation inputs. */mergeInput: (ctx: OfflineAccumulationMergeContext<TInput>) => Promise<TInput> | TInput;
|
|
662
|
+
};
|
|
663
|
+
/**
|
|
664
|
+
* Optional queue-pruning strategy for queued offline mutations.
|
|
665
|
+
*
|
|
666
|
+
* `same-entity` only applies to operations that resolve exactly one entity ref.
|
|
667
|
+
* When enabled, the new operation may remove earlier unattempted pending entries
|
|
668
|
+
* targeting that same single entity before the new entry is persisted.
|
|
669
|
+
*/
|
|
670
|
+
type OfflineSupersedeConfig = {
|
|
671
|
+
/** Drop earlier unattempted pending entries for the same single entity. */scope: 'same-entity';
|
|
672
|
+
/**
|
|
673
|
+
* Limits which earlier operations may be pruned for that entity.
|
|
674
|
+
*
|
|
675
|
+
* Omit this to prune every earlier pending operation for the entity,
|
|
676
|
+
* use `'self'` to prune only earlier entries of the current operation,
|
|
677
|
+
* or provide explicit operation names to target a specific related set.
|
|
678
|
+
*/
|
|
679
|
+
operations?: 'self' | readonly string[];
|
|
680
|
+
/**
|
|
681
|
+
* When the pruned entries include a temp-entity lifecycle, drop the current
|
|
682
|
+
* operation itself instead of persisting a replacement entry.
|
|
683
|
+
*/
|
|
684
|
+
dropSelfIfTempLifecycleCancelled?: boolean;
|
|
685
|
+
};
|
|
686
|
+
/** Shared context passed to offline replay lifecycle hooks. */
|
|
687
|
+
type OperationBaseContext<TInput> = {
|
|
688
|
+
/** Input payload for the queued mutation currently being processed. */input: TInput; /** Timestamp when the operation was originally enqueued. */
|
|
689
|
+
enqueuedAt: number; /** Timestamp when the queued entry or conflict record was last updated. */
|
|
690
|
+
updatedAt: number;
|
|
691
|
+
/**
|
|
692
|
+
* Resolves a previously temp-backed entity ref to its latest known final ref
|
|
693
|
+
* when one has been reconciled.
|
|
694
|
+
*/
|
|
695
|
+
resolveEntityRef: <TEntityRef extends ValidPayload>(entityRef: TEntityRef) => TEntityRef;
|
|
696
|
+
};
|
|
697
|
+
type OperationExecuteContext<TInput, TUploadRef extends ValidPayload = ValidPayload> = OperationBaseContext<TInput> & {
|
|
698
|
+
uploads: OfflineOperationUploadsContext<TUploadRef>;
|
|
699
|
+
};
|
|
700
|
+
/** Context passed to the post-replay success hook after `execute(...)` settles. */
|
|
701
|
+
type OfflineOperationExecuteSuccessContext<TInput, TResult> = OperationBaseContext<TInput> & {
|
|
702
|
+
/** Replay result returned by `execute(...)`. */result: TResult;
|
|
703
|
+
};
|
|
704
|
+
/**
|
|
705
|
+
* Optional callback used to synchronize UI/cache state after a successful
|
|
706
|
+
* offline replay execute.
|
|
707
|
+
*/
|
|
708
|
+
type OfflineOperationExecuteSuccessHandler<TInput, TResult> = (ctx: OfflineOperationExecuteSuccessContext<TInput, TResult>) => Promise<void> | void;
|
|
709
|
+
type IsUnknown<T> = unknown extends T ? [keyof T] extends [never] ? true : false : false;
|
|
710
|
+
/** Context passed to replay checks that may use a fresh server snapshot. */
|
|
711
|
+
type OperationReplayCheckContext<TInput, TServerSnapshot> = OperationBaseContext<TInput> & {
|
|
712
|
+
/**
|
|
713
|
+
* Optional snapshot fetched immediately before `shouldSkipSync` and
|
|
714
|
+
* `detectConflict`.
|
|
715
|
+
*/
|
|
716
|
+
serverSnapshot: IsUnknown<TServerSnapshot> extends true ? undefined : TServerSnapshot;
|
|
717
|
+
};
|
|
718
|
+
/**
|
|
719
|
+
* Conflict hook configuration for a queued offline operation.
|
|
720
|
+
*
|
|
721
|
+
* @typeParam TInput - Input type of the queued operation being checked and potentially requeued.
|
|
722
|
+
* @typeParam TConflict - Conflict payload produced by detection and persisted for later external resolution.
|
|
723
|
+
*/
|
|
724
|
+
type OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot = unknown> = {
|
|
725
|
+
/** Schema used to validate and sanitize persisted conflict payloads. */schema: PersistentStorageSchema<TConflict>;
|
|
726
|
+
/**
|
|
727
|
+
* Inspect remote state before replaying the mutation and return conflict payload
|
|
728
|
+
* when the queued mutation can no longer be applied safely.
|
|
729
|
+
*/
|
|
730
|
+
detectConflict: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<TConflict | false | null> | TConflict | false | null;
|
|
731
|
+
};
|
|
732
|
+
type ConflictHandlingField<TInput, TConflict, TServerSnapshot> = IsUnknown<TConflict> extends true ? {
|
|
733
|
+
/**
|
|
734
|
+
* Optional conflict strategy when a queued operation diverges from remote state.
|
|
735
|
+
*/
|
|
736
|
+
conflictHandling?: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
|
|
737
|
+
} : {
|
|
738
|
+
/**
|
|
739
|
+
* Conflict strategy required when the operation declares a concrete
|
|
740
|
+
* conflict payload type.
|
|
741
|
+
*/
|
|
742
|
+
conflictHandling: OfflineConflictHandlingConfig<TInput, TConflict, TServerSnapshot>;
|
|
743
|
+
};
|
|
744
|
+
type ServerSnapshotField<TInput, TServerSnapshot> = IsUnknown<TServerSnapshot> extends true ? {
|
|
745
|
+
/**
|
|
746
|
+
* Optionally loads a fresh server-side snapshot before replay checks run.
|
|
747
|
+
* The result is passed to `shouldSkipSync` and `detectConflict` as
|
|
748
|
+
* `ctx.serverSnapshot`.
|
|
749
|
+
*/
|
|
750
|
+
getServerSnapshot?: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
|
|
751
|
+
} : {
|
|
752
|
+
/**
|
|
753
|
+
* Required when the operation declares a concrete server snapshot type.
|
|
754
|
+
* The result is passed to `shouldSkipSync` and `detectConflict` as
|
|
755
|
+
* `ctx.serverSnapshot`.
|
|
756
|
+
*/
|
|
757
|
+
getServerSnapshot: (ctx: OperationBaseContext<TInput>) => Promise<TServerSnapshot> | TServerSnapshot;
|
|
758
|
+
};
|
|
759
|
+
/**
|
|
760
|
+
* Replacement data returned by `tempEntity.reconcileServerEntity(...)`.
|
|
761
|
+
*
|
|
762
|
+
* @typeParam TFinalPayload - Final payload that should replace the temporary one.
|
|
763
|
+
* @typeParam TFinalData - Optional replacement entity data for the final payload.
|
|
764
|
+
*/
|
|
765
|
+
type OfflineTempEntityReconciliation<TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
766
|
+
/** Final payload that should replace the temporary optimistic one. */finalPayload: TFinalPayload;
|
|
767
|
+
/**
|
|
768
|
+
* Optional replacement data for the final payload.
|
|
769
|
+
* Omit this to keep the current optimistic entity data and only swap the
|
|
770
|
+
* payload/identity.
|
|
771
|
+
*/
|
|
772
|
+
finalData?: TFinalData;
|
|
773
|
+
};
|
|
774
|
+
/**
|
|
775
|
+
* Replacement data returned by `tempEntities.reconcileServerEntities(...)`.
|
|
776
|
+
*
|
|
777
|
+
* @typeParam TTempId - Temporary payload that should be reconciled.
|
|
778
|
+
* @typeParam TFinalPayload - Final payload that should replace the temporary one.
|
|
779
|
+
* @typeParam TFinalData - Optional replacement entity data for the final payload.
|
|
780
|
+
*/
|
|
781
|
+
type OfflineTempEntitiesReconciliation<TTempId extends ValidPayload = ValidPayload, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = OfflineTempEntityReconciliation<TFinalPayload, TFinalData> & {
|
|
782
|
+
/** Temporary payload that should be reconciled. */tempId: TTempId;
|
|
783
|
+
};
|
|
784
|
+
/**
|
|
785
|
+
* Pending temp-entity returned by `tempEntities.buildPendingEntities(...)`.
|
|
786
|
+
*
|
|
787
|
+
* @typeParam TTempId - Temporary payload used to track the optimistic entity.
|
|
788
|
+
* @typeParam TPendingEntity - Pending entity snapshot to insert locally.
|
|
789
|
+
*/
|
|
790
|
+
type OfflineTempEntityPendingEntry<TTempId extends ValidPayload = ValidPayload, TPendingEntity = unknown> = {
|
|
791
|
+
/** Temporary payload that identifies the optimistic entity. */tempId: TTempId; /** Pending entity snapshot inserted while the mutation is queued. */
|
|
792
|
+
pendingEntity: TPendingEntity;
|
|
793
|
+
};
|
|
794
|
+
/**
|
|
795
|
+
* Optional temp-id lifecycle for optimistic offline create flows.
|
|
796
|
+
*
|
|
797
|
+
* @typeParam TInput - Input type used to derive the temporary entity and identifier.
|
|
798
|
+
* @typeParam TTempResult - Result returned by `execute`, used only by `tempEntity.reconcileServerEntity(...)`.
|
|
799
|
+
* @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
|
|
800
|
+
*/
|
|
801
|
+
type OfflineTempEntityConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
802
|
+
/**
|
|
803
|
+
* Builds the optimistic entity inserted into local state while the mutation
|
|
804
|
+
* is queued offline.
|
|
805
|
+
*
|
|
806
|
+
* `tempId` is the temporary payload used to identify the optimistic entity
|
|
807
|
+
* until replay succeeds and the final server entity can replace it.
|
|
808
|
+
*/
|
|
809
|
+
buildPendingEntity: (input: TInput, tempId: TTempId) => TPendingEntity;
|
|
810
|
+
/**
|
|
811
|
+
* Reconciles the optimistic temp entity with the successful replay result.
|
|
812
|
+
*/
|
|
813
|
+
reconcileServerEntity: (result: TTempResult, tempId: TTempId) => OfflineTempEntityReconciliation<TFinalPayload, TFinalData>;
|
|
814
|
+
};
|
|
815
|
+
/**
|
|
816
|
+
* Optional temp-id lifecycle for optimistic offline batch-create flows.
|
|
817
|
+
*
|
|
818
|
+
* @typeParam TInput - Input type used to derive the temporary entities and identifiers.
|
|
819
|
+
* @typeParam TTempResult - Result returned by `execute`, used only by `tempEntities.reconcileServerEntities(...)`.
|
|
820
|
+
* @typeParam TTempId - Temporary payload used to track optimistic entities before reconciliation.
|
|
821
|
+
*/
|
|
822
|
+
type OfflineTempEntitiesConfig<TInput, TTempResult, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
823
|
+
/**
|
|
824
|
+
* Builds the optimistic entities inserted into local state while the mutation
|
|
825
|
+
* is queued offline.
|
|
826
|
+
*
|
|
827
|
+
* `tempIds` are the temporary payloads derived from the operation entity refs
|
|
828
|
+
* and used until replay succeeds and the final server entities can replace them.
|
|
829
|
+
*/
|
|
830
|
+
buildPendingEntities: (input: TInput, tempIds: readonly TTempId[]) => readonly OfflineTempEntityPendingEntry<TTempId, TPendingEntity>[];
|
|
831
|
+
/**
|
|
832
|
+
* Reconciles the optimistic temp entities with the successful replay result.
|
|
833
|
+
*/
|
|
834
|
+
reconcileServerEntities: (result: TTempResult, tempIds: readonly TTempId[]) => readonly OfflineTempEntitiesReconciliation<TTempId, TFinalPayload, TFinalData>[];
|
|
835
|
+
};
|
|
836
|
+
type NoTempEntityFields = {
|
|
837
|
+
tempEntity?: never;
|
|
838
|
+
tempEntities?: never;
|
|
839
|
+
};
|
|
840
|
+
type ConfiguredTempEntityFields<TInput, TTempResult, TTempId extends ValidPayload, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown> = {
|
|
841
|
+
tempEntity: OfflineTempEntityConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
|
|
842
|
+
tempEntities?: never;
|
|
843
|
+
} | {
|
|
844
|
+
tempEntity?: never;
|
|
845
|
+
tempEntities: OfflineTempEntitiesConfig<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>;
|
|
846
|
+
};
|
|
847
|
+
/**
|
|
848
|
+
* Shape used by `persistentStorage.offline.operations` for each operation name.
|
|
849
|
+
*
|
|
850
|
+
* @typeParam TInput - The persisted input payload for the queued offline operation.
|
|
851
|
+
* @typeParam TConflict - The conflict payload produced by pre-execution conflict detection.
|
|
852
|
+
* @typeParam TTempResult - Result returned by `execute`, used only when `tempEntity` or `tempEntities` needs to reconcile the final server entity. Defaults to `void`.
|
|
853
|
+
*/
|
|
854
|
+
type OfflineOperationDefinition<TInput, TConflict, TTempResult = void, TServerSnapshot = unknown, TTempId extends ValidPayload = string, TPendingEntity = unknown, TFinalPayload extends ValidPayload = ValidPayload, TFinalData = unknown, TUploadRef extends ValidPayload = ValidPayload> = {
|
|
855
|
+
/** Schema used to validate incoming operation input. */inputSchema: PersistentStorageSchema<TInput>; /** Lifecycle classification for the queued operation. */
|
|
856
|
+
kind: OfflineOperationKind;
|
|
857
|
+
/**
|
|
858
|
+
* Optional queue pruning for newer operations that supersede older queued work.
|
|
859
|
+
*
|
|
860
|
+
* This is mutually exclusive with `accumulation`.
|
|
861
|
+
*/
|
|
862
|
+
supersedes?: OfflineSupersedeConfig;
|
|
863
|
+
/**
|
|
864
|
+
* Executes the queued mutation against the remote source during replay.
|
|
865
|
+
* This may run multiple times when transient failures occur.
|
|
866
|
+
*/
|
|
867
|
+
execute: (ctx: OperationExecuteContext<TInput, TUploadRef>) => Promise<TTempResult> | TTempResult;
|
|
868
|
+
/**
|
|
869
|
+
* Optional check executed before retrying a previously failed sync attempt.
|
|
870
|
+
* Return `true` to drop the queued entry because the remote side already reflects it.
|
|
871
|
+
* Return `false` to continue with normal replay.
|
|
872
|
+
*/
|
|
873
|
+
shouldSkipSync?: (ctx: OperationReplayCheckContext<TInput, TServerSnapshot>) => Promise<boolean> | boolean;
|
|
874
|
+
} & ConflictHandlingField<TInput, TConflict, TServerSnapshot> & ServerSnapshotField<TInput, TServerSnapshot> & (({
|
|
875
|
+
/**
|
|
876
|
+
* Explicit store-sync step that runs after `execute(...)` succeeds during
|
|
877
|
+
* offline replay.
|
|
878
|
+
*
|
|
879
|
+
* Provide a callback when replay should update the live store after the
|
|
880
|
+
* server-side execute succeeds.
|
|
881
|
+
*/
|
|
882
|
+
onSuccessExecute: OfflineOperationExecuteSuccessHandler<TInput, TTempResult>;
|
|
883
|
+
/**
|
|
884
|
+
* Optional queue compaction for consecutive mutations with same refs.
|
|
885
|
+
*/
|
|
886
|
+
accumulation?: OfflineAccumulationConfig<TInput>;
|
|
887
|
+
} & NoTempEntityFields) | ({
|
|
888
|
+
/**
|
|
889
|
+
* Temp-entity operations already reconcile the live store through
|
|
890
|
+
* `tempEntity` / `tempEntities`, so they must not declare an extra
|
|
891
|
+
* success sync callback.
|
|
892
|
+
*/
|
|
893
|
+
onSuccessExecute?: undefined; /** Temp-entity operations cannot compact multiple queued creates. */
|
|
894
|
+
accumulation?: never;
|
|
895
|
+
} & ConfiguredTempEntityFields<TInput, TTempResult, TTempId, TPendingEntity, TFinalPayload, TFinalData>));
|
|
896
|
+
type WithoutTempEntity<T extends {
|
|
897
|
+
tempEntity?: unknown;
|
|
898
|
+
tempEntities?: unknown;
|
|
899
|
+
}> = Omit<T, 'tempEntity' | 'tempEntities'> & {
|
|
900
|
+
/** Document stores do not support optimistic temp entities. */tempEntity?: never; /** Document stores do not support optimistic batch temp entities. */
|
|
901
|
+
tempEntities?: never;
|
|
902
|
+
};
|
|
903
|
+
/** Context used to resolve which entities a queued mutation affects. */
|
|
904
|
+
type OperationEntityRefsContext<TInput> = {
|
|
905
|
+
/** Input payload for the queued mutation. */input: TInput;
|
|
906
|
+
};
|
|
907
|
+
/** Non-store-specific offline operation definition alias. */
|
|
908
|
+
type AnyOfflineOperationDefinition<TUploadRef extends ValidPayload = ValidPayload> = {
|
|
909
|
+
inputSchema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
910
|
+
kind: OfflineOperationKind;
|
|
911
|
+
conflictHandling?: {
|
|
912
|
+
schema: PersistentStorageSchema<__LEGIT_ANY__>;
|
|
913
|
+
detectConflict: (ctx: __LEGIT_ANY__) => unknown;
|
|
914
|
+
};
|
|
915
|
+
accumulation?: OfflineAccumulationConfig<__LEGIT_ANY__>;
|
|
916
|
+
supersedes?: OfflineSupersedeConfig;
|
|
917
|
+
tempEntity?: OfflineTempEntityConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
|
|
918
|
+
tempEntities?: OfflineTempEntitiesConfig<__LEGIT_ANY__, __LEGIT_ANY__, __LEGIT_ANY__>;
|
|
919
|
+
getServerSnapshot?: (ctx: OperationBaseContext<__LEGIT_ANY__>) => unknown;
|
|
920
|
+
execute: (ctx: OperationExecuteContext<__LEGIT_ANY__, TUploadRef>) => unknown;
|
|
921
|
+
onSuccessExecute?: OfflineOperationExecuteSuccessHandler<__LEGIT_ANY__, __LEGIT_ANY__>;
|
|
922
|
+
shouldSkipSync?: (ctx: OperationReplayCheckContext<__LEGIT_ANY__, __LEGIT_ANY__>) => Promise<boolean> | boolean;
|
|
923
|
+
} & {
|
|
924
|
+
getEntityRefs?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => unknown[];
|
|
925
|
+
dependsOn?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => __LEGIT_ANY__[];
|
|
926
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<__LEGIT_ANY__>) => string[];
|
|
927
|
+
};
|
|
928
|
+
/**
|
|
929
|
+
* Compact type-spec helper for a single offline operation.
|
|
930
|
+
*
|
|
931
|
+
* Use this helper with {@link DefineDocumentOfflineOperations} to describe each
|
|
932
|
+
* operation using generic parameters instead of inline object literals.
|
|
933
|
+
*
|
|
934
|
+
* The generic order is `input`, `conflict`, `temp result`, then `server snapshot`.
|
|
935
|
+
*
|
|
936
|
+
* @typeParam TInput - Input payload accepted by the operation.
|
|
937
|
+
* @typeParam TConflict - Conflict payload produced by optional conflict handling.
|
|
938
|
+
* @typeParam TTempResult - Result returned by `execute`, also reused when externally committed conflict resolution needs temp-entity reconciliation.
|
|
939
|
+
*
|
|
940
|
+
* @example
|
|
941
|
+
* ```ts
|
|
942
|
+
* type UpdateName = DefineOfflineOperation<
|
|
943
|
+
* { name: string },
|
|
944
|
+
* { remoteName: string },
|
|
945
|
+
* { name: string }
|
|
946
|
+
* >;
|
|
947
|
+
* ```
|
|
948
|
+
*/
|
|
949
|
+
type DefineOfflineOperation<TInput = unknown, TConflict = unknown, TTempResult = unknown, TServerSnapshot = unknown> = {
|
|
950
|
+
/** Input type accepted by the operation. */input?: TInput; /** Conflict payload type produced by the optional conflict handler. */
|
|
951
|
+
conflict?: TConflict; /** Result returned by `execute`, also reused by externally committed conflict resolution for temp-entity reconciliation. */
|
|
952
|
+
result?: TTempResult; /** Snapshot type returned by `getServerSnapshot` and exposed to replay checks. */
|
|
953
|
+
serverSnapshot?: TServerSnapshot;
|
|
954
|
+
};
|
|
955
|
+
type DocumentOperationInput<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
956
|
+
input?: infer TInput;
|
|
957
|
+
} ? TInput : unknown;
|
|
958
|
+
type DocumentOperationConflict<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
959
|
+
conflict?: infer TConflict;
|
|
960
|
+
} ? TConflict : unknown;
|
|
961
|
+
type DocumentOperationResult<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
962
|
+
result?: infer TTempResult;
|
|
963
|
+
} ? TTempResult : unknown;
|
|
964
|
+
type DocumentOperationServerSnapshot<TOptions extends DefineOfflineOperation> = TOptions extends {
|
|
965
|
+
serverSnapshot?: infer TServerSnapshot;
|
|
966
|
+
} ? TServerSnapshot : unknown;
|
|
967
|
+
/**
|
|
968
|
+
* Document-store specific offline operation definition.
|
|
969
|
+
*
|
|
970
|
+
* Prefer this alias when manually typing a single operation inside
|
|
971
|
+
* `persistentStorage.offline.operations` for a document store.
|
|
972
|
+
*
|
|
973
|
+
* `TOptions` is usually provided with {@link DefineOfflineOperation}, which lets
|
|
974
|
+
* callers specify the queued `input`, replay `result`, and optional `conflict`
|
|
975
|
+
* payload concisely. Document stores do not support `tempEntity`.
|
|
976
|
+
*
|
|
977
|
+
* Omitted properties default to `unknown`.
|
|
978
|
+
*
|
|
979
|
+
* @typeParam State - Document state type for the owning store.
|
|
980
|
+
* @typeParam TOptions - Operation typing options, usually created with {@link DefineOfflineOperation}.
|
|
981
|
+
*
|
|
982
|
+
* @example
|
|
983
|
+
* ```ts
|
|
984
|
+
* type RenameOperation = DocumentOfflineOperationDefinition<
|
|
985
|
+
* UserDoc,
|
|
986
|
+
* DefineOfflineOperation<
|
|
987
|
+
* { name: string },
|
|
988
|
+
* { remoteName: string },
|
|
989
|
+
* { name: string }
|
|
990
|
+
* >
|
|
991
|
+
* >;
|
|
992
|
+
* ```
|
|
993
|
+
*/
|
|
994
|
+
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>> & {
|
|
995
|
+
/** Declares which upload ids must finish before replaying this operation. */dependsOnUploads?: (ctx: OperationEntityRefsContext<DocumentOperationInput<TOptions>>) => string[];
|
|
996
|
+
} & ([State] extends [never] ? never : unknown);
|
|
997
|
+
/**
|
|
998
|
+
* Builds a document offline operations map from a compact operation spec.
|
|
999
|
+
*
|
|
1000
|
+
* This is the recommended way to type a document store's full offline operation map.
|
|
1001
|
+
* Each operation key is typically described with {@link DefineOfflineOperation},
|
|
1002
|
+
* and this helper expands that into the full
|
|
1003
|
+
* {@link DocumentOfflineOperationDefinition} map expected by the store.
|
|
1004
|
+
*
|
|
1005
|
+
* @typeParam State - Document state type for the owning store.
|
|
1006
|
+
* @typeParam TOperations - Operation map where each key declares its input, replay result, and optional conflict payload.
|
|
1007
|
+
*
|
|
1008
|
+
* @example
|
|
1009
|
+
* ```ts
|
|
1010
|
+
* type Operations = DefineDocumentOfflineOperations<
|
|
1011
|
+
* UserDoc,
|
|
1012
|
+
* {
|
|
1013
|
+
* updateName: DefineOfflineOperation<
|
|
1014
|
+
* { name: string },
|
|
1015
|
+
* unknown,
|
|
1016
|
+
* { name: string }
|
|
1017
|
+
* >;
|
|
1018
|
+
* archive: DefineOfflineOperation<
|
|
1019
|
+
* { reason: string },
|
|
1020
|
+
* { code: string }
|
|
1021
|
+
* >;
|
|
1022
|
+
* }
|
|
1023
|
+
* >;
|
|
1024
|
+
* ```
|
|
1025
|
+
*
|
|
1026
|
+
* Then use the resulting type as the `operations` object contract:
|
|
1027
|
+
*
|
|
1028
|
+
* ```ts
|
|
1029
|
+
* const operations: Operations = {
|
|
1030
|
+
* updateName: {
|
|
1031
|
+
* inputSchema: z.object({ name: z.string() }),
|
|
1032
|
+
* kind: 'update',
|
|
1033
|
+
* execute: ({ input }) => ({ name: input.name }),
|
|
1034
|
+
* },
|
|
1035
|
+
* archive: {
|
|
1036
|
+
* inputSchema: z.object({ reason: z.string() }),
|
|
1037
|
+
* kind: 'delete',
|
|
1038
|
+
* conflictHandling: {
|
|
1039
|
+
* schema: z.object({ code: z.string() }),
|
|
1040
|
+
* detectConflict: () => false,
|
|
1041
|
+
* },
|
|
1042
|
+
* execute: () => undefined,
|
|
1043
|
+
* },
|
|
1044
|
+
* };
|
|
1045
|
+
* ```
|
|
1046
|
+
*/
|
|
1047
|
+
type DefineDocumentOfflineOperations<State extends ValidStoreState, TOperations extends Record<string, DefineOfflineOperation>, TUploadRef extends ValidPayload = ValidPayload> = { [TName in keyof TOperations]: DocumentOfflineOperationDefinition<State, TOperations[TName], TUploadRef> };
|
|
1048
|
+
/**
|
|
1049
|
+
* Collection offline entity reference.
|
|
1050
|
+
*
|
|
1051
|
+
* Collection operations return raw item payloads, which are normalized to the
|
|
1052
|
+
* internal item key by the store.
|
|
1053
|
+
*
|
|
1054
|
+
* @typeParam ItemPayload - Collection item payload type for the owning store.
|
|
1055
|
+
*/
|
|
1056
|
+
type CollectionOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
|
|
1057
|
+
/**
|
|
1058
|
+
* Collection-store specific offline operation definition.
|
|
1059
|
+
*
|
|
1060
|
+
* @typeParam ItemState - Collection item state type for the owning store.
|
|
1061
|
+
* @typeParam ItemPayloadUnused - Collection payload type used to anchor the operation to the owning store type.
|
|
1062
|
+
* @typeParam TInput - Input type accepted by the offline operation.
|
|
1063
|
+
* @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
|
|
1064
|
+
* @typeParam TTempResult - Result returned by `execute`.
|
|
1065
|
+
* When `tempEntity` or `tempEntities` is provided, the pending builders must
|
|
1066
|
+
* return `ItemState`, and the reconciliation hooks must return an
|
|
1067
|
+
* `ItemPayload` plus optional `ItemState` replacement data.
|
|
1068
|
+
*/
|
|
1069
|
+
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> & {
|
|
1070
|
+
/**
|
|
1071
|
+
* Declares which collection items are affected by this queued mutation.
|
|
1072
|
+
*
|
|
1073
|
+
* Return the raw collection payloads for the affected items. The store will
|
|
1074
|
+
* convert each payload with the configured item key logic.
|
|
1075
|
+
*/
|
|
1076
|
+
getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[];
|
|
1077
|
+
/**
|
|
1078
|
+
* Declares which collection item refs must resolve before replaying this
|
|
1079
|
+
* operation.
|
|
1080
|
+
*/
|
|
1081
|
+
dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => CollectionOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
|
|
1082
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
|
|
1083
|
+
} & ([ItemState | ItemPayloadUnused] extends [never] ? never : unknown);
|
|
1084
|
+
/**
|
|
1085
|
+
* Builds a collection offline operations map from a compact operation spec.
|
|
1086
|
+
*
|
|
1087
|
+
* Use this helper to define the full `persistentStorage.offline.operations` contract for a
|
|
1088
|
+
* collection store while keeping each operation's type declaration short.
|
|
1089
|
+
*
|
|
1090
|
+
* Each operation key is described with {@link DefineOfflineOperation}, and this
|
|
1091
|
+
* helper expands it into the corresponding
|
|
1092
|
+
* {@link CollectionOfflineOperationDefinition}. The runtime operation object
|
|
1093
|
+
* still needs to provide `getEntityRefs(...)`.
|
|
1094
|
+
*
|
|
1095
|
+
* @typeParam ItemState - Collection item state type for the owning store.
|
|
1096
|
+
* @typeParam ItemPayload - Collection payload type for the owning store.
|
|
1097
|
+
* @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
|
|
1098
|
+
*
|
|
1099
|
+
* @example
|
|
1100
|
+
* ```ts
|
|
1101
|
+
* type Operations = DefineCollectionOfflineOperations<
|
|
1102
|
+
* TodoItem,
|
|
1103
|
+
* string,
|
|
1104
|
+
* {
|
|
1105
|
+
* renameTodo: DefineOfflineOperation<
|
|
1106
|
+
* { id: string; title: string }
|
|
1107
|
+
* >;
|
|
1108
|
+
* createTodo: DefineOfflineOperation<
|
|
1109
|
+
* { title: string },
|
|
1110
|
+
* unknown,
|
|
1111
|
+
* { id: string; title: string }
|
|
1112
|
+
* >;
|
|
1113
|
+
* }
|
|
1114
|
+
* >;
|
|
1115
|
+
* ```
|
|
1116
|
+
*/
|
|
1117
|
+
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> };
|
|
1118
|
+
/**
|
|
1119
|
+
* List-query offline entity reference.
|
|
1120
|
+
*
|
|
1121
|
+
* List-query operations return raw item payloads, which are normalized to the
|
|
1122
|
+
* internal item key by the store.
|
|
1123
|
+
*
|
|
1124
|
+
* @typeParam ItemPayload - Item payload type for the owning list-query store.
|
|
1125
|
+
*/
|
|
1126
|
+
type ListQueryOfflineEntityRef<ItemPayload extends ValidPayload> = ItemPayload;
|
|
1127
|
+
/**
|
|
1128
|
+
* List-query-store specific offline operation definition.
|
|
1129
|
+
*
|
|
1130
|
+
* @typeParam ItemState - List item state type for the owning store.
|
|
1131
|
+
* @typeParam QueryPayload - Query payload type used by the list store.
|
|
1132
|
+
* @typeParam ItemPayloadUnused - Item payload type used to anchor the operation to the owning store type.
|
|
1133
|
+
* @typeParam TInput - Input type accepted by the offline operation.
|
|
1134
|
+
* @typeParam TConflict - Conflict payload type produced by the optional conflict handler.
|
|
1135
|
+
* @typeParam TTempResult - Result returned by `execute`.
|
|
1136
|
+
* When `tempEntity` or `tempEntities` is provided, the pending builders must
|
|
1137
|
+
* return `ItemState`, and the reconciliation hooks must return an
|
|
1138
|
+
* `ItemPayload` plus optional `ItemState` replacement data.
|
|
1139
|
+
*/
|
|
1140
|
+
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> & {
|
|
1141
|
+
/**
|
|
1142
|
+
* Declares which list-query entities are affected by this queued mutation.
|
|
1143
|
+
*
|
|
1144
|
+
* Return the raw item payloads for the affected items. The store will
|
|
1145
|
+
* convert each payload with the configured item key logic.
|
|
1146
|
+
*/
|
|
1147
|
+
getEntityRefs: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[];
|
|
1148
|
+
/**
|
|
1149
|
+
* Declares which list item refs must resolve before replaying this
|
|
1150
|
+
* operation.
|
|
1151
|
+
*/
|
|
1152
|
+
dependsOn?: (ctx: OperationEntityRefsContext<TInput>) => ListQueryOfflineEntityRef<ItemPayloadUnused>[]; /** Declares which upload ids must finish before replaying this operation. */
|
|
1153
|
+
dependsOnUploads?: (ctx: OperationEntityRefsContext<TInput>) => string[];
|
|
1154
|
+
} & ([ItemState | QueryPayload | ItemPayloadUnused] extends [never] ? never : unknown);
|
|
1155
|
+
/**
|
|
1156
|
+
* Builds a list-query offline operations map from a compact operation spec.
|
|
1157
|
+
*
|
|
1158
|
+
* Use this helper to define the full `persistentStorage.offline.operations` contract for a
|
|
1159
|
+
* list-query store while keeping each operation's type declaration short.
|
|
1160
|
+
*
|
|
1161
|
+
* Each operation key is described with {@link DefineOfflineOperation}, and this
|
|
1162
|
+
* helper expands it into the corresponding
|
|
1163
|
+
* {@link ListQueryOfflineOperationDefinition}. The runtime operation object
|
|
1164
|
+
* still needs to provide `getEntityRefs(...)`.
|
|
1165
|
+
*
|
|
1166
|
+
* @typeParam ItemState - List item state type for the owning store.
|
|
1167
|
+
* @typeParam QueryPayload - Query payload type used by the list store.
|
|
1168
|
+
* @typeParam ItemPayload - Item payload type used by the list store.
|
|
1169
|
+
* @typeParam TOperations - Operation map where each key declares its input, optional conflict payload, and optional temp-result type.
|
|
1170
|
+
*
|
|
1171
|
+
* @example
|
|
1172
|
+
* ```ts
|
|
1173
|
+
* type Operations = DefineListQueryOfflineOperations<
|
|
1174
|
+
* User,
|
|
1175
|
+
* { tableId: 'users' },
|
|
1176
|
+
* { tableId: 'users'; id: number } | string,
|
|
1177
|
+
* {
|
|
1178
|
+
* renameUser: DefineOfflineOperation<
|
|
1179
|
+
* { id: number; name: string }
|
|
1180
|
+
* >;
|
|
1181
|
+
* createUser: DefineOfflineOperation<
|
|
1182
|
+
* { name: string },
|
|
1183
|
+
* unknown,
|
|
1184
|
+
* { id: number; name: string }
|
|
1185
|
+
* >;
|
|
1186
|
+
* }
|
|
1187
|
+
* >;
|
|
1188
|
+
* ```
|
|
1189
|
+
*/
|
|
1190
|
+
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> };
|
|
1191
|
+
/**
|
|
1192
|
+
* Extracts operation conflict payload from a registered operation map.
|
|
1193
|
+
*
|
|
1194
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1195
|
+
* @typeParam TName - Operation name whose conflict payload should be extracted.
|
|
1196
|
+
*/
|
|
1197
|
+
type OperationConflict<TOperations, TName extends keyof TOperations> = TOperations[TName] extends {
|
|
1198
|
+
conflictHandling?: OfflineConflictHandlingConfig<__LEGIT_ANY__, infer TConflict>;
|
|
1199
|
+
} ? TConflict : never;
|
|
1200
|
+
/**
|
|
1201
|
+
* Result returned when decoding a stored offline conflict payload.
|
|
1202
|
+
*
|
|
1203
|
+
* `ok: true` contains the typed conflict payload. `ok: false` contains a
|
|
1204
|
+
* machine-readable parse error describing why decoding was not possible.
|
|
1205
|
+
*/
|
|
1206
|
+
type ParsedOfflineResolutionConflictResultForOperation<TOperations, TName extends keyof TOperations & string> = Result<OperationConflict<TOperations, TName>, OfflineResolutionConflictParseError>;
|
|
1207
|
+
type ParsedOfflineResolutionConflictResultForStore<TOperations> = ParsedOfflineResolutionConflictResultForOperation<TOperations, keyof TOperations & string>;
|
|
1208
|
+
/**
|
|
1209
|
+
* Operation-aware offline resolution record for a specific registered operation.
|
|
1210
|
+
*
|
|
1211
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1212
|
+
* @typeParam TName - Operation name whose stored resolution shape should be extracted.
|
|
1213
|
+
*/
|
|
1214
|
+
type OfflineResolutionRecordForOperation<TOperations, TName extends keyof TOperations & string> = (OfflineConflictResolutionRecord<OperationConflict<TOperations, TName>, OperationInput<TOperations, TName>> & {
|
|
1215
|
+
/** Operation name associated with this resolution record. */operation: TName;
|
|
1216
|
+
}) | (OfflineRetryExhaustedResolutionRecord<OperationInput<TOperations, TName>> & {
|
|
1217
|
+
/** Operation name associated with this resolution record. */operation: TName;
|
|
1218
|
+
});
|
|
1219
|
+
/**
|
|
1220
|
+
* Union of operation-aware offline resolution records for an operation registry.
|
|
1221
|
+
*
|
|
1222
|
+
* @typeParam TOperations - Operation registry to inspect.
|
|
1223
|
+
* @typeParam TName - Optional subset of operation names to include.
|
|
1224
|
+
*/
|
|
1225
|
+
type OfflineResolutionRecordForStore<TOperations, TName extends keyof TOperations & string = keyof TOperations & string> = { [K in TName]: OfflineResolutionRecordForOperation<TOperations, K> }[TName];
|
|
1226
|
+
/** Failure code returned when parsing a stored offline conflict payload. */
|
|
1227
|
+
type OfflineResolutionConflictParseErrorCode = 'not-conflict' | 'offline-not-configured' | 'operation-not-found' | 'conflict-handling-missing' | 'invalid-conflict-payload';
|
|
1228
|
+
/** Error returned when decoding a stored offline conflict payload fails. */
|
|
1229
|
+
declare class OfflineResolutionConflictParseError extends Error {
|
|
1230
|
+
code: OfflineResolutionConflictParseErrorCode;
|
|
1231
|
+
operation: string;
|
|
1232
|
+
kind?: OfflineResolutionRecord['kind'];
|
|
1233
|
+
rawValue?: unknown;
|
|
1234
|
+
validationError?: SchemaValidationError;
|
|
1235
|
+
constructor(args: {
|
|
1236
|
+
code: OfflineResolutionConflictParseErrorCode;
|
|
1237
|
+
operation: string;
|
|
1238
|
+
kind?: OfflineResolutionRecord['kind'];
|
|
1239
|
+
rawValue?: unknown;
|
|
1240
|
+
validationError?: SchemaValidationError;
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
//#endregion
|
|
1244
|
+
//#region src/persistentStorage/types.d.ts
|
|
1245
|
+
/** Logical namespaces used by managed async persistent storage. */
|
|
1246
|
+
type AsyncStorageNamespaceKind = 'document' | 'collection.item' | 'listQuery.item' | 'listQuery.query' | 'offline.queue' | 'offline.conflict' | 'offline.entity' | '__internal.protected';
|
|
1247
|
+
/** Identifies one logical persistent-storage namespace. */
|
|
1248
|
+
type AsyncStorageNamespaceScope = {
|
|
1249
|
+
/** Session key owning this namespace. */sessionKey: string; /** Store id owning this namespace. */
|
|
1250
|
+
storeName: string; /** Type of records stored in this namespace. */
|
|
1251
|
+
kind: AsyncStorageNamespaceKind;
|
|
1252
|
+
};
|
|
1253
|
+
type AsyncStorageTouchMode = 'never' | 'coarse' | 'force';
|
|
1254
|
+
/** Read behavior for managed async namespace operations. */
|
|
1255
|
+
type AsyncStorageReadOptions = {
|
|
1256
|
+
/** Whether reading should update LRU access metadata. */touch?: AsyncStorageTouchMode;
|
|
1257
|
+
};
|
|
1258
|
+
/** Sort order for listing async storage metadata. */
|
|
1259
|
+
type AsyncStorageMetadataOrder = 'key' | 'lru-asc' | 'lru-desc';
|
|
1260
|
+
type AsyncStorageEntryMetadataBase = {
|
|
1261
|
+
key: string;
|
|
1262
|
+
payloadRef: string;
|
|
1263
|
+
writtenAt: number;
|
|
1264
|
+
lastAccessAt: number; /** Serialized JSON size used for persistence budgeting for this entry. */
|
|
1265
|
+
sizeBytes?: number;
|
|
1266
|
+
version: number;
|
|
1267
|
+
};
|
|
1268
|
+
type AsyncStorageEntryMetadata<TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = AsyncStorageEntryMetadataBase & {
|
|
1269
|
+
customMetadata: TCustomMetadata;
|
|
1270
|
+
};
|
|
1271
|
+
/** Value and metadata returned from a managed async namespace read. */
|
|
1272
|
+
type AsyncStorageNamespaceGetResult<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1273
|
+
/** Stored value decoded from the namespace. */value: TValue; /** Managed metadata associated with the stored value. */
|
|
1274
|
+
metadata: AsyncStorageEntryMetadata<TCustomMetadata>;
|
|
1275
|
+
};
|
|
1276
|
+
/** Upsert entry committed to a managed async namespace. */
|
|
1277
|
+
type AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1278
|
+
/** Raw namespace key to write. */key: string; /** Decoded value to store. */
|
|
1279
|
+
value: TValue; /** Pre-serialized JSON string, when the caller already has it. */
|
|
1280
|
+
serializedValue?: string; /** Serialized JSON size used for persistence budgeting. */
|
|
1281
|
+
sizeBytes?: number; /** Cache version associated with this value. */
|
|
1282
|
+
version: number; /** Custom metadata stored alongside the value. */
|
|
1283
|
+
metadata?: TCustomMetadata;
|
|
1284
|
+
};
|
|
1285
|
+
/** Touch entry committed to update managed async namespace LRU metadata. */
|
|
1286
|
+
type AsyncStorageNamespaceCommitTouch = {
|
|
1287
|
+
/** Raw namespace key to touch. */key: string; /** Explicit access timestamp. Defaults to the adapter's current time. */
|
|
1288
|
+
lastAccessAt?: number;
|
|
1289
|
+
};
|
|
1290
|
+
type AsyncStorageNamespaceStaticPolicy = {
|
|
1291
|
+
maxBytes?: number;
|
|
1292
|
+
pinnedKeys?: string[];
|
|
1293
|
+
};
|
|
1294
|
+
/** Batched write/remove/touch operation for a managed async namespace. */
|
|
1295
|
+
type AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1296
|
+
/** Entries to create or replace. */upserts?: AsyncStorageNamespaceCommitUpsert<TValue, TCustomMetadata>[]; /** Raw namespace keys to remove. */
|
|
1297
|
+
removes?: string[]; /** Static cleanup policy applied during this commit. */
|
|
1298
|
+
staticPolicy?: AsyncStorageNamespaceStaticPolicy | null; /** Existing entries whose access metadata should be updated. */
|
|
1299
|
+
touches?: AsyncStorageNamespaceCommitTouch[];
|
|
1300
|
+
};
|
|
1301
|
+
/** Raw entry passed to low-level async storage driver bulk writes. */
|
|
1302
|
+
type AsyncStorageDriverSetEntry = {
|
|
1303
|
+
/** Raw record key to write. */key: string; /** Raw value to store. */
|
|
1304
|
+
value: unknown; /** Pre-serialized JSON string, when available. */
|
|
1305
|
+
serializedValue?: string; /** Serialized value size used for budgeting. */
|
|
1306
|
+
sizeBytes?: number;
|
|
1307
|
+
};
|
|
1308
|
+
/** Scope discovered by a low-level async storage driver. */
|
|
1309
|
+
type AsyncStorageDiscoveredScope = {
|
|
1310
|
+
/** Known raw record keys for this scope. `null` if keys were not enumerated during discovery. */knownRecordKeys: string[] | null; /** Discovered namespace scope. */
|
|
1311
|
+
scope: AsyncStorageNamespaceScope;
|
|
1312
|
+
};
|
|
1313
|
+
/** Low-level async backend contract implemented by custom storage drivers. */
|
|
1314
|
+
type AsyncStorageDriver = {
|
|
1315
|
+
/** Read a single raw record from a logical namespace. */get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
|
|
1316
|
+
set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
|
|
1317
|
+
remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
|
|
1318
|
+
listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
|
|
1319
|
+
clear(scope: AsyncStorageNamespaceScope): Promise<void>; /** Namespace discovery used for cold cleanup, protected-key restore, and session clearing. */
|
|
1320
|
+
listScopes(sessionKey?: string): Promise<AsyncStorageNamespaceScope[]>; /** Returns discovered scopes together with known raw record keys. Used for cleanup. */
|
|
1321
|
+
listScopesWithKnownRecordKeys(sessionKey?: string): Promise<AsyncStorageDiscoveredScope[]>; /** Bulk read for multiple keys in a single call. */
|
|
1322
|
+
getMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<unknown[]>; /** Bulk write for multiple entries in a single call. */
|
|
1323
|
+
setMany(scope: AsyncStorageNamespaceScope, entries: AsyncStorageDriverSetEntry[]): Promise<void>; /** Bulk remove for multiple keys in a single call. */
|
|
1324
|
+
removeMany(scope: AsyncStorageNamespaceScope, keys: string[]): Promise<void>;
|
|
1325
|
+
};
|
|
1326
|
+
/** Managed namespace handle opened by an async storage adapter. */
|
|
1327
|
+
type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>> = {
|
|
1328
|
+
/** Reads one decoded value and metadata by raw namespace key. */get(key: string, options?: AsyncStorageReadOptions): Promise<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>; /** Reads many decoded values and metadata records by raw namespace key. */
|
|
1329
|
+
getMany(keys: string[], options?: AsyncStorageReadOptions): Promise<Array<AsyncStorageNamespaceGetResult<TValue, TCustomMetadata> | null>>; /** Lists raw record keys in this namespace. */
|
|
1330
|
+
listKeys(): Promise<string[]>; /** Applies batched writes, removes, touches, and cleanup policy changes. */
|
|
1331
|
+
commit(args: AsyncStorageNamespaceCommitArgs<TValue, TCustomMetadata>): Promise<void>; /** Lists metadata for all records in this namespace. */
|
|
1332
|
+
listMetadata(args?: {
|
|
1333
|
+
order?: AsyncStorageMetadataOrder;
|
|
1334
|
+
}): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>; /** Lists metadata matching a custom metadata equality filter. */
|
|
1335
|
+
listMetadataByFilter?(args: {
|
|
1336
|
+
filter: {
|
|
1337
|
+
equals: unknown;
|
|
1338
|
+
key: string;
|
|
1339
|
+
};
|
|
1340
|
+
order?: AsyncStorageMetadataOrder;
|
|
1341
|
+
}): Promise<AsyncStorageEntryMetadata<TCustomMetadata>[]>; /** Removes every record in this namespace. */
|
|
1342
|
+
clear(): Promise<void>;
|
|
1343
|
+
};
|
|
1344
|
+
/** Managed async adapter consumed by TSDF persistence internals. */
|
|
1345
|
+
type AsyncStorageAdapter = {
|
|
1346
|
+
/** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Open a logical namespace with managed batching and touch guarantees. */
|
|
1347
|
+
openNamespace<TValue, TCustomMetadata extends Record<string, unknown> = Record<string, unknown>>(scope: AsyncStorageNamespaceScope): AsyncStorageNamespaceHandle<TValue, TCustomMetadata>; /** Reconstruct offline-protected entry refs for a session from persisted metadata. */
|
|
1348
|
+
readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
|
|
1349
|
+
syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
|
|
1350
|
+
clearSession(sessionKey: string): Promise<void>; /** Test-only reset hook used by TSDF internals. */
|
|
1351
|
+
resetForTests?(): void;
|
|
1352
|
+
};
|
|
1353
|
+
/** Injected persistent storage adapter. */
|
|
1354
|
+
type StorageAdapter = 'local-sync' | AsyncStorageAdapter;
|
|
1355
|
+
/** Standard Schema v1 (zod, valibot, arktype, etc.). */
|
|
1356
|
+
type StandardSchemaLike<T> = StandardSchemaV1<unknown, T>;
|
|
1357
|
+
/** Union of supported schema types for persistent storage validation. */
|
|
1358
|
+
type PersistentStorageSchema<T> = RcType<T> | StandardSchemaLike<T>;
|
|
1359
|
+
/**
|
|
1360
|
+
* Converts between the in-memory store data shape and the persisted storage shape.
|
|
1361
|
+
* Use this when the cached representation should differ from the API store format.
|
|
1362
|
+
*/
|
|
1363
|
+
type ConvertedPersistentStorageDataSchema<TFinal, TStorage> = {
|
|
1364
|
+
/** Schema for the final in-memory store data after hydration. */storeSchema: PersistentStorageSchema<TFinal>; /** Schema for the raw persisted storage representation. */
|
|
1365
|
+
storageSchema: PersistentStorageSchema<TStorage>; /** Converts in-memory store data into the persisted storage representation. */
|
|
1366
|
+
convertToStorage: (value: TFinal) => TStorage; /** Converts persisted storage data into the final in-memory store representation. */
|
|
1367
|
+
convertFromStorage: (value: TStorage) => TFinal;
|
|
1368
|
+
};
|
|
1369
|
+
/**
|
|
1370
|
+
* Schema configuration for persisted store data.
|
|
1371
|
+
* Accept either the final store schema directly or a converted storage format.
|
|
1372
|
+
*/
|
|
1373
|
+
type PersistentStorageDataSchema<TFinal, TStorage = unknown> = PersistentStorageSchema<TFinal> | ConvertedPersistentStorageDataSchema<TFinal, TStorage>;
|
|
1374
|
+
/** Result entry returned by explicit persistent-storage preload APIs. */
|
|
1375
|
+
type PersistentStoragePreloadResult<Payload extends ValidPayload = ValidPayload> = {
|
|
1376
|
+
/** Payload loaded from storage or fresh store initialization result. */payload: Payload; /** `true` when payload came from storage cache, `false` when loaded from source. */
|
|
1377
|
+
preloaded: boolean;
|
|
1378
|
+
};
|
|
1379
|
+
type PersistentStorageErrorHandler = (error: unknown) => void;
|
|
1380
|
+
/** Base config shared by all store types. */
|
|
1381
|
+
type PersistentStorageBaseConfig<TFinal, TStorage = unknown> = {
|
|
1382
|
+
/** 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. */
|
|
1383
|
+
adapter: StorageAdapter; /** Schema used to validate cached data on load and optionally convert persisted data. */
|
|
1384
|
+
schema: PersistentStorageDataSchema<TFinal, TStorage>; /** Optional version number for cache invalidation. When omitted, no version is persisted or checked. */
|
|
1385
|
+
version?: number;
|
|
1386
|
+
/**
|
|
1387
|
+
* Returns a session key scoping storage per org/tenant.
|
|
1388
|
+
* Return `false` to indicate the session is not ready — all storage
|
|
1389
|
+
* operations (load, save, clear) will be skipped until it returns a string.
|
|
1390
|
+
*/
|
|
1391
|
+
getSessionKey: () => string | false;
|
|
1392
|
+
/**
|
|
1393
|
+
* Called when a storage write operation fails (e.g. quota exceeded, OPFS write error).
|
|
1394
|
+
* Use this to log or report persistence failures to your error tracking service.
|
|
1395
|
+
*/
|
|
1396
|
+
onPersistentStorageError?: PersistentStorageErrorHandler | null;
|
|
1397
|
+
};
|
|
1398
|
+
/** Store-level persistent storage config. Session scoping comes from the parent store. */
|
|
1399
|
+
type StorePersistentStorageBaseConfig<TFinal, TStorage = unknown> = Omit<PersistentStorageBaseConfig<TFinal, TStorage>, 'getSessionKey' | 'storeName'>;
|
|
1400
|
+
type InternalDocumentOfflineOperations<State extends ValidStoreState> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> & ([State] extends [never] ? never : unknown);
|
|
1401
|
+
type DocumentOfflineOperationsConfig<State extends ValidStoreState> = InternalDocumentOfflineOperations<State> | null;
|
|
1402
|
+
type PublicStoreOfflineConfig<TOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> = Record<never, never>> = {
|
|
1403
|
+
/** Store-local offline operation definitions. Optional when only session-level offline controls are used. */operations?: TOperations;
|
|
1404
|
+
};
|
|
1405
|
+
type PublicStoreOfflineConfigField<TOfflineOperations extends Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__>> | null> = {
|
|
1406
|
+
/** Optional offline sync/replay configuration for mutations. */offline?: TOfflineOperations extends null ? PublicStoreOfflineConfig : PublicStoreOfflineConfig<Exclude<TOfflineOperations, null>>;
|
|
1407
|
+
};
|
|
1408
|
+
/** Persistent storage config for DocumentStore. */
|
|
1409
|
+
type DocumentPersistentStorageConfig<State extends ValidStoreState, StorageState = unknown, TOfflineOperations extends DocumentOfflineOperationsConfig<State> = null> = StorePersistentStorageBaseConfig<State, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations>;
|
|
1410
|
+
type InternalCollectionOfflineOperations<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
|
|
1411
|
+
getEntityRefs: (ctx: {
|
|
1412
|
+
input: __LEGIT_ANY__;
|
|
1413
|
+
}) => CollectionOfflineEntityRef<ItemPayload>[];
|
|
1414
|
+
dependsOn?: (ctx: {
|
|
1415
|
+
input: __LEGIT_ANY__;
|
|
1416
|
+
}) => CollectionOfflineEntityRef<ItemPayload>[];
|
|
1417
|
+
}> & ([ItemState | ItemPayload] extends [never] ? never : unknown);
|
|
1418
|
+
type CollectionOfflineOperationsConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = InternalCollectionOfflineOperations<ItemState, ItemPayload> | null;
|
|
1419
|
+
type CollectionPersistentStorageFields<ItemPayload extends ValidPayload> = {
|
|
1420
|
+
/** Schema used to validate cached item payloads on load. */payloadSchema: PersistentStorageSchema<ItemPayload>;
|
|
1421
|
+
/**
|
|
1422
|
+
* Maximum serialized JSON size to persist for collection items. Budgeting
|
|
1423
|
+
* uses the serialized string length, not browser quota bytes. Items are
|
|
1424
|
+
* evicted via LRU. Defaults to 64 KB in `local-sync` and 128 KB in async
|
|
1425
|
+
* adapters.
|
|
1426
|
+
*/
|
|
1427
|
+
maxBytes?: number; /** Item payloads that should never be evicted from storage. */
|
|
1428
|
+
pinnedItems?: ItemPayload[];
|
|
1429
|
+
/**
|
|
1430
|
+
* Item payloads that should never be persisted or restored.
|
|
1431
|
+
* Accepts either an explicit payload list or a predicate function.
|
|
1432
|
+
* Takes precedence over `pinnedItems`.
|
|
1433
|
+
*/
|
|
1434
|
+
ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
|
|
1435
|
+
};
|
|
1436
|
+
/** Persistent storage config for CollectionStore. */
|
|
1437
|
+
type CollectionPersistentStorageConfig<ItemState extends ValidStoreState, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends CollectionOfflineOperationsConfig<ItemState, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & CollectionPersistentStorageFields<ItemPayload>;
|
|
1438
|
+
type InternalListQueryOfflineOperations<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = Record<string, AnyOfflineOperationDefinition<__LEGIT_ANY__> & {
|
|
1439
|
+
getEntityRefs: (ctx: {
|
|
1440
|
+
input: __LEGIT_ANY__;
|
|
1441
|
+
}) => ListQueryOfflineEntityRef<ItemPayload>[];
|
|
1442
|
+
dependsOn?: (ctx: {
|
|
1443
|
+
input: __LEGIT_ANY__;
|
|
1444
|
+
}) => ListQueryOfflineEntityRef<ItemPayload>[];
|
|
1445
|
+
}> & ([ItemState | QueryPayload | ItemPayload] extends [never] ? never : unknown);
|
|
1446
|
+
type ListQueryOfflineOperationsConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = InternalListQueryOfflineOperations<ItemState, QueryPayload, ItemPayload> | null;
|
|
1447
|
+
type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
|
|
1448
|
+
/** Schema used to validate cached item payloads on load. */itemPayloadSchema: PersistentStorageSchema<ItemPayload>; /** Schema used to validate cached query payloads on load. */
|
|
1449
|
+
queryPayloadSchema: PersistentStorageSchema<QueryPayload>;
|
|
1450
|
+
/**
|
|
1451
|
+
* Maximum serialized JSON size to persist for list items. Budgeting uses the
|
|
1452
|
+
* serialized string length, not browser quota bytes. Defaults to 64 KB in
|
|
1453
|
+
* `local-sync` and 128 KB in async adapters.
|
|
1454
|
+
*/
|
|
1455
|
+
maxItemBytes?: number;
|
|
1456
|
+
/**
|
|
1457
|
+
* Maximum serialized JSON size to persist for list queries. Budgeting uses
|
|
1458
|
+
* the serialized string length, not browser quota bytes. Defaults to 32 KB
|
|
1459
|
+
* in `local-sync` and 64 KB in async adapters.
|
|
1460
|
+
*/
|
|
1461
|
+
maxQueryBytes?: number; /** Maximum number of items per query to persist. Defaults to 100. */
|
|
1462
|
+
maxQuerySize?: number; /** Item payloads that should never be evicted from storage. */
|
|
1463
|
+
pinnedItems?: ItemPayload[]; /** Query payloads that should never be evicted from storage. */
|
|
1464
|
+
pinnedQueries?: QueryPayload[];
|
|
1465
|
+
/**
|
|
1466
|
+
* Item payloads that should never be persisted or restored.
|
|
1467
|
+
* Accepts either an explicit payload list or a predicate function.
|
|
1468
|
+
* Takes precedence over `pinnedItems`.
|
|
1469
|
+
*/
|
|
1470
|
+
ignoreItems?: ItemPayload[] | ((payload: ItemPayload) => boolean);
|
|
1471
|
+
};
|
|
1472
|
+
/** Persistent storage config for ListQueryStore. */
|
|
1473
|
+
type ListQueryPersistentStorageConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload = ValidPayload, ItemPayload extends ValidPayload = ValidPayload, StorageState = unknown, TOfflineOperations extends ListQueryOfflineOperationsConfig<ItemState, QueryPayload, ItemPayload> = null> = StorePersistentStorageBaseConfig<ItemState, StorageState> & PublicStoreOfflineConfigField<TOfflineOperations> & ListQueryPersistentStorageFields<QueryPayload, ItemPayload>;
|
|
1474
|
+
//#endregion
|
|
1475
|
+
export { OfflineResolutionRecord as $, DefineListQueryOfflineOperations as A, PayloadDebounce as At, OfflineEntityMutationKind as B, mutationSkipped as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, TSDFStatus as Ft, OfflineMutationQueueingPolicy as G, ScheduleFetchResults as Gt, OfflineMutationInput as H, RequestSchedulerEventData as Ht, ListQueryOfflineOperationDefinition as I, UnwrapTSDFResult as It, OfflineReplayRetryConfig as J, TSDFDebugLogLevel as Jt, OfflineOperationKind as K, TSDFDebugLogArea as Kt, OfflineAccumulationConfig as L, ValidPayload as Lt, DocumentOfflineOperationDefinition as M, StoreFetchError as Mt, GlobalOfflineEntity as N, StoreMutationError as Nt, DefineCollectionOfflineOperations as O, MaybeTSDFResult as Ot, GlobalOfflineStatus as P, StoreMutationErrorOptions as Pt, OfflineResolutionConflictParseErrorCode as Q, OfflineAccumulationMergeContext as R, ValidStoreState as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, RequestSchedulerEvents as Ut, OfflineMutationDescriptor as V, FetchType as Vt, OfflineMutationQueueingConfig as W, ScheduleFetchOptions as Wt, OfflineResolutionActionForOperation as X, TSDFDebugOptions as Xt, OfflineResolutionAction as Y, TSDFDebugLogger as Yt, OfflineResolutionConflictParseError as Z, ListQueryOfflineOperationsConfig as _, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, OfflineTempEntityConfig as dt, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, StoreError as jt, DefineDocumentOfflineOperations as k, MutationSkipped as kt, AsyncStorageNamespaceGetResult as l, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, OperationResult as mt, AsyncStorageDiscoveredScope as n, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, OperationConflict as pt, OfflineQueueEntry as q, TSDFDebugLogEntry as qt, AsyncStorageDriver as r, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, fetchTypePriority as zt };
|