tsdf 17.0.0-alpha.9 → 17.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-CBnUebnf.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-Ci0JcCo5.js";
2
2
  export { opfsPersistentStorage };
@@ -1,2 +1,2 @@
1
- import { t as opfsPersistentStorage } from "./opfsPersistentStorage-BO_uDxe4.js";
1
+ import { t as opfsPersistentStorage } from "./opfsPersistentStorage-DqJXzF7M.js";
2
2
  export { opfsPersistentStorage };
@@ -1,4 +1,4 @@
1
- import { t as AsyncStorageAdapter } from "./types-2zQlbxtw.js";
1
+ import { t as AsyncStorageAdapter } from "./types-D0ttVGmj.js";
2
2
 
3
3
  //#region src/persistentStorage/opfsPersistentStorage.d.ts
4
4
  declare const opfsPersistentStorage: AsyncStorageAdapter;
@@ -1,4 +1,4 @@
1
- import { B as parseAsyncStorageRecordKey, F as encodePersistedAsyncNamespaceKind, I as getNamespaceId, L as getPayloadRecordKey, V as parsePersistedAsyncNamespaceKind, i as createAsyncStorageAdapter } from "./asyncStorageAdapter-BZSj1ZO5.js";
1
+ import { B as getNamespaceId, G as parsePersistedAsyncNamespaceKind, V as getPayloadRecordKey, W as parseAsyncStorageRecordKey, h as getTSDFDebugTimingMs, i as createAsyncStorageAdapter, m as emitTSDFDebugLog, z as encodePersistedAsyncNamespaceKind } from "./asyncStorageAdapter-CGfnsd9m.js";
2
2
  import { getCompositeKey } from "@ls-stack/utils/getCompositeKey";
3
3
  import { __LEGIT_CAST__ } from "@ls-stack/utils/saferTyping";
4
4
  import { isObject } from "@ls-stack/utils/typeGuards";
@@ -134,6 +134,7 @@ async function getFileHandleIfExists(parent, name) {
134
134
  const OPFS_DIR_HANDLE_CACHE_MAX_SIZE = 500;
135
135
  const OPFS_FILE_HANDLE_CACHE_MAX_SIZE = 1e4;
136
136
  var OpfsAsyncStorageDriver = class {
137
+ debugLogger;
137
138
  #rootDirPromise = null;
138
139
  #mainCacheContext = {
139
140
  cleanupKnowledge: null,
@@ -247,7 +248,15 @@ var OpfsAsyncStorageDriver = class {
247
248
  storeDir
248
249
  });
249
250
  if (fileHandle === null) return null;
250
- return this.#readJsonFile(this.#getFilePath(scope, key), fileHandle, cacheContext);
251
+ const filePath = this.#getFilePath(scope, key);
252
+ if (!import.meta.env.DEV || !this.debugLogger) return this.#readJsonFile(filePath, fileHandle, cacheContext);
253
+ const startTime = getTSDFDebugTimingMs();
254
+ return this.#readJsonFile(filePath, fileHandle, cacheContext).finally(() => {
255
+ this.#logAdapterOperation(scope, "read-file", startTime, {
256
+ filePath,
257
+ key
258
+ });
259
+ });
251
260
  }));
252
261
  }
253
262
  async #setManyWithContext(scope, entries, cacheContext) {
@@ -265,10 +274,20 @@ var OpfsAsyncStorageDriver = class {
265
274
  if (await this.#removeWholeStoreDirIfAllKnownEntriesAreBeingRemoved(scope, uniqueKeys, cacheContext)) return;
266
275
  const removeResults = await Promise.all(uniqueKeys.map(async (key) => {
267
276
  const fileName = buildFileName(scope, key);
277
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
268
278
  try {
269
279
  await storeDir.removeEntry(fileName);
280
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
281
+ fileName,
282
+ key
283
+ });
270
284
  return true;
271
285
  } catch {
286
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "delete-file", startTime, {
287
+ fileName,
288
+ key,
289
+ status: "miss"
290
+ });
272
291
  return false;
273
292
  } finally {
274
293
  this.#invalidateFileHandle(scope, key, cacheContext);
@@ -279,8 +298,14 @@ var OpfsAsyncStorageDriver = class {
279
298
  await this.#pruneEmptyDirectories(scope, cacheContext);
280
299
  }
281
300
  async #listKeysWithContext(scope, cacheContext) {
301
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
282
302
  const { resolvedEntries } = await this.#listScopedFiles(scope, cacheContext);
283
- return resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
303
+ const keys = resolvedEntries.map((entry) => entry.key).sort((left, right) => left.localeCompare(right));
304
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "list-directory", startTime, {
305
+ count: keys.length,
306
+ storeDirPath: this.#getStoreDirPath(scope)
307
+ });
308
+ return keys;
284
309
  }
285
310
  async #clearWithContext(scope, cacheContext) {
286
311
  const storeDir = await this.#getStoreDir(scope, {
@@ -633,11 +658,17 @@ var OpfsAsyncStorageDriver = class {
633
658
  if (fileHandle === null) throw new Error("[TSDF] Failed to open OPFS file handle.");
634
659
  const writable = await fileHandle.createWritable();
635
660
  const rawValue = entry.serializedValue ?? JSON.stringify(entry.value);
661
+ const startTime = import.meta.env.DEV && this.debugLogger ? getTSDFDebugTimingMs() : null;
636
662
  try {
637
663
  await writable.write(rawValue);
638
664
  } finally {
639
665
  await writable.close();
640
666
  }
667
+ if (import.meta.env.DEV && this.debugLogger) this.#logAdapterOperation(scope, "write-file", startTime, {
668
+ filePath: this.#getFilePath(scope, entry.key),
669
+ key: entry.key,
670
+ sizeBytes: rawValue.length
671
+ });
641
672
  cacheContext.readValueCache?.set(this.#getFilePath(scope, entry.key), entry.value);
642
673
  return;
643
674
  } catch (error) {
@@ -648,6 +679,29 @@ var OpfsAsyncStorageDriver = class {
648
679
  this.#invalidateDirectory(this.#getSessionDirPath(scope.sessionKey), cacheContext);
649
680
  }
650
681
  }
