tsdf 16.0.3 → 17.0.0-alpha.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.
- package/README.md +2 -0
- package/dist/main.d.ts +2730 -366
- package/dist/main.js +18910 -2474
- package/docs/README.md +98 -0
- package/docs/batch-fetching.md +125 -0
- package/docs/browser-tabs-sync.md +59 -0
- package/docs/cache-limits.md +105 -0
- package/docs/collection-store.md +171 -0
- package/docs/document-store.md +148 -0
- package/docs/fetch-scheduling.md +93 -0
- package/docs/hooks.md +416 -0
- package/docs/invalidation.md +133 -0
- package/docs/list-query-store.md +350 -0
- package/docs/mutations.md +261 -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 +282 -0
- package/docs/real-time-updates.md +158 -0
- package/docs/shared-types.md +169 -0
- package/docs/store-manager.md +128 -0
- package/package.json +63 -46
- package/dist/main.cjs +0 -2511
- package/dist/main.d.cts +0 -400
package/docs/README.md
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# TSDF Documentation
|
|
2
|
+
|
|
3
|
+
TSDF (TypeScript Data Fetching) is a data fetching and caching library for React, built on [t-state](https://github.com/lucasols/t-state). It manages server data with automatic fetching, caching, invalidation, optimistic updates, and real-time update support.
|
|
4
|
+
|
|
5
|
+
## Store Types
|
|
6
|
+
|
|
7
|
+
TSDF provides three store types for different data patterns:
|
|
8
|
+
|
|
9
|
+
| Store | Use case | Key characteristics |
|
|
10
|
+
| ----------------------------------------- | ------------------------------ | ------------------------------------------------ |
|
|
11
|
+
| [Document Store](./document-store.md) | Single entity/document | One fetch function, one piece of data |
|
|
12
|
+
| [Collection Store](./collection-store.md) | Key-value collection of items | Each item fetched independently by payload |
|
|
13
|
+
| [List Query Store](./list-query-store.md) | Paginated lists + item queries | Items shared across queries, supports pagination |
|
|
14
|
+
|
|
15
|
+
## Features
|
|
16
|
+
|
|
17
|
+
| Feature | Applicable stores | Description |
|
|
18
|
+
| ------------------------------------------------------- | ---------------------- | -------------------------------------------------------------------------- |
|
|
19
|
+
| [React Hooks](./hooks.md) | All | `useDocument`, `useItem`, `useListQuery`, and more |
|
|
20
|
+
| [Store Manager](./store-manager.md) | All | Session scoping, global resets, shared offline runtime state |
|
|
21
|
+
| [Fetch Scheduling](./fetch-scheduling.md) | All | Priority levels, throttling, coalescing, and batching |
|
|
22
|
+
| [Browser Tabs Sync](./browser-tabs-sync.md) | All | Cross-tab fetch deduplication and snapshot synchronization |
|
|
23
|
+
| [Mutations](./mutations.md) | All | Data mutations with optimistic updates and revalidation |
|
|
24
|
+
| [Invalidation](./invalidation.md) | All | Mark data as stale and trigger refetches |
|
|
25
|
+
| [Batch Fetching](./batch-fetching.md) | Collection, List Query | Fetch multiple items in a single request |
|
|
26
|
+
| [Cache Limits](./cache-limits.md) | Collection, List Query | Bound in-memory item/query caches with LRU eviction |
|
|
27
|
+
| [Real-Time Updates](./real-time-updates.md) | All | WebSocket/SSE integration with adaptive throttling |
|
|
28
|
+
| [Persistent Storage](./persistent-storage.md) | All | Restore cached data from localStorage, IndexedDB, or OPFS between sessions |
|
|
29
|
+
| [Offline](./offline.md) | All | Durable mutation queueing, replay, conflicts, temp entities, and uploads |
|
|
30
|
+
| [Optimistic List Updates](./optimistic-list-updates.md) | List Query | Auto-sort/filter queries when item state changes |
|
|
31
|
+
| [Partial Resources](./partial-resources.md) | List Query | Fetch only specific fields, with per-field invalidation |
|
|
32
|
+
| [Offset Pagination](./offset-pagination.md) | List Query | Offset/limit-based pagination with chunked invalidation |
|
|
33
|
+
| [Shared Types](./shared-types.md) | All | Common types/utilities (`StoreError`, `IsOffScreenContext`, priorities) |
|
|
34
|
+
|
|
35
|
+
Notable additions:
|
|
36
|
+
|
|
37
|
+
- Hook payload debouncing is documented in [React Hooks](./hooks.md#debouncepayload)
|
|
38
|
+
- The exported `PayloadDebounce` type is documented in [Shared Types](./shared-types.md#payloaddebounce)
|
|
39
|
+
|
|
40
|
+
## Quick Start
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { createDocumentStore, createStoreManager } from 'tsdf';
|
|
44
|
+
|
|
45
|
+
const storeManager = createStoreManager({
|
|
46
|
+
getSessionKey: () => (auth.userId ? `tenant:${auth.tenantId}` : false),
|
|
47
|
+
errorNormalizer: (err) => ({
|
|
48
|
+
code: 500,
|
|
49
|
+
id: 'fetch-error',
|
|
50
|
+
message: err.message,
|
|
51
|
+
}),
|
|
52
|
+
lowPriorityThrottleMs: 5,
|
|
53
|
+
baseCoalescingWindowMs: 10,
|
|
54
|
+
blockWindowClose: null,
|
|
55
|
+
revalidateOnWindowFocus: true,
|
|
56
|
+
onMutationError: (error) => {
|
|
57
|
+
console.error('TSDF mutation failed', error);
|
|
58
|
+
},
|
|
59
|
+
onPersistentStorageError: (error) => {
|
|
60
|
+
console.error('TSDF persistence failed', error);
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
const userStore = createDocumentStore<User>({
|
|
65
|
+
id: 'document-user',
|
|
66
|
+
storeManager,
|
|
67
|
+
fetchFn: (signal) => fetch('/api/user', { signal }).then((r) => r.json()),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
function UserProfile() {
|
|
71
|
+
const { data, status, isLoading } = userStore.useDocument();
|
|
72
|
+
|
|
73
|
+
if (isLoading) return <Loading />;
|
|
74
|
+
if (!data) return null;
|
|
75
|
+
|
|
76
|
+
return <div>{data.name}</div>;
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Common Options
|
|
81
|
+
|
|
82
|
+
All three store types share these creation options:
|
|
83
|
+
|
|
84
|
+
| Option | Type | Required | Description |
|
|
85
|
+
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
86
|
+
| `debugName` | `string` | No | Debug name for the store |
|
|
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 for [Browser Tabs Sync](./browser-tabs-sync.md) |
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# Batch Fetching
|
|
2
|
+
|
|
3
|
+
Batch fetching allows multiple item fetches to be combined into a single network request. Available in [Collection Store](./collection-store.md) and [List Query Store](./list-query-store.md).
|
|
4
|
+
|
|
5
|
+
## How It Works
|
|
6
|
+
|
|
7
|
+
When multiple items need to be fetched around the same time, the [fetch scheduler](./fetch-scheduling.md) groups them during the coalescing window and sends them as a single batch request via your `batchFetchFn`.
|
|
8
|
+
|
|
9
|
+
Without batch fetching, each item triggers its own `fetchFn` call. With batch fetching, items are grouped and passed to `batchFetchFn` together.
|
|
10
|
+
|
|
11
|
+
## Collection Store
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
const storeManager = createStoreManager({
|
|
15
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
16
|
+
errorNormalizer: normalizeError,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const store = createCollectionStore<Product, string>({
|
|
20
|
+
storeManager,
|
|
21
|
+
// Individual fetch (fallback when batch is not used)
|
|
22
|
+
fetchFn: (productId, signal) => api.getProduct(productId, signal),
|
|
23
|
+
|
|
24
|
+
// Batch fetch — receives an array of payloads
|
|
25
|
+
batchFetchFn: (productIds, signal, batchKey) => {
|
|
26
|
+
return api.getProducts(productIds, signal);
|
|
27
|
+
// Returns Map<string, Product | Error>
|
|
28
|
+
},
|
|
29
|
+
|
|
30
|
+
// ...other options
|
|
31
|
+
});
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The `batchFetchFn` must return a `Map` where:
|
|
35
|
+
|
|
36
|
+
- Keys are the original payloads
|
|
37
|
+
- Values are either the fetched data or an `Error` for failed items
|
|
38
|
+
|
|
39
|
+
Items that return an `Error` in the map are handled individually with the error normalizer.
|
|
40
|
+
|
|
41
|
+
## List Query Store
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
const storeManager = createStoreManager({
|
|
45
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
46
|
+
errorNormalizer: normalizeError,
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const store = createListQueryStore<Task, TaskFilter, string>({
|
|
50
|
+
storeManager,
|
|
51
|
+
fetchListFn: (filter, size, { signal }) => api.getTasks(filter, size, signal),
|
|
52
|
+
|
|
53
|
+
// Individual item fetch
|
|
54
|
+
fetchItemFn: (taskId, { signal, fields }) => api.getTask(taskId, signal),
|
|
55
|
+
|
|
56
|
+
// Batch item fetch
|
|
57
|
+
batchFetchItemFn: (requests, { signal, batchKey }) => {
|
|
58
|
+
const payloads = requests.map((r) => r.payload);
|
|
59
|
+
return api.getTasks(payloads, signal);
|
|
60
|
+
// Returns Map<string, Task | Error>
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
// ...other options
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
In List Query Store, `batchFetchItemFn` receives an array of `{ payload, fields? }` objects, allowing each item to request different fields when using [Partial Resources](./partial-resources.md).
|
|
68
|
+
|
|
69
|
+
## Batch Keys
|
|
70
|
+
|
|
71
|
+
By default, all items share a single batch scheduler (batch key `'__default__'`). Use `getItemsBatchKey` to group items into separate batches:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const storeManager = createStoreManager({
|
|
75
|
+
getSessionKey: () => currentTenantId ?? false,
|
|
76
|
+
errorNormalizer: normalizeError,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const store = createCollectionStore<Resource, { type: string; id: string }>({
|
|
80
|
+
storeManager,
|
|
81
|
+
fetchFn: (params, signal) => api.getResource(params, signal),
|
|
82
|
+
batchFetchFn: (payloads, signal, batchKey) => {
|
|
83
|
+
// batchKey is the type — batch requests by resource type
|
|
84
|
+
return api.getResourcesByType(batchKey, payloads, signal);
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
// Group batches by resource type
|
|
88
|
+
getItemsBatchKey: (payload) => payload.type,
|
|
89
|
+
|
|
90
|
+
// ...other options
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Opting Out Per Item
|
|
95
|
+
|
|
96
|
+
Return `false` from `getItemsBatchKey` to fall back to per-item `fetchFn` for specific items:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
getItemsBatchKey: (payload) => {
|
|
100
|
+
if (payload.type === 'special') return false; // use individual fetchFn
|
|
101
|
+
return payload.type; // batch all others by type
|
|
102
|
+
},
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Max Batch Size
|
|
106
|
+
|
|
107
|
+
When `maxBatchSize` is set, the scheduler triggers an immediate fetch (skipping the remaining coalescing window) once the batch reaches that size:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
{
|
|
111
|
+
batchFetchFn: /* ... */,
|
|
112
|
+
maxBatchSize: 50, // fire immediately when 50 items are queued
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
This is useful when you know your API has a limit on batch size.
|
|
117
|
+
|
|
118
|
+
## Scheduler Lifecycle
|
|
119
|
+
|
|
120
|
+
When using batch fetching:
|
|
121
|
+
|
|
122
|
+
- A single scheduler is created per batch key
|
|
123
|
+
- All items with the same batch key share the scheduler's throttling and coalescing
|
|
124
|
+
- When all items for a batch key are deleted from the store, the scheduler is cleaned up
|
|
125
|
+
- Per-item schedulers are used for items that opt out of batching (`getItemsBatchKey` returns `false`)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Browser Tabs Sync
|
|
2
|
+
|
|
3
|
+
TSDF can keep data and fetch activity synchronized across tabs and windows, reducing duplicate network requests and keeping UI state consistent.
|
|
4
|
+
|
|
5
|
+
## Activation requirements
|
|
6
|
+
|
|
7
|
+
Browser tabs sync is available when all of these are true:
|
|
8
|
+
|
|
9
|
+
- All tabs use the same `id` for the same store
|
|
10
|
+
- `storeManager.getSessionKey()` returns the same string in all tabs
|
|
11
|
+
- Tab communication is available (default: `BroadcastChannel`)
|
|
12
|
+
|
|
13
|
+
If `getSessionKey` returns `false`, sync is disabled for that store instance.
|
|
14
|
+
|
|
15
|
+
## What gets synchronized
|
|
16
|
+
|
|
17
|
+
- `fetch-start` and `fetch-success` messages for fetch batches
|
|
18
|
+
- successful fetch snapshots (document, collection item, list query/query+item)
|
|
19
|
+
- local state updates and optimistic mutation updates
|
|
20
|
+
|
|
21
|
+
Tabs use a versioned message model so later snapshots do not overwrite fresher remote state.
|
|
22
|
+
|
|
23
|
+
## Behavior details
|
|
24
|
+
|
|
25
|
+
- Tab status messages include focus and heartbeat data.
|
|
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.
|
|
28
|
+
- `fetch-start` messages let sibling tabs drop duplicate scheduled work when another tab is already fetching the same request IDs.
|
|
29
|
+
- Confirmed snapshots from one tab are only applied to others when remote ordering says they are newer than the current version.
|
|
30
|
+
|
|
31
|
+
## Isolation
|
|
32
|
+
|
|
33
|
+
- Same `id` with different `sessionKey` values do not sync.
|
|
34
|
+
- Different `id` values do not sync.
|
|
35
|
+
- When `sessionKey` changes (for example, login/logout), sync state is refreshed for the new session.
|
|
36
|
+
- If transport is unavailable, sync becomes inactive silently.
|
|
37
|
+
|
|
38
|
+
## Required options
|
|
39
|
+
|
|
40
|
+
Add the following options to any store that should sync:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const storeManager = createStoreManager({
|
|
44
|
+
getSessionKey: () => {
|
|
45
|
+
return isLoggedIn ? `tenant:${tenantId}` : false;
|
|
46
|
+
},
|
|
47
|
+
errorNormalizer: normalizeError,
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const store = createDocumentStore({
|
|
51
|
+
id: 'document-store',
|
|
52
|
+
storeManager,
|
|
53
|
+
/* ... */
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The same keys are used by `createCollectionStore` and `createListQueryStore`.
|
|
58
|
+
|
|
59
|
+
See also: [Fetch Scheduling](./fetch-scheduling.md), where background tab focus ranking is integrated with coalescing.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Cache Limits
|
|
2
|
+
|
|
3
|
+
Collection stores and list-query stores keep recently used state in memory. Cache limits bound that in-memory state so long-lived apps can browse many items or queries without keeping every result forever.
|
|
4
|
+
|
|
5
|
+
See also: [Collection Store](./collection-store.md) | [List Query Store](./list-query-store.md) | [Persistent Storage](./persistent-storage.md)
|
|
6
|
+
|
|
7
|
+
## What is limited
|
|
8
|
+
|
|
9
|
+
Cache limits only affect live in-memory store state.
|
|
10
|
+
|
|
11
|
+
- `CollectionStore` limits cached item entries with `maxItems`.
|
|
12
|
+
- `ListQueryStore` limits cached item entries with `maxItems` and cached query entries with `maxQueries`.
|
|
13
|
+
- Persistent storage has separate byte and query-size budgets documented in [Persistent Storage](./persistent-storage.md#cache-retention-controls).
|
|
14
|
+
|
|
15
|
+
The defaults are:
|
|
16
|
+
|
|
17
|
+
| Store | Limit | Default |
|
|
18
|
+
| ---------------- | ------------ | ------- |
|
|
19
|
+
| Collection Store | `maxItems` | `5000` |
|
|
20
|
+
| List Query Store | `maxItems` | `5000` |
|
|
21
|
+
| List Query Store | `maxQueries` | `1000` |
|
|
22
|
+
|
|
23
|
+
## Eviction model
|
|
24
|
+
|
|
25
|
+
TSDF evicts inactive entries in least-recently-used order. Hook reads, explicit fetches, and local item/query access keep entries fresh.
|
|
26
|
+
|
|
27
|
+
Entries are protected while they are actively mounted or doing work:
|
|
28
|
+
|
|
29
|
+
- mounted hook items and queries
|
|
30
|
+
- loading, refetching, or loading-more entries
|
|
31
|
+
- entries with an in-flight fetch
|
|
32
|
+
- entries with an in-flight mutation
|
|
33
|
+
|
|
34
|
+
Eviction is scheduled after state changes that can push the store over its configured limits. If every over-limit entry is protected, TSDF keeps the protected entries until they become inactive, then enforces the limit again.
|
|
35
|
+
|
|
36
|
+
## Collection store behavior
|
|
37
|
+
|
|
38
|
+
`CollectionStore` evicts inactive item entries when `maxItems` is exceeded.
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const productStore = createCollectionStore<Product, string>({
|
|
42
|
+
id: 'collection-products',
|
|
43
|
+
storeManager,
|
|
44
|
+
fetchFn: (productId, signal) => api.getProduct(productId, signal),
|
|
45
|
+
maxItems: 1000,
|
|
46
|
+
onStateCleanup: ({ reason, itemKeys, payloads }) => {
|
|
47
|
+
console.log(reason, itemKeys, payloads);
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
When items are evicted, TSDF also cleans their per-item scheduler and invalidation metadata. A later hook or fetch for the same payload behaves like a cold read unless persistent storage can hydrate it.
|
|
53
|
+
|
|
54
|
+
## List query store behavior
|
|
55
|
+
|
|
56
|
+
`ListQueryStore` has two related limits:
|
|
57
|
+
|
|
58
|
+
- `maxQueries` evicts inactive query entries in least-recently-used order.
|
|
59
|
+
- `maxItems` limits the shared item cache used by both list queries and standalone item hooks.
|
|
60
|
+
|
|
61
|
+
When item pressure is caused by items referenced by old queries, TSDF may evict whole inactive queries first. This avoids keeping a cached query whose item list is only partially available. After query eviction, orphan items that are no longer referenced by any query can be removed.
|
|
62
|
+
|
|
63
|
+
Standalone item entries can also be evicted directly when they are inactive and not referenced by any cached query.
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const taskStore = createListQueryStore<Task, TaskFilter, string>({
|
|
67
|
+
id: 'list-query-tasks',
|
|
68
|
+
storeManager,
|
|
69
|
+
fetchListFn: (filter, size, { signal }) => api.getTasks(filter, size, signal),
|
|
70
|
+
fetchItemFn: (taskId, { signal }) => api.getTask(taskId, signal),
|
|
71
|
+
maxItems: 2000,
|
|
72
|
+
maxQueries: 250,
|
|
73
|
+
onStateCleanup: ({ reason, itemPayloads, queryPayloads }) => {
|
|
74
|
+
console.log(reason, { itemPayloads, queryPayloads });
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Cleanup callbacks
|
|
80
|
+
|
|
81
|
+
Use `onStateCleanup` when app-level resources are keyed to cached TSDF state and should be released after eviction.
|
|
82
|
+
|
|
83
|
+
`CollectionStore` receives:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
type CollectionStateCleanup<ItemPayload> = {
|
|
87
|
+
reason: 'cacheLimitEviction';
|
|
88
|
+
itemKeys: string[];
|
|
89
|
+
payloads: ItemPayload[];
|
|
90
|
+
};
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
`ListQueryStore` receives:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
type ListQueryStateCleanup<QueryPayload, ItemPayload> = {
|
|
97
|
+
reason: 'cacheLimitEviction';
|
|
98
|
+
itemKeys: string[];
|
|
99
|
+
itemPayloads: ItemPayload[];
|
|
100
|
+
queryKeys: string[];
|
|
101
|
+
queryPayloads: QueryPayload[];
|
|
102
|
+
};
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
The callback is notification-only. The affected entries have already been removed from in-memory state by the time it runs.
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# Collection Store
|
|
2
|
+
|
|
3
|
+
A store for managing a key-value collection of independently fetched items. Each item is identified by a payload and has its own fetch lifecycle, loading state, and error handling.
|
|
4
|
+
|
|
5
|
+
See also: [Hooks](./hooks.md) | [Mutations](./mutations.md) | [Invalidation](./invalidation.md) | [Batch Fetching](./batch-fetching.md) | [Cache Limits](./cache-limits.md) | [Persistent Storage](./persistent-storage.md) | [Offline](./offline.md)
|
|
6
|
+
|
|
7
|
+
## Creating a Collection Store
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { createCollectionStore, createStoreManager } from 'tsdf';
|
|
11
|
+
|
|
12
|
+
type Product = { id: string; name: string; price: number };
|
|
13
|
+
const storeManager = createStoreManager({
|
|
14
|
+
getSessionKey: () =>
|
|
15
|
+
authState.userId ? `tenant:${authState.tenantId}` : false,
|
|
16
|
+
errorNormalizer: normalizeError,
|
|
17
|
+
lowPriorityThrottleMs: 5,
|
|
18
|
+
baseCoalescingWindowMs: 10,
|
|
19
|
+
blockWindowClose: null,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const productStore = createCollectionStore<Product, string>({
|
|
23
|
+
id: 'collection-products',
|
|
24
|
+
storeManager,
|
|
25
|
+
fetchFn: (productId, signal) => api.getProduct(productId, signal),
|
|
26
|
+
});
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Options
|
|
30
|
+
|
|
31
|
+
| Option | Type | Required | Description |
|
|
32
|
+
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------- |
|
|
33
|
+
| `id` | `string` | Yes | Stable logical store id for [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? }) => void` | No | Global mutation error handler |
|
|
53
|
+
|
|
54
|
+
## Item State Shape
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
type TSFDCollectionItem<ItemState, ItemPayload> = {
|
|
58
|
+
data: ItemState | null;
|
|
59
|
+
error: StoreError | null;
|
|
60
|
+
status: 'loading' | 'error' | 'refetching' | 'success';
|
|
61
|
+
payload: ItemPayload;
|
|
62
|
+
refetchOnMount:
|
|
63
|
+
| false
|
|
64
|
+
| 'lowPriority'
|
|
65
|
+
| 'mediumPriority'
|
|
66
|
+
| 'realtimeUpdate'
|
|
67
|
+
| 'highPriority';
|
|
68
|
+
wasLoaded: boolean;
|
|
69
|
+
};
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The overall store state is `Record<string, TSFDCollectionItem | null>` where keys are derived from payloads.
|
|
73
|
+
|
|
74
|
+
- A `null` value means the item was deleted via `deleteItemState`
|
|
75
|
+
- An `undefined` value (key not present) means the item was never fetched
|
|
76
|
+
|
|
77
|
+
## API
|
|
78
|
+
|
|
79
|
+
### Hooks
|
|
80
|
+
|
|
81
|
+
| Hook | Description | Details |
|
|
82
|
+
| ---------------------------------------- | ------------------------------------- | ------------------------------------------------------------- |
|
|
83
|
+
| `useItem(payload, options?)` | Fetch and subscribe to a single item | See [Hooks - useItem](./hooks.md#useitem) |
|
|
84
|
+
| `useMultipleItems(items, options?)` | Fetch and subscribe to multiple items | See [Hooks - useMultipleItems](./hooks.md#usemultipleitems) |
|
|
85
|
+
| `useListItemIsLoading(payload, options)` | Detect if a sub-item is loading | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
|
|
86
|
+
| `useListItemIsDeleted(payload, options)` | Detect if a sub-item was deleted | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
|
|
87
|
+
| `useListItem(payload, options)` | Combined loading + deletion detection | See [Hooks - useListItem Hooks](./hooks.md#uselistitem-hooks) |
|
|
88
|
+
|
|
89
|
+
### Methods
|
|
90
|
+
|
|
91
|
+
| Method | Signature | Description |
|
|
92
|
+
| ------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
93
|
+
| `scheduleFetch` | `(fetchType, payload(s), options?) => ScheduleFetchResults` | Schedule fetch for one or more items |
|
|
94
|
+
| `awaitFetch` | `(params, options?) => Promise<{ data, error }>` | Await fetch with optional `timeoutMs` |
|
|
95
|
+
| `getItemFromStateOrFetch` | `(params, options?) => Promise<Result<ItemState, StoreFetchError>>` | Return loaded item data or fetch it if missing |
|
|
96
|
+
| `preloadItemFromStorage` | `(params) => Promise<PersistentStoragePreloadResult<ItemPayload>[]>` | Preload cached item payloads from async storage (OPFS) |
|
|
97
|
+
| `getItemKey` | `(params) => string` | Get the composite key for a payload |
|
|
98
|
+
| `getItemState` | `(params) => CollectionItem` | Get item state (single, array, or filter function) |
|
|
99
|
+
| `invalidateItem` | `(payload(s), priority?) => void` | See [Invalidation](./invalidation.md) |
|
|
100
|
+
| `updateItemState` | `(params, produceFn, options?) => boolean` | Immer-based state update |
|
|
101
|
+
| `addItemToState` | `(payload, data) => void` | Add a new item to the store |
|
|
102
|
+
| `deleteItemState` | `(params) => void` | Delete item(s) and cleanup scheduler resources |
|
|
103
|
+
| `startMutation` | `(params) => () => void` | Start mutation lock. See [Mutations](./mutations.md) |
|
|
104
|
+
| `performMutation` | `(payload, options) => Promise<Result<T>>` | Full mutation lifecycle. See [Mutations](./mutations.md) |
|
|
105
|
+
| `reset` | `() => void` | Reset store and all schedulers |
|
|
106
|
+
| `dispose` | `() => void` | Release listeners and store-manager registration |
|
|
107
|
+
| `onTransportReconnect` | `() => void` | Store-level reconnect hook. Prefer `storeManager.onTransportReconnect()` for shared transports. See [Real-Time Updates](./real-time-updates.md) |
|
|
108
|
+
|
|
109
|
+
### Offline Methods
|
|
110
|
+
|
|
111
|
+
| Method | Description |
|
|
112
|
+
| ----------------------------------------------------- | ----------------------------------------------------------------- |
|
|
113
|
+
| `getOfflineEntities()` / `useOfflineEntities()` | Read offline entities scoped to this store |
|
|
114
|
+
| `getOfflineResolutions()` / `useOfflineResolutions()` | Read manual conflict/retry resolutions scoped to this store |
|
|
115
|
+
| `parseOfflineResolutionConflict(resolution)` | Narrow a persisted resolution to this store's operation types |
|
|
116
|
+
| `resolveOfflineResolution(id, operation, action)` | Resolve, retry, discard, requeue, or commit an offline resolution |
|
|
117
|
+
|
|
118
|
+
### Payload Overloads
|
|
119
|
+
|
|
120
|
+
Many methods accept payloads in multiple forms:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
// Single item
|
|
124
|
+
store.invalidateItem('product-1');
|
|
125
|
+
|
|
126
|
+
// Array of items
|
|
127
|
+
store.invalidateItem(['product-1', 'product-2']);
|
|
128
|
+
|
|
129
|
+
// Filter function
|
|
130
|
+
store.invalidateItem((payload, data) => data?.category === 'electronics');
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
This applies to: `invalidateItem`, `getItemState`, `updateItemState`, `deleteItemState`, `startMutation`, `scheduleFetch`.
|
|
134
|
+
|
|
135
|
+
## Usage Example
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
function ProductCard({ productId }: { productId: string }) {
|
|
139
|
+
const { data, isLoading, error } = productStore.useItem(productId);
|
|
140
|
+
|
|
141
|
+
if (isLoading) return <Skeleton />;
|
|
142
|
+
if (error) return <Error error={error} />;
|
|
143
|
+
|
|
144
|
+
return (
|
|
145
|
+
<div>
|
|
146
|
+
{data?.name} - ${data?.price}
|
|
147
|
+
</div>
|
|
148
|
+
);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Disable fetching with falsy payload
|
|
152
|
+
function MaybeProduct({ productId }: { productId: string | null }) {
|
|
153
|
+
const { data, status } = productStore.useItem(productId); // disabled when null
|
|
154
|
+
// ...
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Update item state locally
|
|
158
|
+
productStore.updateItemState('product-1', (draft) => {
|
|
159
|
+
draft.price = 29.99;
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
// Add a new item
|
|
163
|
+
productStore.addItemToState('product-new', {
|
|
164
|
+
id: 'product-new',
|
|
165
|
+
name: 'New',
|
|
166
|
+
price: 0,
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
// Delete an item
|
|
170
|
+
productStore.deleteItemState('product-old');
|
|
171
|
+
```
|