tsdf 17.0.0-alpha.8 → 17.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/async-storage.d.ts +1 -1
  2. package/dist/async-storage.js +2 -1
  3. package/dist/asyncStorageAdapter-CGfnsd9m.js +1945 -0
  4. package/dist/{asyncStorageAdapter-kvAIhrBD.d.ts → asyncStorageAdapter-CMohMeKm.d.ts} +1 -1
  5. package/dist/asyncStorageAdapters-BpfM2_Y6.js +3 -0
  6. package/dist/indexed-db-storage.d.ts +4 -2
  7. package/dist/indexed-db-storage.js +2 -1
  8. package/dist/indexedDbPersistentStorage-DC9GsYHH.js +954 -0
  9. package/dist/main.d.ts +355 -414
  10. package/dist/main.js +16046 -1
  11. package/dist/opfs-storage.d.ts +1 -1
  12. package/dist/opfs-storage.js +2 -1
  13. package/dist/{opfsPersistentStorage-D_fecOJg.d.ts → opfsPersistentStorage-Ci0JcCo5.d.ts} +1 -1
  14. package/dist/opfsPersistentStorage-DqJXzF7M.js +892 -0
  15. package/dist/{types-DkNgE_f9.d.ts → types-D0ttVGmj.d.ts} +395 -65
  16. package/docs/README.md +16 -16
  17. package/docs/batch-fetching.md +1 -1
  18. package/docs/browser-tabs-sync.md +5 -2
  19. package/docs/collection-store.md +26 -24
  20. package/docs/document-store.md +8 -6
  21. package/docs/fetch-scheduling.md +18 -14
  22. package/docs/list-query-store.md +37 -35
  23. package/docs/mutations.md +2 -0
  24. package/docs/offline.md +2 -2
  25. package/docs/offset-pagination.md +1 -4
  26. package/docs/optimistic-list-updates.md +13 -17
  27. package/docs/partial-resources.md +26 -1
  28. package/docs/persistent-storage.md +4 -2
  29. package/docs/real-time-updates.md +7 -5
  30. package/docs/store-manager.md +41 -14
  31. package/package.json +6 -3
  32. package/dist/asyncStorageAdapter-CgG3vm0t.js +0 -1
  33. package/dist/asyncStorageAdapters-eagaD77Y.js +0 -1
  34. package/dist/indexedDbPersistentStorage-JYXvMjTG.js +0 -1
  35. package/dist/opfsPersistentStorage-DS-SWDSq.js +0 -1
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) => {
@@ -82,17 +82,17 @@ function UserProfile() {
82
82
 
83
83
  All three store types share these creation options:
84
84
 
85
- | Option | Type | Required | Description |
86
- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
87
- | `storeManager` | `StoreManager` | Yes | Shared global config with session scoping, store defaults, and global store controls |
88
- | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default minimum interval between low-priority fetches |
89
- | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default window to group multiple fetch requests into a batch |
90
- | `mediumPriorityDelayMs` | `number` | No | Delay before medium-priority fetches execute |
91
- | `dynamicRealtimeThrottleMs` | `(params) => number` | No | Dynamic throttle for [real-time updates](./real-time-updates.md) |
92
- | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Overrides the manager default for refetching data when window regains focus. Use `false` to disable |
93
- | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
94
- | `persistentStorage` | `DocumentPersistentStorageConfig<...> \| CollectionPersistentStorageConfig<...> \| ListQueryPersistentStorageConfig<...>` | No | Configure cache persistence and optional session-based offline behavior |
95
- | `usesRealTimeUpdates` | `boolean` | No | Enables [real-time update mode](./real-time-updates.md) |
96
- | `onSchedulerEvent` | `(event) => void` | No | Callback for [scheduler events](./fetch-scheduling.md) |
97
- | `onMutationError` | `(error, options) => void \| null` | No | Store-specific handler for [mutation](./mutations.md) errors. Overrides the manager fallback; use `null` to disable it |
98
- | `id` | `string` | Yes | Stable logical store id used for debug labels, persistence namespaces, and [Browser Tabs Sync](./browser-tabs-sync.md) |
85
+ | Option | Type | Required | Description |
86
+ | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
87
+ | `storeManager` | `StoreManager` | Yes | Shared global config with session scoping, store defaults, and global store controls |
88
+ | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default minimum interval between low-priority fetches |
89
+ | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default window to group multiple fetch requests into a batch |
90
+ | `mediumPriorityDelayMs` | `number` | No | Delay before medium-priority fetches execute |
91
+ | `dynamicRealtimeThrottleMs` | `(params) => number` | No | Overrides the manager default dynamic throttle for [real-time updates](./real-time-updates.md). Built-in manager default: `100ms` focused, `1000ms` background |
92
+ | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Overrides the manager default for refetching data when window regains focus. Use `false` to disable |
93
+ | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
94
+ | `persistentStorage` | `DocumentPersistentStorageConfig<...> \| CollectionPersistentStorageConfig<...> \| ListQueryPersistentStorageConfig<...>` | No | Configure cache persistence and optional session-based offline behavior |
95
+ | `usesRealTimeUpdates` | `boolean` | No | Enables [real-time update mode](./real-time-updates.md) |
96
+ | `onSchedulerEvent` | `(event) => void` | No | Callback for [scheduler events](./fetch-scheduling.md) |
97
+ | `onMutationError` | `(error, options) => void \| null` | No | Store-specific handler for [mutation](./mutations.md) errors. Overrides the manager fallback; use `null` to disable it |
98
+ | `id` | `string` | Yes | Stable logical store id used for debug labels, persistence namespaces, and [Browser Tabs Sync](./browser-tabs-sync.md) |
@@ -104,7 +104,7 @@ getItemsBatchKey: (payload) => {
104
104
 
105
105
  ## Max Batch Size
106
106
 
107
- When `maxBatchSize` is set, the scheduler triggers an immediate fetch (skipping the remaining coalescing window) once the batch reaches that size:
107
+ When `maxBatchSize` is set, the scheduler triggers an immediate fetch (skipping the remaining coalescing window) once the batch reaches that size. List Query Store uses `maxItemBatchSize` for the same behavior, and it defaults to `50`:
108
108
 
109
109
  ```ts
110
110
  {
@@ -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,6 +35,8 @@ 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({ 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
+
38
40
  ## Required options
39
41
 
40
42
  Add the following options to any store that should sync:
@@ -45,6 +47,7 @@ const storeManager = createStoreManager({
45
47
  return isLoggedIn ? `tenant:${tenantId}` : false;
46
48
  },
47
49
  errorNormalizer: normalizeError,
50
+ backgroundCoalescingDelayMs: 3_000,
48
51
  });
49
52
 
50
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
 
@@ -28,28 +28,30 @@ const productStore = createCollectionStore<Product, string>({
28
28
 
29
29
  ## Options
30
30
 
31
- | Option | Type | Required | Description |
32
- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
33
- | `id` | `string` | Yes | Stable logical store id used for debug labels, persistence namespaces, and [Browser Tabs Sync](./browser-tabs-sync.md) |
34
- | `storeManager` | `StoreManager` | Yes | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
35
- | `fetchFn` | `(params: ItemPayload, signal: AbortSignal) => Promise<ItemState>` | Yes | Fetches a single item |
36
- | `batchFetchFn` | `(payloads: ItemPayload[], signal: AbortSignal, batchKey: string) => Promise<Map<ItemPayload, ItemState \| Error>>` | No | See [Batch Fetching](./batch-fetching.md) |
37
- | `getItemsBatchKey` | `(payload: ItemPayload) => string \| false` | No | Groups batch fetches by key. `false` falls back to per-item fetch |
38
- | `maxBatchSize` | `number` | No | Triggers immediate fetch when batch reaches this size |
39
- | `maxItems` | `number` | No | Maximum cached items kept in memory. Defaults to `5000`. See [Cache Limits](./cache-limits.md) |
40
- | `onStateCleanup` | `(cleanup) => void` | No | Called when memory cache eviction removes items. See [Cache Limits](./cache-limits.md) |
41
- | `getCollectionItemKey` | `(params: ItemPayload) => ValidPayload \| unknown[]` | No | Custom key derivation from payload |
42
- | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
43
- | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
44
- | `mediumPriorityDelayMs` | `number` | No | Delay for medium-priority fetches |
45
- | `dynamicRealtimeThrottleMs` | `(params) => number` | No | See [Real-Time Updates](./real-time-updates.md) |
46
- | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Refetch on window focus |
47
- | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
48
- | `usesRealTimeUpdates` | `boolean` | No | See [Real-Time Updates](./real-time-updates.md) |
49
- | `persistentStorage` | `CollectionPersistentStorageConfig<ItemState, ItemPayload>` | No | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
50
- | `onInvalidate` | `(props: { itemState, payload, priority }) => void` | No | Called when an item is invalidated |
51
- | `onSchedulerEvent` | `(event, data?) => void` | No | Scheduler event listener |
52
- | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | No | Global mutation error handler |
31
+ | Option | Type | Required | Description |
32
+ | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
33
+ | `id` | `string` | Yes | Stable logical store id used for debug labels, persistence namespaces, and [Browser Tabs Sync](./browser-tabs-sync.md) |
34
+ | `storeManager` | `StoreManager` | Yes | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
35
+ | `fetchFn` | `(params, signal) => Promise<ItemState \| Result<ItemState, Error>>` | Yes | Fetches a single item |
36
+ | `batchFetchFn` | `(payloads, signal, batchKey) => Promise<Map<ItemPayload, ItemState \| Error \| Result<ItemState, Error>> \| Result<Map>>` | No | See [Batch Fetching](./batch-fetching.md) |
37
+ | `getItemsBatchKey` | `(payload: ItemPayload) => string \| false` | No | Groups batch fetches by key. `false` falls back to per-item fetch |
38
+ | `maxBatchSize` | `number` | No | Triggers immediate fetch when batch reaches this size |
39
+ | `maxItems` | `number` | No | Maximum cached items kept in memory. Defaults to `5000`. See [Cache Limits](./cache-limits.md) |
40
+ | `onStateCleanup` | `(cleanup) => void` | No | Called when memory cache eviction removes items. See [Cache Limits](./cache-limits.md) |
41
+ | `getCollectionItemKey` | `(params: ItemPayload) => ValidPayload \| unknown[]` | No | Custom key derivation from payload |
42
+ | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
43
+ | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
44
+ | `mediumPriorityDelayMs` | `number` | No | Delay for medium-priority fetches |
45
+ | `dynamicRealtimeThrottleMs` | `(params) => number` | No | Overrides the manager default. See [Real-Time Updates](./real-time-updates.md) |
46
+ | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Refetch on window focus |
47
+ | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
48
+ | `usesRealTimeUpdates` | `boolean` | No | See [Real-Time Updates](./real-time-updates.md) |
49
+ | `persistentStorage` | `CollectionPersistentStorageConfig<ItemState, ItemPayload>` | No | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
50
+ | `onInvalidate` | `(props: { itemState, payload, priority }) => void` | No | Called when an item is invalidated |
51
+ | `onSchedulerEvent` | `(event, data?) => void` | No | Scheduler event listener |
52
+ | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | No | Global mutation error handler |
53
+
54
+ Fetch callbacks return promises. The resolved value may be either plain data or a `Result`. `Result.ok(data)` is stored as successful data; `Result.err(error)` is normalized into the item error state.
53
55
 
54
56
  ## Item State Shape
55
57
 
@@ -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
 
@@ -32,10 +32,10 @@ const userStore = createDocumentStore<User>({
32
32
  | ------------------------------ | -------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
33
33
  | `id` | `string` | Yes | Stable logical store id used for debug labels, persistence namespaces, and [Browser Tabs Sync](./browser-tabs-sync.md) |
34
34
  | `storeManager` | `StoreManager` | Yes | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
35
- | `fetchFn` | `(signal: AbortSignal) => Promise<State>` | Yes | Fetches the document data |
35
+ | `fetchFn` | `(signal: AbortSignal) => Promise<State \| Result<State, Error>>` | Yes | Fetches the document data |
36
36
  | `lowPriorityThrottleMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
37
37
  | `baseCoalescingWindowMs` | `number` | No | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
38
- | `dynamicRealtimeThrottleMs` | `(params: { lastFetchDuration: number; windowIsNotFocused: boolean }) => number` | No | See [Real-Time Updates](./real-time-updates.md) |
38
+ | `dynamicRealtimeThrottleMs` | `(params: { lastFetchDuration: number; windowIsNotFocused: boolean }) => number` | No | Overrides the manager default. See [Real-Time Updates](./real-time-updates.md) |
39
39
  | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | No | Refetch on window focus |
40
40
  | `transportReconnectCooldownMs` | `number` | No | Cooldown for repeated transport reconnect revalidation |
41
41
  | `mediumPriorityDelayMs` | `number` | No | Delay for medium-priority fetches |
@@ -44,6 +44,8 @@ const userStore = createDocumentStore<User>({
44
44
  | `onSchedulerEvent` | `(event) => void` | No | Scheduler event listener |
45
45
  | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | No | Global mutation error handler |
46
46
 
47
+ `fetchFn` returns a promise. The resolved value may be either plain data or a `Result`. `Result.ok(data)` is stored as successful data; `Result.err(error)` is normalized into the store error state.
48
+
47
49
  ## State Shape
48
50
 
49
51
  ```ts
@@ -114,8 +116,8 @@ const storeManager = createStoreManager({
114
116
  getSessionKey: () =>
115
117
  authState.userId ? `tenant:${authState.tenantId}` : false,
116
118
  errorNormalizer: normalizeError,
117
- lowPriorityThrottleMs: 5,
118
- baseCoalescingWindowMs: 10,
119
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
120
+ baseCoalescingWindowMs: 16,
119
121
  blockWindowClose: null,
120
122
  });
121
123
 
@@ -18,7 +18,7 @@ Every fetch request has a priority that determines its behavior:
18
18
  Low-priority fetches are throttled to avoid redundant requests:
19
19
 
20
20
  ```
21
- lowPriorityThrottleMs: 5
21
+ lowPriorityThrottleMs: 40 * 60 * 1_000
22
22
  ```
23
23
 
24
24
  If a hook mounts within the configured throttle window after the last fetch completed, the low-priority fetch is **skipped** because the data is still fresh enough.
@@ -28,14 +28,14 @@ If a hook mounts within the configured throttle window after the last fetch comp
28
28
  When multiple fetch requests arrive in a short window, they are coalesced into a single batch:
29
29
 
30
30
  ```
31
- baseCoalescingWindowMs: 10
31
+ baseCoalescingWindowMs: 16
32
32
  ```
33
33
 
34
34
  If three `useItem` hooks mount within the configured coalescing window, their fetches are grouped and executed as one request (when using batch fetching) or sequentially but without duplicate requests for the same item.
35
35
 
36
36
  ### Background Tabs
37
37
 
38
- When synced browser tabs are open, TSDF can extend coalescing internally for background tabs based on focus ranking. Focused tabs keep `baseCoalescingWindowMs`; background tabs may wait longer so duplicate background work can be dropped when another tab is already fetching the same data.
38
+ When synced browser tabs are open, TSDF can extend coalescing internally for background tabs based on focus ranking. Focused tabs keep `baseCoalescingWindowMs`; background tabs use `baseCoalescingWindowMs + backgroundCoalescingDelayMs + backgroundRank * 1000ms`, where the first background tab has rank `0`. This gives sibling tabs time to drop duplicate background work when another tab is already fetching the same data.
39
39
 
40
40
  See [Browser Tabs Sync](./browser-tabs-sync.md) for focus ranking and request deduplication behavior across tabs.
41
41
 
@@ -69,23 +69,27 @@ This is useful for background refetches that should yield to user-initiated acti
69
69
 
70
70
  ## Configuration Reference
71
71
 
72
- | Option | Required | Description |
73
- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------- |
74
- | `lowPriorityThrottleMs` | No | Manager default minimum interval between low-priority fetches, or a store-level override. Defaults to `5` |
75
- | `baseCoalescingWindowMs` | No | Manager default time window to group multiple requests into a single batch, or a store-level override. Defaults to `10` |
76
- | `mediumPriorityDelayMs` | No | Delay before medium-priority fetches execute |
77
- | `dynamicRealtimeThrottleMs` | No | Function returning throttle duration for real-time updates. See [Real-Time Updates](./real-time-updates.md) |
78
- | `maxBatchSize` | No | (Collection/ListQuery) Triggers immediate fetch when batch size is reached, skipping the coalescing window |
72
+ | Option | Required | Description |
73
+ | ----------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
74
+ | `lowPriorityThrottleMs` | No | Manager default minimum interval between low-priority fetches, or a store-level override. Defaults to 40 minutes (`2_400_000ms`) |
75
+ | `baseCoalescingWindowMs` | No | Manager default time window to group multiple requests into a single batch, or a store-level override. Defaults to `16ms` |
76
+ | `backgroundCoalescingDelayMs` | No | Manager-level delay added only for background browser tabs before the per-rank `1000ms` step. Defaults to `3000ms` |
77
+ | `mediumPriorityDelayMs` | No | Delay before medium-priority fetches execute |
78
+ | `dynamicRealtimeThrottleMs` | No | Manager default or store override returning throttle duration for real-time updates. Built-in default: `100ms` focused, `1000ms` background. See [Real-Time Updates](./real-time-updates.md) |
79
+ | `maxBatchSize` / `maxItemBatchSize` | No | Collection/ListQuery batch cap. List Query `maxItemBatchSize` defaults to `50`. Triggers immediate fetch when reached |
79
80
 
80
81
  ## Typical Configuration
81
82
 
82
83
  ```ts
83
84
  {
84
- // Skip refetch if one happened in the last 5ms
85
- lowPriorityThrottleMs: 5,
85
+ // Skip refetch if one happened in the last 40 minutes
86
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
86
87
 
87
- // Group fetches within 10ms
88
- baseCoalescingWindowMs: 10,
88
+ // Group fetches within 16ms
89
+ baseCoalescingWindowMs: 16,
90
+
91
+ // Add 3s before background browser-tab rank staggering
92
+ backgroundCoalescingDelayMs: 3_000,
89
93
 
90
94
  // Wait 300ms before executing medium-priority fetches
91
95
  mediumPriorityDelayMs: 300,
@@ -20,8 +20,8 @@ const storeManager = createStoreManager({
20
20
  getSessionKey: () =>
21
21
  authState.userId ? `tenant:${authState.tenantId}` : false,
22
22
  errorNormalizer: normalizeError,
23
- lowPriorityThrottleMs: 5,
24
- baseCoalescingWindowMs: 10,
23
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
24
+ baseCoalescingWindowMs: 16,
25
25
  blockWindowClose: null,
26
26
  });
27
27
 
@@ -45,42 +45,44 @@ The type parameters are:
45
45
 
46
46
  ### Required Options
47
47
 
48
- | Option | Type | Description |
49
- | -------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
50
- | `id` | `string` | Stable logical store id used for debug labels, persistence namespaces, and tab sync |
51
- | `storeManager` | `StoreManager` | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
52
- | `fetchListFn` | Size mode: `(payload, size, options) => Promise<FetchListFnReturn>` | Fetches a paginated list. See [Pagination modes](#pagination-modes) |
48
+ | Option | Type | Description |
49
+ | -------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
50
+ | `id` | `string` | Stable logical store id used for debug labels, persistence namespaces, and tab sync |
51
+ | `storeManager` | `StoreManager` | Shared global config with `getSessionKey`, `errorNormalizer`, and global store controls |
52
+ | `fetchListFn` | Size mode: `(payload, size, options) => Promise<FetchListFnReturn \| Result<FetchListFnReturn, Error>>` | Fetches a paginated list. See [Pagination modes](#pagination-modes) |
53
53
 
54
54
  ### Optional Options
55
55
 
56
- | Option | Type | Description |
57
- | ------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- |
58
- | `lowPriorityThrottleMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
59
- | `baseCoalescingWindowMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
60
- | `fetchItemFn` | `(payload, options: { signal, fields? }) => Promise<ItemState>` | Fetches a single item. Required for `useItem`, `invalidateItem`, `scheduleItemFetch` |
61
- | `batchFetchItemFn` | `(requests, options) => Promise<Map<ItemPayload, ItemState \| Error>>` | See [Batch Fetching](./batch-fetching.md) |
62
- | `getItemsBatchKey` | `(payload: ItemPayload) => string \| false` | See [Batch Fetching](./batch-fetching.md) |
63
- | `defaultQuerySize` | `number` | Default page size (default: `50`) |
64
- | `maxItemBatchSize` | `number` | Max items per batch fetch |
65
- | `maxItems` | `number` | Maximum cached items kept in memory. Defaults to `5000`. See [Cache Limits](./cache-limits.md) |
66
- | `maxQueries` | `number` | Maximum cached queries kept in memory. Defaults to `1000`. See [Cache Limits](./cache-limits.md) |
67
- | `onStateCleanup` | `(cleanup) => void` | Called when memory cache eviction removes items or queries. See [Cache Limits](./cache-limits.md) |
68
- | `optimisticListUpdates` | `OptimisticListUpdate[]` | See [Optimistic List Updates](./optimistic-list-updates.md) |
69
- | `partialResources` | `PartialResourcesConfig` | See [Partial Resources](./partial-resources.md) |
70
- | `derivedQueries` | `DerivedQueriesConfig` | Derive hook results from local items instead of fetching when possible |
71
- | `offsetPagination` | `OffsetPaginationConfig` | See [Offset Pagination](./offset-pagination.md) |
72
- | `getQueryKey` | `(params) => ValidPayload \| unknown[]` | Custom query key derivation |
73
- | `getItemKey` | `(params) => ValidPayload \| unknown[]` | Custom item key derivation |
74
- | `mediumPriorityDelayMs` | `number` | Delay before medium-priority fetches execute |
75
- | `dynamicRealtimeThrottleMs` | `(params) => number` | See [Real-Time Updates](./real-time-updates.md) |
76
- | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | Refetch on window focus |
77
- | `transportReconnectCooldownMs` | `number` | Cooldown for repeated transport reconnect revalidation |
78
- | `usesRealTimeUpdates` | `boolean` | See [Real-Time Updates](./real-time-updates.md) |
79
- | `onInvalidateQuery` | `(query, priority) => void` | Called when a query is invalidated |
80
- | `onInvalidateItem` | `(props: { itemState, payload, priority }) => void` | Called when an item is invalidated |
81
- | `persistentStorage` | `ListQueryPersistentStorageConfig<ItemState, QueryPayload, ItemPayload>` | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
82
- | `onSchedulerEvent` | `(event, data?) => void` | Scheduler event listener |
83
- | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | Global mutation error handler |
56
+ | Option | Type | Description |
57
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
58
+ | `lowPriorityThrottleMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
59
+ | `baseCoalescingWindowMs` | `number` | Overrides the manager default. See [Fetch Scheduling](./fetch-scheduling.md) |
60
+ | `fetchItemFn` | `(payload, options) => Promise<ItemState \| Result<ItemState, Error>>` | Fetches a single item. Required for `useItem`, `invalidateItem`, `scheduleItemFetch` |
61
+ | `batchFetchItemFn` | `(requests, options) => Promise<Map<ItemPayload, ItemState \| Error \| Result<ItemState, Error>> \| Result<Map>>` | See [Batch Fetching](./batch-fetching.md) |
62
+ | `getItemsBatchKey` | `(payload: ItemPayload) => string \| false` | See [Batch Fetching](./batch-fetching.md) |
63
+ | `defaultQuerySize` | `number` | Default page size (default: `50`) |
64
+ | `maxItemBatchSize` | `number` | Max items per batch fetch. Defaults to `50` |
65
+ | `maxItems` | `number` | Maximum cached items kept in memory. Defaults to `5000`. See [Cache Limits](./cache-limits.md) |
66
+ | `maxQueries` | `number` | Maximum cached queries kept in memory. Defaults to `1000`. See [Cache Limits](./cache-limits.md) |
67
+ | `onStateCleanup` | `(cleanup) => void` | Called when memory cache eviction removes items or queries. See [Cache Limits](./cache-limits.md) |
68
+ | `optimisticListUpdates` | `OptimisticListUpdate[]` | See [Optimistic List Updates](./optimistic-list-updates.md) |
69
+ | `partialResources` | `PartialResourcesConfig` | See [Partial Resources](./partial-resources.md) |
70
+ | `derivedQueries` | `DerivedQueriesConfig` | Derive hook results from local items instead of fetching when possible |
71
+ | `offsetPagination` | `OffsetPaginationConfig` | See [Offset Pagination](./offset-pagination.md) |
72
+ | `getQueryKey` | `(params) => ValidPayload \| unknown[]` | Custom query key derivation |
73
+ | `getItemKey` | `(params) => ValidPayload \| unknown[]` | Custom item key derivation |
74
+ | `mediumPriorityDelayMs` | `number` | Delay before medium-priority fetches execute |
75
+ | `dynamicRealtimeThrottleMs` | `(params) => number` | Overrides the manager default. See [Real-Time Updates](./real-time-updates.md) |
76
+ | `revalidateOnWindowFocus` | `boolean \| (() => boolean)` | Refetch on window focus |
77
+ | `transportReconnectCooldownMs` | `number` | Cooldown for repeated transport reconnect revalidation |
78
+ | `usesRealTimeUpdates` | `boolean` | See [Real-Time Updates](./real-time-updates.md) |
79
+ | `onInvalidateQuery` | `(query, priority) => void` | Called when a query is invalidated |
80
+ | `onInvalidateItem` | `(props: { itemState, payload, priority }) => void` | Called when an item is invalidated |
81
+ | `persistentStorage` | `ListQueryPersistentStorageConfig<ItemState, QueryPayload, ItemPayload>` | Configure cache persistence. See [Persistent Storage](./persistent-storage.md) |
82
+ | `onSchedulerEvent` | `(event, data?) => void` | Scheduler event listener |
83
+ | `onMutationError` | `(error, options: { silentErrors?: boolean }) => void` | Global mutation error handler |
84
+
85
+ Fetch callbacks return promises. The resolved value may be either plain data or a `Result`. `Result.ok(data)` is handled as a successful fetch; `Result.err(error)` is normalized into the query or item error state.
84
86
 
85
87
  ### FetchListFnReturn
86
88
 
package/docs/mutations.md CHANGED
@@ -42,6 +42,8 @@ The `mutation` callback receives:
42
42
  - `updateState` - An immer-based function to update state during the mutation
43
43
  - `currentState` - The current data at the time the mutation executes
44
44
 
45
+ Mutation callbacks return promises. The resolved value may be either a plain value or a `Result`. `Result.ok(value)` is treated like resolving to `value`; `Result.err(error)` is handled like rejecting with `error`, including optimistic rollback, error normalization, and offline fallback classification.
46
+
45
47
  ### Collection Store
46
48
 
47
49
  ```ts
package/docs/offline.md CHANGED
@@ -34,8 +34,8 @@ type UserOfflineOperations = DefineListQueryOfflineOperations<
34
34
  const storeManager = createStoreManager({
35
35
  getSessionKey: () => currentTenantId ?? false,
36
36
  errorNormalizer: normalizeError,
37
- lowPriorityThrottleMs: 5,
38
- baseCoalescingWindowMs: 10,
37
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
38
+ baseCoalescingWindowMs: 16,
39
39
  blockWindowClose: null,
40
40
  offlineSession: {
41
41
  network: { enabled: true },
@@ -17,10 +17,7 @@ const store = createListQueryStore<Task, TaskFilter, string, false, true>({
17
17
  return api.getTasks(filter, { offset, limit, signal });
18
18
  },
19
19
 
20
- offsetPagination: {
21
- maxInvalidationLimit: 200,
22
- maxParallel: 3,
23
- },
20
+ offsetPagination: { maxInvalidationLimit: 200, maxParallel: 3 },
24
21
 
25
22
  // ...other options
26
23
  });
@@ -30,9 +30,6 @@ const taskStore = createListQueryStore<Task, TaskFilter, string>({
30
30
 
31
31
  // Where to add new items
32
32
  appendNewTo: 'start',
33
-
34
- // Trigger background revalidation when items are moved
35
- invalidateQueries: true,
36
33
  },
37
34
  {
38
35
  // Sort a specific query by priority
@@ -112,7 +109,9 @@ Sorting is applied only to queries that contain the updated item.
112
109
 
113
110
  ### invalidateQueries
114
111
 
115
- When `true`, queries affected by the optimistic update are invalidated in the background. This ensures the server's actual ordering/filtering is fetched eventually.
112
+ Schedules a background refetch of queries this rule mutated.
113
+
114
+ **Leave off by default.** Only enable when the optimistic update can't represent the final server state — e.g. sort depends on a server-assigned field (`updatedAt`, computed score), membership depends on server-only data (permissions, full-text match), or cursor pagination shifts the page window. If `filterItem` and `sort` already match the server, the extra refetch is just noise.
116
115
 
117
116
  ```ts
118
117
  invalidateQueries: true;
@@ -137,8 +136,8 @@ They are **not** triggered by:
137
136
  const storeManager = createStoreManager({
138
137
  getSessionKey: () => currentTenantId ?? false,
139
138
  errorNormalizer: normalizeError,
140
- lowPriorityThrottleMs: 5,
141
- baseCoalescingWindowMs: 10,
139
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
140
+ baseCoalescingWindowMs: 16,
142
141
  blockWindowClose: null,
143
142
  });
144
143
 
@@ -149,31 +148,28 @@ const taskStore = createListQueryStore<Task, { status: string }, string>({
149
148
  fetchItemFn: (id, { signal }) => api.getTask(id, signal),
150
149
 
151
150
  optimisticListUpdates: [
152
- {
153
- // Move tasks between status columns
154
- queries: (q) => true,
155
- filterItem: (item) => item.status === 'todo',
156
- // Only applies to queries where status matches
157
- },
151
+ // Membership follows status — the optimistic change is final.
158
152
  {
159
153
  queries: { status: 'todo' },
160
154
  filterItem: (item) => item.status === 'todo',
161
155
  appendNewTo: 'start',
162
- invalidateQueries: true,
163
156
  },
164
157
  {
165
158
  queries: { status: 'done' },
166
159
  filterItem: (item) => item.status === 'done',
167
160
  appendNewTo: 'end',
161
+ },
162
+ // Server sorts by `updatedAt`, which it assigns — refetch to settle order.
163
+ {
164
+ queries: (q) => true,
165
+ sort: { sortBy: (item) => item.updatedAt, order: 'desc' },
168
166
  invalidateQueries: true,
169
167
  },
170
168
  ],
171
169
  });
172
170
 
173
- // When a task is moved to "done", it's automatically:
174
- // 1. Removed from the "todo" query
175
- // 2. Added to the "done" query
176
- // 3. Both queries are revalidated in the background
171
+ // Moving "task-1" to done removes it from the todo query and adds it to the
172
+ // done query. Only the sort rule triggers a background refetch.
177
173
  taskStore.updateItemState('task-1', (draft) => {
178
174
  draft.status = 'done';
179
175
  });
@@ -44,10 +44,18 @@ const userStore = createListQueryStore<User, UserFilter, string, true>({
44
44
  selectFields: (fields, item) => {
45
45
  const result: Partial<User> = {};
46
46
  for (const field of fields) {
47
- result[field] = item[field];
47
+ if (item[field] !== undefined) {
48
+ result[field] = item[field];
49
+ }
48
50
  }
49
51
  return result as User;
50
52
  },
53
+
54
+ // Report which logical fields are genuinely present in an item snapshot —
55
+ // the only signal for metadata-free snapshots (manually added or offline
56
+ // items), and a way to vouch for fields present beyond tracked metadata.
57
+ inferFields: (item) =>
58
+ Object.keys(item).filter((field) => item[field] !== undefined),
51
59
  },
52
60
 
53
61
  // ...other options
@@ -61,6 +69,7 @@ const userStore = createListQueryStore<User, UserFilter, string, true>({
61
69
  3. When a hook requests fields that haven't been loaded yet, a fetch is triggered requesting only the missing fields
62
70
  4. The `mergeItems` function combines the newly fetched data with previously loaded data
63
71
  5. The `selectFields` function extracts the requested fields for the hook's return value
72
+ 6. The `inferFields` function reports which fields are genuinely present in an item snapshot, complementing (or substituting for) the tracked metadata
64
73
 
65
74
  ## Using Fields in Hooks
66
75
 
@@ -130,6 +139,8 @@ When a hook requests fields that are partially loaded:
130
139
 
131
140
  If you enable `showPartialAsRefetching`, the hook exposes `loadingFields` with the requested fields that are still pending. When cached partial data already exists, TSDF keeps it visible during the follow-up fetch.
132
141
 
142
+ Invalidations are refetches, not new loads: when an invalidation (full or per-field) marks cached data as stale, hooks whose requested fields are still present keep the stale data visible while the refetch is in flight (with a `refetching` status when `returnRefetchingStatus` is enabled). Data is only hidden behind `loading` when a requested field was genuinely never loaded.
143
+
133
144
  ## Fields in Scheduling and Fetching
134
145
 
135
146
  Fields propagate through the scheduling and fetching APIs:
@@ -166,3 +177,17 @@ selectFields: (fields: string[], item: ItemState) => ItemState;
166
177
  ```
167
178
 
168
179
  Called when a hook requests specific fields. Should return an item containing only the requested fields.
180
+
181
+ ### inferFields
182
+
183
+ ```ts
184
+ inferFields: (item: ItemState) => string[] | '*';
185
+ ```
186
+
187
+ Reports which logical fields are genuinely present in an item snapshot. Return the available fields, or `'*'` if the snapshot is complete.
188
+
189
+ It is the only availability signal for snapshots without `itemLoadedFields` metadata — manually inserted items, persisted fallback snapshots, and offline optimistic rows. But it is also consulted for metadata-tracked items: the loaded-fields metadata only records what fetches delivered, so `inferFields` can additionally vouch for fields that are present beyond the tracked list (e.g. written into the item by a mutation), avoiding refetches of data that is already there. Returning `'*'` marks the snapshot complete even when the tracked metadata is a partial field list.
190
+
191
+ Because it can vouch for any snapshot, `inferFields` must only report fields whose data is genuinely usable — inspect the item, don't return `'*'` unconditionally unless every snapshot your store can ever hold is complete. Staleness is not its concern: fields awaiting an invalidation refetch are excluded by TSDF before `inferFields` is consulted.
192
+
193
+ TSDF does not infer fields by checking object keys internally. If your field names are top-level properties, implement that rule explicitly in `inferFields` (excluding keys with `undefined` values); if your fields are logical or nested, return those logical field names instead.
@@ -64,6 +64,8 @@ Store-specific options:
64
64
 
65
65
  > `persistentStorage` automatically reuses the store's existing `id` for its storage namespace and the store manager's `getSessionKey` for session scoping. When `getSessionKey` returns `false`, no persistence operations run.
66
66
 
67
+ Enable `createStoreManager({ debugLogger: true, ... })` to inspect load, save/write, commit, clear, metadata, and offline protection persistence operations in development. Production-safe quota cleanup logs are emitted through the manager `logger` by default; they include the affected quota, configured byte budget, total unprotected bytes, and kept/evicted entry counts. Pass `logger: false` to disable them. Async adapters also emit timed `adapter-operation` entries with `durationMs` for concrete OPFS, IndexedDB, or custom driver work in development.
68
+
67
69
  ## Converted Data Schemas
68
70
 
69
71
  Use `ConvertedPersistentStorageDataSchema<TStore, TStorage>` when the in-memory store shape should differ from the data saved in persistent storage. This is useful for compact cache formats, migration-friendly storage shapes, or persisted data that should omit derived fields.
@@ -200,8 +202,8 @@ const getSessionKey = () => (userId ? `tenant:${userId}` : false);
200
202
  const storeManager = createStoreManager({
201
203
  getSessionKey,
202
204
  errorNormalizer: normalizeError,
203
- lowPriorityThrottleMs: 5,
204
- baseCoalescingWindowMs: 10,
205
+ lowPriorityThrottleMs: 40 * 60 * 1_000,
206
+ baseCoalescingWindowMs: 16,
205
207
  blockWindowClose: null,
206
208
  onPersistentStorageError: (error) => {
207
209
  console.error('TSDF persistence failed', error);