682
+ #logAdapterOperation(scope, adapterOperation, startTime, details = {}) {
683
+ if (!import.meta.env.DEV) return;
684
+ if (startTime === null) return;
685
+ if (!this.debugLogger) return;
686
+ const status = typeof details.status === "string" ? details.status : "success";
687
+ emitTSDFDebugLog(this.debugLogger, {
688
+ area: "persistent-storage",
689
+ level: "log",
690
+ message: `persistent storage adapter ${adapterOperation} ${status}`,
691
+ operation: "adapter-operation",
692
+ details: {
693
+ adapter: "async",
694
+ adapterName: "opfs",
695
+ adapterOperation,
696
+ durationMs: getTSDFDebugTimingMs() - startTime,
697
+ namespaceKind: scope.kind,
698
+ sessionKey: scope.sessionKey,
699
+ status,
700
+ storeName: scope.storeName,
701
+ ...details
702
+ }
703
+ });
704
+ }
651
705
  async #cleanupRemoveKnownRecordsWithContext(scope, keys, cacheContext) {
652
706
  if (keys.length === 0) return [];
653
707
  const storeDir = await this.#getStoreDir(scope, {
@@ -7,9 +7,11 @@ import { StandardSchemaV1 } from "@standard-schema/spec";
7
7
  /** Debug log severity used to choose the default console method. */
8
8
  type TSDFDebugLogLevel = 'log' | 'warn' | 'error';
9
9
  /** Internal subsystem that emitted a debug log entry. */
10
- type TSDFDebugLogArea = 'browser-tabs' | 'persistent-storage';
10
+ type TSDFDebugLogArea = 'browser-tabs' | 'focus' | 'persistent-storage';
11
+ /** Operations emitted by focus lifecycle handling. */
12
+ type TSDFFocusDebugOperation = 'window-focus-revalidate';
11
13
  /** 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';
14
+ type TSDFPersistentStorageDebugOperation = 'clear' | 'commit' | 'list-keys' | 'list-metadata' | 'list-metadata-by-filter' | 'load' | 'load-many' | 'adapter-operation' | 'quota-cleanup' | 'read-entry' | 'read-protected-keys' | 'remove' | 'save' | 'schedule-save' | 'sync-load' | 'sync-protected-keys' | 'write';
13
15
  /** Operations emitted by the browser-tab sync subsystem. */
14
16
  type TSDFBrowserTabsDebugOperation = 'leader-change' | 'publish' | 'publish-skipped' | 'receive' | 'receive-skipped' | 'session-change' | 'transport-close' | 'transport-open' | 'transport-unavailable';
15
17
  /** Structured debug log entry emitted by TSDF internals. */
@@ -17,13 +19,13 @@ type TSDFDebugLogEntry = {
17
19
  /** Subsystem that emitted the entry. */area: TSDFDebugLogArea; /** Severity of the entry. */
18
20
  level: TSDFDebugLogLevel; /** Human-readable summary of the operation. */
19
21
  message: string; /** Stable operation id, such as `publish`, `load`, or `write`. */
20
- operation: TSDFPersistentStorageDebugOperation | TSDFBrowserTabsDebugOperation; /** Structured operation metadata for filtering and diagnostics. */
22
+ operation: TSDFFocusDebugOperation | TSDFPersistentStorageDebugOperation | TSDFBrowserTabsDebugOperation; /** Structured operation metadata for filtering and diagnostics. */
21
23
  details?: Readonly<Record<string, unknown>>;
22
24
  };
23
25
  /** Custom debug logger invoked for each emitted TSDF debug entry. */
24
26
  type TSDFDebugLogger = (entry: TSDFDebugLogEntry) => void;
25
- /** Enables manager-wide debug logging for browser-tab sync and persistence. */
26
- type TSDFDebugOptions = boolean | TSDFDebugLogger;
27
+ /** Logger option used by manager-wide debug and production-signal logging. */
28
+ type TSDFLoggerOptions = boolean | TSDFDebugLogger;
27
29
  //#endregion
28
30
  //#region src/requestScheduler.d.ts
29
31
  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';
@@ -125,6 +127,261 @@ declare class StoreFetchError extends Error {
125
127
  constructor(error: StoreError, type: 'fetch' | 'aborted' | 'timeout');
126
128
  }
127
129
  //#endregion
130
+ //#region src/listQueryStore/types.d.ts
131
+ /** Lifecycle status for a list query or list item query. */
132
+ type QueryStatus = TSDFStatus | 'loadingMore';
133
+ /** Raw cached state for one list query. */
134
+ type TSFDListQuery<QueryPayload extends ValidPayload> = {
135
+ /** Last fetch error for this query, when the latest fetch failed. */error: StoreError | null; /** Current fetch lifecycle status for this query. */
136
+ status: QueryStatus; /** Payload used to identify and fetch this query. */
137
+ payload: QueryPayload; /** Whether another page is available. */
138
+ hasMore: boolean; /** Whether this query has ever loaded successfully. */
139
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
140
+ refetchOnMount: false | FetchType; /** Ordered item keys included in the cached query page. */
141
+ items: string[];
142
+ };
143
+ /** Raw cached state for one item query in a list-query store. */
144
+ type TSDFItemQuery<ItemPayload extends ValidPayload> = {
145
+ /** Last item fetch error, if any. */error: StoreError | null; /** Current fetch lifecycle status for this item. */
146
+ status: Exclude<QueryStatus, 'loadingMore'>; /** Whether this item has ever loaded successfully. */
147
+ wasLoaded: boolean; /** Pending automatic refetch priority for stale data mounted by hooks. */
148
+ refetchOnMount: false | FetchType; /** Payload used to identify and fetch this item. */
149
+ payload: ItemPayload;
150
+ };
151
+ /** Loaded partial-resource fields for one item, or `'*'` when fully loaded. */
152
+ type ItemLoadedFields = string[] | '*';
153
+ /** Raw t-state shape used by a list-query store. */
154
+ type TSFDListQueryState<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
155
+ /** Item data records keyed by item store key. */items: Record<string, ItemState | null>; /** List query records keyed by query store key. */
156
+ queries: Record<string, TSFDListQuery<QueryPayload>>; /** Item query records keyed by item store key. */
157
+ itemQueries: Record<string, TSDFItemQuery<ItemPayload> | null>; /** Loaded partial-resource fields for each item key. */
158
+ itemLoadedFields: Record<string, ItemLoadedFields>; /** Pending field invalidations for each item key. */
159
+ itemFieldInvalidationFields: Record<string, string[]>;
160
+ };
161
+ /**
162
+ * Partial-resource fields to request.
163
+ *
164
+ * Pass a field-name array to load only those fields, or `'*'` to load the
165
+ * complete item.
166
+ */
167
+ type FieldsInput = string[] | '*';
168
+ /** Value returned by `ListQueryStore.useListQuery(...)` and `useMultipleListQueries(...)`. */
169
+ type TSFDUseListQueryReturn<Selected, QueryPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined, HasPartialResources extends boolean = false> = {
170
+ /** Selected items included in the current query result. */items: Selected[]; /** Hook-visible query status, including `idle` before a query runs. */
171
+ status: QueryStatus | 'idle'; /** Query payload for this result, unless omitted or unavailable. */
172
+ payload: QueryPayload | undefined; /** Requested partial-resource fields for this query result. */
173
+ fields: HasPartialResources extends true ? FieldsInput : FieldsInput | undefined; /** Requested partial-resource fields that are still pending. */
174
+ loadingFields?: string[]; /** Last query fetch error, if any. */
175
+ error: StoreError | null; /** Stable store key for the current query payload. */
176
+ queryKey: string; /** Whether another page is available. */
177
+ hasMore: boolean; /** Whether this result was derived from local items instead of fetched directly. */
178
+ isDerived: boolean; /** Convenience flag for `loading` or `refetching` states. */
179
+ isLoading: boolean; /** Whether a `loadMore(...)` request is currently active. */
180
+ isLoadingMore: boolean; /** Whether this result has local offline changes that still need to sync to the server. */
181
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
182
+ queryMetadata: QueryMetadata;
183
+ };
184
+ /** Value returned by `ListQueryStore.useItem(...)` and `useMultipleItems(...)`. */
185
+ type TSFDUseListItemReturn<Selected, ItemPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
186
+ /** Selected item data. Defaults to the full item or `null`. */data: Selected; /** Hook-visible item status, including idle/deleted states for hook ergonomics. */
187
+ status: QueryStatus | 'idle' | 'deleted'; /** Item payload for this result, or `null` when unavailable. */
188
+ payload: ItemPayload | null; /** Requested partial-resource fields that are still pending. */
189
+ loadingFields?: string[]; /** Last item fetch error, if any. */
190
+ error: StoreError | null; /** Convenience flag for `loading` or `refetching` states. */
191
+ isLoading: boolean; /** Stable store key for the current item payload. */
192
+ itemStateKey: string; /** Whether this result has local offline changes that still need to sync to the server. */
193
+ pendingSync: boolean; /** Caller-provided metadata copied from the query descriptor. */
194
+ queryMetadata: QueryMetadata;
195
+ };
196
+ /** Value returned by `ListQueryStore.usePendingOfflineItems(...)`. */
197
+ type TSFDUsePendingOfflineItemsReturn<Selected, ItemPayload extends ValidPayload> = {
198
+ /** Locally created or updated offline items selected by the hook. */items: Selected[]; /** Payloads for locally deleted offline items. */
199
+ deletedItems: ItemPayload[];
200
+ };
201
+ /** One item returned from a list query fetch function. */
202
+ type FetchListFnReturnItem<ItemPayload extends ValidPayload, ItemState extends ValidStoreState> = {
203
+ /** Item payload used to key and refetch the returned item. */itemPayload: ItemPayload; /** Item data returned by the server. */
204
+ data: ItemState;
205
+ };
206
+ /** Return shape for list query fetch functions. */
207
+ type FetchListFnReturn<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = {
208
+ /** Items included in the fetched page. */items: FetchListFnReturnItem<ItemPayload, ItemState>[]; /** Whether the query has another page available. */
209
+ hasMore: boolean;
210
+ };
211
+ /** Item descriptor accepted by `ListQueryStore.useMultipleItems(...)`. */
212
+ type ListQueryUseMultipleItemsQuery<ItemPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
213
+ /** Item payload to subscribe to and fetch when needed. */payload: ItemPayload;
214
+ /**
215
+ * Partial-resource fields to request for this item.
216
+ *
217
+ * Pass `'*'` to fetch the complete item. This option is required when
218
+ * `partialResources` is enabled and optional otherwise.
219
+ */
220
+ fields?: FieldsInput; /** Metadata returned with this item result for caller-side bookkeeping. */
221
+ queryMetadata?: QueryMetadata;
222
+ /**
223
+ * Only fetches when the item is missing from state, skipping stale-state and
224
+ * invalidation refetches.
225
+ */
226
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
227
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the item has not been fetched. */
228
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
229
+ returnRefetchingStatus?: boolean;
230
+ /**
231
+ * When requested fields are missing but cached partial data exists, return
232
+ * `refetching` instead of `loading`.
233
+ */
234
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
235
+ isOffScreen?: boolean;
236
+ };
237
+ /** Query descriptor accepted by `ListQueryStore.useMultipleListQueries(...)`. */
238
+ type ListQueryUseMultipleListQueriesQuery<QueryPayload extends ValidPayload, QueryMetadata extends undefined | Record<string, unknown> = undefined> = {
239
+ /** Query payload to subscribe to and fetch when needed. */payload: QueryPayload;
240
+ /**
241
+ * Partial-resource fields to request for each item in this query.
242
+ *
243
+ * Pass `'*'` to fetch complete items. This option is required when
244
+ * `partialResources` is enabled and optional otherwise.
245
+ */
246
+ fields?: FieldsInput; /** Metadata returned with this query result for caller-side bookkeeping. */
247
+ queryMetadata?: QueryMetadata; /** Omits `payload` from this query result. */
248
+ omitPayload?: boolean;
249
+ /**
250
+ * Only fetches when the query is missing from state, skipping stale-state and
251
+ * invalidation refetches.
252
+ */
253
+ disableRefetches?: boolean; /** Prevents the automatic mount refetch for stale loaded data. */
254
+ disableRefetchOnMount?: boolean; /** Returns `idle` instead of `loading` while the query has not been fetched. */
255
+ returnIdleStatus?: boolean; /** Returns `refetching` instead of keeping `loaded` status during refetches. */
256
+ returnRefetchingStatus?: boolean;
257
+ /**
258
+ * When requested fields are missing but cached partial data exists, return
259
+ * `refetching` instead of `loading`.
260
+ */
261
+ showPartialAsRefetching?: boolean; /** Marks this subscription as off-screen, lowering automatic fetch priority. */
262
+ isOffScreen?: boolean; /** Number of items to request when fetching this query page. */
263
+ loadSize?: number;
264
+ };
265
+ /** Callback invoked when an already-loaded list query is invalidated. */
266
+ type OnListQueryInvalidate<QueryPayload extends ValidPayload> = (query: QueryPayload, priority: FetchType) => void;
267
+ /** Callback invoked when an already-loaded list-query item is invalidated. */
268
+ type OnListQueryItemInvalidate<ItemState extends ValidStoreState, ItemPayload extends ValidPayload> = (props: {
269
+ /** Current cached item state at invalidation time. */itemState: ItemState; /** Payload of the invalidated item. */
270
+ payload: ItemPayload; /** Fetch priority requested for the invalidation. */
271
+ priority: FetchType;
272
+ }) => void;
273
+ /** Rule for keeping cached list query membership in sync after item updates. */
274
+ type OptimisticListUpdate<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
275
+ /** Query payloads, or a predicate over query payloads, affected by this rule. */queries: QueryPayload | ((query: QueryPayload) => boolean) | QueryPayload[]; /** Restricts this rule to items that should belong in the affected query set. */
276
+ filterItem?: (item: ItemState) => boolean | null; /** Where newly matching items should be inserted in affected query pages. */
277
+ appendNewTo?: 'start' | 'end';
278
+ /**
279
+ * Schedules a background refetch of queries this rule mutated. Leave off
280
+ * unless the optimistic update can't represent the final server state —
281
+ * e.g. server-assigned sort fields (`updatedAt`, computed scores), server-
282
+ * only membership data (permissions), or cursor pagination shifts.
283
+ */
284
+ invalidateQueries?: boolean; /** Sort order to maintain inside affected query pages. */
285
+ sort?: {
286
+ /** Selects sortable values from an item. */sortBy: (item: ItemState, itemPayload: ItemPayload) => string | number | (string | number)[]; /** Sort direction for each `sortBy` value. */
287
+ order?: 'asc' | 'desc' | ('asc' | 'desc')[];
288
+ };
289
+ };
290
+ /** Payload passed to list fetch functions. */
291
+ type QueryFetchPayload<QueryPayload extends ValidPayload> = {
292
+ /** Whether this request loads the first page or a later page. */type: 'load' | 'loadMore'; /** Query payload being fetched. */
293
+ payload: QueryPayload; /** Offset used for offset-paginated fetches. */
294
+ offset: number; /** Maximum number of items requested. */
295
+ limit: number; /** Partial-resource fields requested for each item in the fetched query. */
296
+ fields?: string[];
297
+ };
298
+ /** Options for offset-based list pagination. */
299
+ type OffsetPaginationConfig = {
300
+ /** Largest item count requested when refetching invalidated offset queries. */maxInvalidationLimit: number; /** Max parallel chunk requests during chunked invalidation (default: 3) */
301
+ maxParallel?: number;
302
+ };
303
+ /** Partial-resource helpers used to merge and select field subsets. */
304
+ type PartialResourcesConfig<ItemState extends ValidStoreState> = {
305
+ /** Merges a partial fetch result into an existing item snapshot. */mergeItems: (prev: ItemState | undefined, fetched: ItemState) => ItemState; /** Returns an item containing only the requested fields. */
306
+ selectFields: (fields: string[], item: ItemState) => ItemState;
307
+ /**
308
+ * Reports which logical fields are genuinely present in an item snapshot,
309
+ * or `'*'` when the snapshot is complete.
310
+ *
311
+ * It is the only availability signal for snapshots without loaded-field
312
+ * metadata (manually inserted items, persisted fallback snapshots, offline
313
+ * optimistic rows), but it is also consulted for metadata-tracked items:
314
+ * metadata only records what fetches delivered, so `inferFields` can vouch
315
+ * for fields present beyond the tracked list (e.g. written by a mutation)
316
+ * and avoid refetching data that is already there.
317
+ *
318
+ * Because it can vouch for any snapshot, it must only report fields whose
319
+ * data is genuinely usable — never return `'*'` unconditionally unless
320
+ * every snapshot the store can hold is complete. Staleness is handled by
321
+ * TSDF: fields awaiting an invalidation refetch are excluded before
322
+ * `inferFields` is consulted.
323
+ */
324
+ inferFields: (item: ItemState) => ItemLoadedFields;
325
+ };
326
+ type DerivedQuerySummary<QueryPayload extends ValidPayload> = {
327
+ payload: QueryPayload;
328
+ hasMore: boolean;
329
+ itemCount: number;
330
+ };
331
+ type DerivedQueryItem<ItemState extends ValidStoreState> = {
332
+ key: string;
333
+ data: ItemState;
334
+ };
335
+ /** Why a derived query is currently being resolved. */
336
+ type DerivedQuerySource = 'online' | 'offline' | 'sticky-offline';
337
+ /** Runtime context passed to `derivedQueries.deriveQuery(...)`. */
338
+ type DerivedQueryContext = {
339
+ /** The requested hook fields for this query, when partial resources are enabled. */fields: FieldsInput | undefined; /** Whether the store is currently in offline mode. */
340
+ isOfflineMode: boolean;
341
+ /**
342
+ * What caused derivation to run.
343
+ * `sticky-offline` means a query that was derived offline is still sticking
344
+ * to the local derived view after reconnect, until explicit invalidation.
345
+ */
346
+ deriveSource: DerivedQuerySource;
347
+ };
348
+ /** Configuration for deriving query membership from locally materialized items. */
349
+ type DerivedQueriesConfig<ItemState extends ValidStoreState, QueryPayload extends ValidPayload, ItemPayload extends ValidPayload> = {
350
+ /** Extracts the domain/group key for a query payload. */getQueryGroup: (queryPayload: QueryPayload) => string; /** Extracts the domain/group key for a materialized item. */
351
+ getItemGroup: (item: ItemState, itemPayload: ItemPayload) => string;
352
+ /**
353
+ * Returns whether the local data for the query group is complete enough to
354
+ * derive from while online.
355
+ */
356
+ isComplete: (queryPayload: QueryPayload, context: {
357
+ queries: DerivedQuerySummary<QueryPayload>[];
358
+ }) => boolean;
359
+ /**
360
+ * Computes a derived ordered list of item keys for a query, or `false` to
361
+ * fall back to the regular fetch/cache path. `context.fields` lets the
362
+ * callback decide whether partial-resource queries should still derive.
363
+ */
364
+ deriveQuery: (queryPayload: QueryPayload, items: DerivedQueryItem<ItemState>[], context: DerivedQueryContext) => string[] | false;
365
+ };
366
+ /** Field option shape used by APIs that are conditional on `partialResources`. */
367
+ type FieldsOption<HasPartialResources extends boolean> = HasPartialResources extends true ? {
368
+ /**
369
+ * Partial-resource fields to request.
370
+ *
371
+ * Pass `'*'` to fetch complete items. This option is required when
372
+ * `partialResources` is enabled.
373
+ */
374
+ fields: FieldsInput;
375
+ } : {
376
+ /**
377
+ * Partial-resource fields to request.
378
+ *
379
+ * Pass `'*'` to fetch complete items. This option is optional when
380
+ * `partialResources` is not enabled.
381
+ */
382
+ fields?: FieldsInput;
383
+ };
384
+ //#endregion
128
385
  //#region src/persistentStorage/offlineUploadTypes.d.ts
129
386
  /** Lifecycle state for a session-scoped offline upload. */
130
387
  type OfflineUploadState = 'pending' | 'uploading' | 'uploaded' | 'failed';
@@ -1312,7 +1569,9 @@ type AsyncStorageDiscoveredScope = {
1312
1569
  };
1313
1570
  /** Low-level async backend contract implemented by custom storage drivers. */
1314
1571
  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. */
1572
+ /** Mutable debug logger used by concrete adapters to emit operation timings. */debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1573
+ logger?: TSDFDebugLogger; /** Read a single raw record from a logical namespace. */
1574
+ get(scope: AsyncStorageNamespaceScope, key: string): Promise<unknown>; /** Write a single raw record to a logical namespace. */
1316
1575
  set(scope: AsyncStorageNamespaceScope, key: string, value: unknown): Promise<void>; /** Remove a single raw record from a logical namespace. */
1317
1576
  remove(scope: AsyncStorageNamespaceScope, key: string): Promise<void>; /** List raw record keys within a logical namespace. */
1318
1577
  listKeys(scope: AsyncStorageNamespaceScope): Promise<string[]>; /** Remove every record from a logical namespace. */
@@ -1343,7 +1602,9 @@ type AsyncStorageNamespaceHandle<TValue, TCustomMetadata extends Record<string,
1343
1602
  };
1344
1603
  /** Managed async adapter consumed by TSDF persistence internals. */
1345
1604
  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. */
1605
+ /** Adapter mode marker used by persistence internals to pick async behavior. */kind: 'async'; /** Mutable debug logger used by concrete adapters to emit operation timings. */
1606
+ debugLogger?: TSDFDebugLogger; /** Mutable logger used for low-volume production signals. */
1607
+ logger?: TSDFDebugLogger; /** Open a logical namespace with managed batching and touch guarantees. */
1347
1608
  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
1609
  readProtectedStorageKeys(sessionKey: string): Promise<Set<string>>; /** Eagerly sync offline protection changes into persisted metadata for already-cached entries. */
1349
1610
  syncSessionProtectedKeys(sessionKey: string, protectedKeys: Iterable<string>, previousProtectedKeys?: Iterable<string>): Promise<void>; /** Remove all namespaces for a session key. */
@@ -1472,4 +1733,4 @@ type ListQueryPersistentStorageFields<QueryPayload extends ValidPayload, ItemPay
1472
1733
  /** Persistent storage config for ListQueryStore. */
1473
1734
  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
1735
  //#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 };
1736
+ export { OfflineResolutionRecord as $, StoreError as $t, DefineListQueryOfflineOperations as A, DerivedQuerySource as At, OfflineEntityMutationKind as B, OptimisticListUpdate as Bt, PersistentStorageSchema as C, OfflineUploadAdapter as Ct, CollectionOfflineOperationDefinition as D, OfflineUploadTransportContext as Dt, CollectionOfflineEntityRef as E, OfflineUploadState as Et, ListQueryOfflineEntityRef as F, ListQueryUseMultipleItemsQuery as Ft, OfflineMutationQueueingPolicy as G, TSFDListQuery as Gt, OfflineMutationInput as H, QueryFetchPayload as Ht, ListQueryOfflineOperationDefinition as I, ListQueryUseMultipleListQueriesQuery as It, OfflineReplayRetryConfig as J, TSFDUseListQueryReturn as Jt, OfflineOperationKind as K, TSFDListQueryState as Kt, OfflineAccumulationConfig as L, OffsetPaginationConfig as Lt, DocumentOfflineOperationDefinition as M, FetchListFnReturnItem as Mt, GlobalOfflineEntity as N, FieldsInput as Nt, DefineCollectionOfflineOperations as O, DerivedQueriesConfig as Ot, GlobalOfflineStatus as P, FieldsOption as Pt, OfflineResolutionConflictParseErrorCode as Q, PayloadDebounce as Qt, OfflineAccumulationMergeContext as R, OnListQueryInvalidate as Rt, PersistentStoragePreloadResult as S, OfflineUpload as St, AnyOfflineOperationDefinition as T, OfflineUploadSource as Tt, OfflineMutationQueueingCause as U, QueryStatus as Ut, OfflineMutationDescriptor as V, PartialResourcesConfig as Vt, OfflineMutationQueueingConfig as W, TSDFItemQuery as Wt, OfflineResolutionActionForOperation as X, MaybeTSDFResult as Xt, OfflineResolutionAction as Y, TSFDUsePendingOfflineItemsReturn as Yt, OfflineResolutionConflictParseError as Z, MutationSkipped as Zt, ListQueryOfflineOperationsConfig as _, TSDFDebugLogger as _n, defaultOfflineRuntimeConfig as _t, AsyncStorageMetadataOrder as a, ValidPayload as an, OfflineSession as at, PersistentStorageDataSchema as b, OfflineSessionUploadsConfig as bt, AsyncStorageNamespaceCommitUpsert as c, mutationSkipped as cn, OfflineSyncState as ct, AsyncStorageNamespaceKind as d, RequestSchedulerEvents as dn, OfflineTempEntityConfig as dt, StoreFetchError as en, OfflineResolutionRecordForOperation as et, AsyncStorageNamespaceScope as f, ScheduleFetchOptions as fn, OfflineTempEntityPendingEntry as ft, DocumentPersistentStorageConfig as g, TSDFDebugLogLevel as gn, ParsedOfflineResolutionConflictResultForStore as gt, ConvertedPersistentStorageDataSchema as h, TSDFDebugLogEntry as hn, ParsedOfflineResolutionConflictResultForOperation as ht, AsyncStorageDriverSetEntry as i, UnwrapTSDFResult as in, OfflineRuntimeConfigUpdate as it, DefineOfflineOperation as j, FetchListFnReturn as jt, DefineDocumentOfflineOperations as k, DerivedQueryContext as kt, AsyncStorageNamespaceGetResult as l, FetchType as ln, OfflineTempEntitiesConfig as lt, CollectionPersistentStorageConfig as m, TSDFDebugLogArea as mn, OperationResult as mt, AsyncStorageDiscoveredScope as n, StoreMutationErrorOptions as nn, OfflineRetryExhaustedResolutionAction as nt, AsyncStorageNamespaceCommitArgs as o, ValidStoreState as on, OfflineSessionConfig as ot, AsyncStorageReadOptions as p, ScheduleFetchResults as pn, OperationConflict as pt, OfflineQueueEntry as q, TSFDUseListItemReturn as qt, AsyncStorageDriver as r, TSDFStatus as rn, OfflineRuntimeConfig as rt, AsyncStorageNamespaceCommitTouch as s, fetchTypePriority as sn, OfflineSupersedeConfig as st, AsyncStorageAdapter as t, StoreMutationError as tn, OfflineResolutionRecordForStore as tt, AsyncStorageNamespaceHandle as u, RequestSchedulerEventData as un, OfflineTempEntitiesReconciliation as ut, ListQueryPersistentStorageConfig as v, TSDFFocusDebugOperation as vn, OfflineMutationUploadsInput as vt, StorageAdapter as w, OfflineUploadProgress as wt, PersistentStorageErrorHandler as x, OfflineStoredUploadRecord as xt, PersistentStorageBaseConfig as y, TSDFLoggerOptions as yn, OfflineOperationUploadsContext as yt, OfflineConflictResolutionAction as z, OnListQueryItemInvalidate as zt };
package/docs/README.md CHANGED
@@ -50,8 +50,8 @@ const storeManager = createStoreManager({
50
50
  id: 'fetch-error',
51
51
  message: err.message,
52
52
  }),
53
- lowPriorityThrottleMs: 5,
54
- baseCoalescingWindowMs: 10,
53
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
54
+ baseCoalescingWindowMs: 16,
55
55
  blockWindowClose: null,
56
56
  revalidateOnWindowFocus: true,
57
57
  onMutationError: (error) => {
@@ -22,9 +22,9 @@ Tabs use a versioned message model so later snapshots do not overwrite fresher r
22
22
 
23
23
  ## Behavior details
24
24
 
25
- - Tab status messages include focus and heartbeat data.
25
+ - Tab status messages include focus and presence timestamp data.
26
26
  - Focused tabs keep the base `baseCoalescingWindowMs`.
27
- - Background tabs are ranked and may receive an extended coalescing window (`base` + rank \* `1000ms`), which helps avoid duplicate background refetch work.
27
+ - Background tabs are ranked and may receive an extended coalescing window (`base` + `backgroundCoalescingDelayMs` + background rank \* `1000ms`), which helps avoid duplicate background refetch work. The first background tab uses rank `0`, so the default first background window is `base + 3000ms`.
28
28
  - `fetch-start` messages let sibling tabs drop duplicate scheduled work when another tab is already fetching the same request IDs.
29
29
  - Confirmed snapshots from one tab are only applied to others when remote ordering says they are newer than the current version.
30
30
 
@@ -35,7 +35,7 @@ Tabs use a versioned message model so later snapshots do not overwrite fresher r
35
35
  - When `sessionKey` changes (for example, login/logout), sync state is refreshed for the new session.
36
36
  - If transport is unavailable, sync becomes inactive silently.
37
37
 
38
- Enable `createStoreManager({ debug: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debug` to route those entries to your own observability tool.
38
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect transport open/close, publish, receive, skipped-message events, and leader changes in development. Store data sync uses store-specific channels, while tab-presence status uses one shared `presence` channel per manager/session. Presence prioritizes the focused tab; background tabs announce open/focus/blur changes and keep their last known fallback rank during quiet periods. Leader-change entries include the elected `leaderTabId`, whether the local tab is the leader, the local tab rank, and the ranked live-tab snapshot. Pass a logger function as `debugLogger` to route those entries to your own tooling.
39
39
 
40
40
  ## Required options
41
41
 
@@ -47,6 +47,7 @@ const storeManager = createStoreManager({
47
47
  return isLoggedIn ? `tenant:${tenantId}` : false;
48
48
  },
49
49
  errorNormalizer: normalizeError,
50
+ backgroundCoalescingDelayMs: 3_000,
50
51
  });
51
52
 
52
53
  const store = createDocumentStore({
@@ -14,8 +14,8 @@ const storeManager = createStoreManager({
14
14
  getSessionKey: () =>
15
15
  authState.userId ? `tenant:${authState.tenantId}` : false,
16
16
  errorNormalizer: normalizeError,
17
- lowPriorityThrottleMs: 5,
18
- baseCoalescingWindowMs: 10,
17
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
18
+ baseCoalescingWindowMs: 16,
19
19
  blockWindowClose: null,
20
20
  });
21
21
 
@@ -14,8 +14,8 @@ const storeManager = createStoreManager({
14
14
  getSessionKey: () =>
15
15
  authState.userId ? `tenant:${authState.tenantId}` : false,
16
16
  errorNormalizer: normalizeError,
17
- lowPriorityThrottleMs: 5,
18
- baseCoalescingWindowMs: 10,
17
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
18
+ baseCoalescingWindowMs: 16,
19
19
  blockWindowClose: null,
20
20
  });
21
21
 
@@ -116,8 +116,8 @@ const storeManager = createStoreManager({
116
116
  getSessionKey: () =>
117
117
  authState.userId ? `tenant:${authState.tenantId}` : false,
118
118
  errorNormalizer: normalizeError,
119
- lowPriorityThrottleMs: 5,
120
- baseCoalescingWindowMs: 10,
119
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
120
+ baseCoalescingWindowMs: 16,
121
121
  blockWindowClose: null,
122
122
  });
123
123