tsdf 16.0.2 → 17.0.0-alpha.1

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.
@@ -0,0 +1,156 @@
1
+ # Real-Time Updates
2
+
3
+ TSDF has built-in support for real-time data sources like WebSockets or Server-Sent Events. When enabled, stores adjust their fetch behavior to work with push-based data.
4
+
5
+ ## Enabling Real-Time Mode
6
+
7
+ ```ts
8
+ const storeManager = createStoreManager({
9
+ getSessionKey: () => currentTenantId ?? false,
10
+ errorNormalizer: normalizeError,
11
+ });
12
+
13
+ const store = createDocumentStore<Data>({
14
+ id: 'document-data',
15
+ storeManager,
16
+ usesRealTimeUpdates: true,
17
+ dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
18
+ if (windowIsNotFocused) return lastFetchDuration * 10;
19
+ return lastFetchDuration * 2;
20
+ },
21
+ // ...other options
22
+ });
23
+ ```
24
+
25
+ ## Behavior Changes
26
+
27
+ When `usesRealTimeUpdates: true`:
28
+
29
+ | Behavior | Change |
30
+ | --------------------------- | -------------------------------------------------------------- |
31
+ | `disableRefetchOnMount` | Defaults to `true` globally (data comes via push, not polling) |
32
+ | `revalidateOnWindowFocus` | Disabled (real-time transport handles freshness) |
33
+ | `realtimeUpdate` fetch type | Enabled for use with the scheduler |
34
+
35
+ ## Pushing Updates
36
+
37
+ When your real-time transport receives new data, update the store directly:
38
+
39
+ ```ts
40
+ // Document Store
41
+ websocket.on('user-updated', (newData) => {
42
+ store.updateState((draft) => {
43
+ Object.assign(draft, newData);
44
+ });
45
+ });
46
+
47
+ // Collection Store
48
+ websocket.on('product-updated', ({ productId, data }) => {
49
+ store.updateItemState(productId, (draft) => {
50
+ Object.assign(draft, data);
51
+ });
52
+ });
53
+
54
+ // List Query Store
55
+ websocket.on('task-updated', ({ taskId, data }) => {
56
+ store.updateItemState(taskId, (draft) => {
57
+ Object.assign(draft, data);
58
+ });
59
+ });
60
+ ```
61
+
62
+ If the pushed data is partial, you can invalidate instead:
63
+
64
+ ```ts
65
+ websocket.on('task-changed', ({ taskId }) => {
66
+ // Collection Store
67
+ store.invalidateItem(taskId, 'realtimeUpdate');
68
+
69
+ // List Query Store
70
+ store.invalidateQueryAndItems({
71
+ itemPayload: taskId,
72
+ queryPayload: () => true,
73
+ type: 'realtimeUpdate',
74
+ });
75
+ });
76
+ ```
77
+
78
+ ## Adaptive Throttling
79
+
80
+ The `dynamicRealtimeThrottleMs` function controls how often real-time invalidations trigger actual fetches. It receives the duration of the last fetch and whether the window is focused:
81
+
82
+ ```ts
83
+ dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
84
+ // If fetch took 200ms, wait at least 400ms before the next one
85
+ // If window is not focused, wait 10x longer
86
+ if (windowIsNotFocused) return lastFetchDuration * 10;
87
+ return lastFetchDuration * 2;
88
+ };
89
+ ```
90
+
91
+ This prevents the UI from being overwhelmed by rapid updates while keeping data fresh.
92
+
93
+ ## Transport Reconnection
94
+
95
+ When your WebSocket or SSE connection drops and reconnects, events may have been missed. Call `onTransportReconnect()` to revalidate:
96
+
97
+ ```ts
98
+ websocket.on('reconnect', () => {
99
+ store.onTransportReconnect();
100
+ });
101
+ ```
102
+
103
+ Behavior:
104
+
105
+ - If the window is **focused**: all data is invalidated immediately with `realtimeUpdate` priority
106
+ - If the window is **not focused**: invalidation is deferred until the window regains focus
107
+ - Multiple reconnect calls while unfocused are coalesced (only one invalidation fires on focus)
108
+ - This is a no-op when `usesRealTimeUpdates` is `false`
109
+
110
+ ## Pattern: WebSocket Integration
111
+
112
+ ```ts
113
+ const storeManager = createStoreManager({
114
+ getSessionKey: () => currentTenantId ?? false,
115
+ errorNormalizer: normalizeError,
116
+ });
117
+
118
+ const taskStore = createListQueryStore<Task, TaskFilter, string>({
119
+ id: 'tasks',
120
+ storeManager,
121
+ fetchListFn: (filter, size, { signal }) => api.getTasks(filter, size, signal),
122
+ fetchItemFn: (taskId, { signal }) => api.getTask(taskId, signal),
123
+ usesRealTimeUpdates: true,
124
+ dynamicRealtimeThrottleMs: ({ lastFetchDuration, windowIsNotFocused }) => {
125
+ if (windowIsNotFocused) return 30_000;
126
+ return Math.max(lastFetchDuration * 2, 1000);
127
+ },
128
+ // ...other options
129
+ });
130
+
131
+ // Connect WebSocket
132
+ const ws = connectWebSocket('/tasks');
133
+
134
+ ws.on('task:created', ({ task, taskId }) => {
135
+ taskStore.addItemToState(taskId, task, {
136
+ addItemToQueries: {
137
+ queries: (query) => query.projectId === task.projectId,
138
+ appendTo: 'start',
139
+ },
140
+ });
141
+ });
142
+
143
+ ws.on('task:updated', ({ taskId, changes }) => {
144
+ taskStore.updateItemState(taskId, (draft) => {
145
+ Object.assign(draft, changes);
146
+ });
147
+ });
148
+
149
+ ws.on('task:deleted', ({ taskId }) => {
150
+ taskStore.deleteItemState(taskId);
151
+ });
152
+
153
+ ws.on('reconnect', () => {
154
+ taskStore.onTransportReconnect();
155
+ });
156
+ ```
@@ -0,0 +1,169 @@
1
+ # Shared Types & Utilities
2
+
3
+ Common types and utilities used across all TSDF store types.
4
+
5
+ ## StoreError
6
+
7
+ The normalized error type used across all stores. Your `errorNormalizer` function converts raw exceptions into this shape:
8
+
9
+ ```ts
10
+ type StoreError = {
11
+ code: number;
12
+ id: string;
13
+ message: string;
14
+ path?: string;
15
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
16
+ };
17
+ ```
18
+
19
+ ## StoreFetchError
20
+
21
+ An `Error` subclass returned by `awaitFetch` methods. Contains the same fields as `StoreError` plus a `type` indicating why the fetch failed:
22
+
23
+ - `'fetch'` — the fetch function threw an error
24
+ - `'timeout'` — the fetch exceeded the specified `timeoutMs`
25
+ - `'aborted'` — the fetch was aborted (e.g., due to a mutation starting)
26
+
27
+ ## StoreMutationError
28
+
29
+ An `Error` subclass returned by `performMutation` when the mutation fails.
30
+ It contains the normalized `StoreError` fields plus:
31
+
32
+ - `kind: 'error'`
33
+ - `cause` — the original thrown value, preserved via `Error.cause`
34
+
35
+ ## MutationSkipped
36
+
37
+ A sentinel returned by `performMutation` when the mutation is intentionally not
38
+ run, for example because:
39
+
40
+ - `optimisticUpdate` returned `false`
41
+ - a debounced mutation call was superseded by a newer call
42
+
43
+ Shape:
44
+
45
+ ```ts
46
+ type MutationSkipped = { kind: 'skipped' };
47
+ ```
48
+
49
+ ## Fetch Priorities
50
+
51
+ Priority levels for [fetch scheduling](./fetch-scheduling.md). Higher priority fetches override lower ones:
52
+
53
+ - `lowPriority` (0) — Default hook mount fetches
54
+ - `mediumPriority` (1) — Background refetches
55
+ - `realtimeUpdate` (2) — Push-based updates
56
+ - `highPriority` (3) — Explicit invalidation, user actions
57
+
58
+ ## ValidPayload
59
+
60
+ Payloads that identify items or queries must be one of:
61
+
62
+ - `number` — e.g., `42`
63
+ - `string` — e.g., `'user-123'`
64
+ - `Record<string, unknown>` — e.g., `{ projectId: 'proj-1', status: 'active' }`
65
+
66
+ Payloads are converted to composite keys internally for state storage. Object payloads are serialized deterministically (key order doesn't matter).
67
+
68
+ ## PayloadDebounce
69
+
70
+ Configuration for debouncing automatic fetches triggered by rapid payload
71
+ changes in payload-based hooks.
72
+
73
+ Supported by:
74
+
75
+ - `useItem`
76
+ - `useListQuery`
77
+ - `useMultipleItems`
78
+ - `useMultipleListQueries`
79
+
80
+ Shape:
81
+
82
+ ```ts
83
+ type PayloadDebounce = { ms: number; maxWait?: number; leading?: boolean };
84
+ ```
85
+
86
+ Fields:
87
+
88
+ - `ms` — debounce window in milliseconds
89
+ - `maxWait` — optional upper bound for how long a burst may stay deferred
90
+ - `leading` — allows the first payload in a burst to fetch immediately
91
+
92
+ Important behavior:
93
+
94
+ - The hook still reads from state using the latest payload immediately
95
+ - Only the automatic fetch side is delayed
96
+ - If cached data already exists for the latest payload, the hook can still
97
+ return it immediately while the fetch is deferred
98
+ - `useItem` and `useListQuery` do not support combining `debouncePayload` with
99
+ `ensureIsLoaded`
100
+
101
+ Example:
102
+
103
+ ```tsx
104
+ const result = store.useListQuery(
105
+ { search, status: 'active' },
106
+ { debouncePayload: { ms: 300, leading: true, maxWait: 1200 } },
107
+ );
108
+ ```
109
+
110
+ See [React Hooks](./hooks.md#debouncepayload) for usage patterns.
111
+
112
+ ## IsOffScreenContext
113
+
114
+ A React context that disables all TSDF hooks in a subtree when set to `true`. Useful for tabs, modals, or off-screen content that shouldn't trigger fetches.
115
+
116
+ ```tsx
117
+ import { IsOffScreenContext } from 'tsdf';
118
+
119
+ function TabPanel({ isActive, children }) {
120
+ return (
121
+ <IsOffScreenContext.Provider value={!isActive}>
122
+ {children}
123
+ </IsOffScreenContext.Provider>
124
+ );
125
+ }
126
+ ```
127
+
128
+ When `IsOffScreenContext` is `true`:
129
+
130
+ - Hooks don't trigger fetches
131
+ - Hooks don't respond to invalidation events
132
+ - Individual hooks can override via their `isOffScreen` prop
133
+
134
+ ## fetchTypePriority
135
+
136
+ Numeric mapping of fetch priorities for comparison:
137
+
138
+ ```ts
139
+ import { fetchTypePriority } from 'tsdf';
140
+
141
+ fetchTypePriority.lowPriority; // 0
142
+ fetchTypePriority.mediumPriority; // 1
143
+ fetchTypePriority.realtimeUpdate; // 2
144
+ fetchTypePriority.highPriority; // 3
145
+ ```
146
+
147
+ ## BlockWindowCloseHandler
148
+
149
+ A function that blocks the browser window from closing during mutations. Returns an object with an `unblock` method:
150
+
151
+ ```ts
152
+ const blockWindowClose = () => {
153
+ const handler = (e: BeforeUnloadEvent) => {
154
+ e.preventDefault();
155
+ };
156
+ window.addEventListener('beforeunload', handler);
157
+ return { unblock: () => window.removeEventListener('beforeunload', handler) };
158
+ };
159
+ ```
160
+
161
+ Pass `null` to `createStoreManager({ blockWindowClose })` to disable this behavior.
162
+
163
+ ## MutationDebounce
164
+
165
+ Configuration for debouncing [mutations](./mutations.md):
166
+
167
+ - `context` — Debounce key. Mutations with the same context are debounced together
168
+ - `payload` — The latest payload replaces previous ones during the debounce window
169
+ - `ms` — Milliseconds of inactivity before the mutation executes
@@ -0,0 +1,118 @@
1
+ # Store Manager
2
+
3
+ `createStoreManager(...)` creates the shared session boundary for TSDF stores. Every store requires one manager so data can be scoped by tenant/account, errors can be normalized consistently, and global store/offline APIs can coordinate across store instances.
4
+
5
+ See also: [Persistent Storage](./persistent-storage.md) | [Offline](./offline.md) | [Browser Tabs Sync](./browser-tabs-sync.md)
6
+
7
+ ## Creating A Manager
8
+
9
+ ```ts
10
+ import { createStoreManager } from 'tsdf';
11
+
12
+ const storeManager = createStoreManager({
13
+ getSessionKey: () => currentTenantId ?? false,
14
+ errorNormalizer: (error) => ({
15
+ code: 500,
16
+ id: 'unknown-error',
17
+ message: error.message,
18
+ }),
19
+ lowPriorityThrottleMs: 5,
20
+ baseCoalescingWindowMs: 10,
21
+ blockWindowClose: null,
22
+ onPersistentStorageError: (error) => {
23
+ console.error('TSDF persistence failed', error);
24
+ },
25
+ });
26
+ ```
27
+
28
+ Options:
29
+
30
+ | Option | Required | Description |
31
+ | -------------------------- | -------- | ---------------------------------------------------------------------------------------------- |
32
+ | `getSessionKey` | Yes | Returns the active tenant/account key. Return `false` while no session is ready. |
33
+ | `errorNormalizer` | Yes | Converts thrown `Error` values into TSDF's shared `StoreError` shape. |
34
+ | `lowPriorityThrottleMs` | No | Default minimum interval between low-priority fetches for attached stores. Defaults to `5`. |
35
+ | `baseCoalescingWindowMs` | No | Default window to group fetch requests for attached stores. Defaults to `10`. |
36
+ | `blockWindowClose` | No | Shared window-close blocker for mutations in attached stores. Defaults to `null`. |
37
+ | `onPersistentStorageError` | No | Global fallback for persistent storage failures when a store does not provide its own handler. |
38
+ | `offlineSession` | No | Shared offline config used by stores with `persistentStorage.offline`. |
39
+
40
+ The session key is used by browser-tab sync, persistent storage, and offline state. Stores with the same `id` but different session keys are isolated.
41
+
42
+ Stores inherit the manager's `lowPriorityThrottleMs` and `baseCoalescingWindowMs` unless they provide their own store-level overrides. `blockWindowClose` is manager-only so window-close mutation protection is consistent across attached stores.
43
+
44
+ ## Store Registry
45
+
46
+ The manager tracks attached stores:
47
+
48
+ ```ts
49
+ storeManager.getAllStoreIds();
50
+ storeManager.resetAll(['document-current-user']);
51
+ ```
52
+
53
+ - `getAllStoreIds()` returns registered logical store ids.
54
+ - `resetAll(ignoreStores)` resets all registered stores except the ignored ids.
55
+
56
+ Call each store's `dispose()` when the store instance is permanently discarded so it can unregister listeners and manager state.
57
+
58
+ ## Offline Session
59
+
60
+ Pass `offlineSession` when stores need offline queueing or session-level offline reads:
61
+
62
+ ```ts
63
+ const storeManager = createStoreManager({
64
+ getSessionKey: () => currentTenantId ?? false,
65
+ errorNormalizer: normalizeError,
66
+ offlineSession: {
67
+ network: { enabled: true },
68
+ mutationQueueing: { network: 'allow', outage: 'allow' },
69
+ },
70
+ });
71
+ ```
72
+
73
+ Manager offline methods are safe to call even when no offline session is configured. In that case they return empty/default state, and upload helpers return `Result.err(...)` where applicable.
74
+
75
+ ## Offline Status APIs
76
+
77
+ Read session-wide offline state:
78
+
79
+ ```tsx
80
+ const status = storeManager.useOfflineStatus();
81
+ const entities = storeManager.useOfflineEntities();
82
+ const resolutions = storeManager.useOfflineResolutions();
83
+ ```
84
+
85
+ Synchronous equivalents:
86
+
87
+ - `getOfflineConfig()`
88
+ - `getOfflineRuntimeConfig()`
89
+ - `getOfflineStatus()`
90
+ - `getOfflineEntities()`
91
+ - `getOfflineResolutions()`
92
+ - `getOfflineUploads()`
93
+
94
+ Runtime controls:
95
+
96
+ - `setOfflineRuntimeConfig(update)` returns a `Result<void, Error>`
97
+ - `resetOfflineRuntimeConfig()` restores the static `offlineSession` controls
98
+
99
+ ## Upload APIs
100
+
101
+ When `offlineSession.uploads` is configured, the manager also owns session-scoped upload storage and resolution:
102
+
103
+ ```ts
104
+ await storeManager.saveOfflineUpload({ id: 'avatar', file });
105
+ const resolved = await storeManager.resolveOfflineUpload('avatar');
106
+ ```
107
+
108
+ Upload methods:
109
+
110
+ - `saveOfflineUpload({ id, file })`
111
+ - `replaceOfflineUpload({ id, file })`
112
+ - `loadOfflineUpload(id)`
113
+ - `deleteOfflineUpload(id)`
114
+ - `resolveOfflineUpload(id)`
115
+ - `resolveOfflineUploads(ids)`
116
+ - `useOfflineUploads()`
117
+
118
+ Most upload methods return `Result` objects so UI can branch on `result.ok` without catching thrown errors.
package/package.json CHANGED
@@ -1,75 +1,92 @@
1
1
  {
2
2
  "name": "tsdf",
3
- "version": "16.0.2",
3
+ "version": "17.0.0-alpha.1",
4
4
  "description": "A data fetching solution based on t-state",
5
5
  "license": "MIT",
6
6
  "author": "Lucas Santos",
7
7
  "repository": "github:lucasols/tsdf",
8
8
  "type": "module",
9
- "main": "./dist/main.cjs",
10
- "module": "./dist/main.js",
9
+ "main": "./dist/main.js",
11
10
  "types": "./dist/main.d.ts",
12
11
  "exports": {
13
12
  ".": {
13
+ "types": "./dist/main.d.ts",
14
14
  "import": "./dist/main.js",
15
- "require": "./dist/main.cjs"
15
+ "default": "./dist/main.js"
16
16
  }
17
17
  },
18
18
  "files": [
19
- "dist"
19
+ "dist",
20
+ "docs"
20
21
  ],
21
22
  "sideEffects": false,
22
23
  "engines": {
23
24
  "node": ">=16.0.0"
24
25
  },
25
26
  "devDependencies": {
26
- "@lucasols/eslint-plugin-extended-lint": "^1.4.0",
27
- "@testing-library/jest-dom": "^6.1.3",
28
- "@testing-library/react": "^14.0.0",
29
- "@types/node": "^20.8.4",
30
- "@types/react": "^18.2.28",
31
- "@types/react-dom": "^18.2.13",
32
- "@typescript-eslint/eslint-plugin": "^6.7.5",
33
- "@typescript-eslint/parser": "^6.7.5",
34
- "@vitest/ui": "1.0.4",
35
- "eslint": "^8.51.0",
36
- "eslint-plugin-local-rules": "^2.0.0",
37
- "eslint-plugin-react-hooks": "^4.6.0",
38
- "eslint-plugin-vitest": "^0.3.15",
39
- "happy-dom": "^12.9.1",
40
- "jsdom": "^22.1.0",
41
- "prettier": "^3.0.3",
42
- "pretty-format": "^29.7.0",
43
- "react": "^18.2.0",
44
- "react-dom": "^18.2.0",
45
- "tiny-glob": "^0.2.9",
46
- "tsm": "^2.3.0",
47
- "tsup": "^7.2.0",
48
- "typescript": "^5.4.2",
49
- "vite": "^5.1.5",
50
- "vitest": "^1.3.1"
27
+ "@ls-stack/eslint-cfg": "^0.10.0",
28
+ "@playwright/test": "^1.58.2",
29
+ "@testing-library/react": "^16.3.2",
30
+ "@types/node": "^25.0.3",
31
+ "@types/react": "^18.3.27",
32
+ "@types/react-dom": "^18.3.7",
33
+ "@typescript/native-preview": "7.0.0-dev.20260302.1",
34
+ "@vitest/coverage-v8": "4.1.2",
35
+ "@vitest/ui": "^4.1.0",
36
+ "eslint": "^9.39.2",
37
+ "eslint-plugin-react-hooks": "^7.0.1",
38
+ "fake-indexeddb": "^6.2.5",
39
+ "happy-dom": "^20.8.4",
40
+ "knip": "^6.4.1",
41
+ "oxfmt": "^0.40.0",
42
+ "react": "^19.2.3",
43
+ "react-dom": "^19.2.3",
44
+ "simple-git-hooks": "^2.13.1",
45
+ "tsdown": "^0.21.10",
46
+ "typescript": "^5.9.3",
47
+ "vite": "^8.0.0",
48
+ "vitest": "^4.1.0",
49
+ "zod": "^4.3.6"
51
50
  },
52
51
  "dependencies": {
53
- "evtmitter": "^0.3.3",
54
- "immer": "^10.0.3",
52
+ "@evtmitter/react": "^0.1.0",
53
+ "@ls-stack/browser-utils": "^0.3.0",
54
+ "@ls-stack/extended-lint": "^0.89.3",
55
+ "@ls-stack/react-utils": "^0.12.1",
56
+ "@ls-stack/utils": "^3.76.0",
57
+ "@standard-schema/spec": "^1.1.0",
58
+ "evtmitter": "^1.0.2",
59
+ "immer": "^11.1.3",
55
60
  "klona": "^2.0.6",
56
- "t-state": "^9.0.0"
61
+ "runcheck": "^1.15.0",
62
+ "t-result": "^0.6.1",
63
+ "t-state": "^9.8.2"
64
+ },
65
+ "simple-git-hooks": {
66
+ "pre-commit": "node --no-warnings scripts/preCommitHook.ts"
57
67
  },
58
68
  "peerDependencies": {
59
- "react": "^18.0.0",
60
- "react-dom": "^18.0.0"
69
+ "react": "^18.0.0||^19.0.0",
70
+ "react-dom": "^18.0.0||^19.0.0"
61
71
  },
62
72
  "scripts": {
63
- "test": "vitest --ui --mode development",
64
- "test:changed": "vitest --changed --ui --mode development",
65
- "lint": "pnpm tsc && pnpm eslint && pnpm format",
66
- "eslint": "CI=true eslint --color --ext .jsx,.js,.ts,.tsx src/ test/",
67
- "format": "prettier --write src/**/*.ts",
68
- "tsc": "tsc -p tsconfig.prod.json",
69
- "tsc:watch": "tsc -p tsconfig.prod.json --watch",
70
- "test:run": "vitest run",
71
- "build": "pnpm test:run && pnpm lint && pnpm build:no-test",
72
- "build:no-test": "tsup --dts",
73
- "pre-publish": "./scripts/check-if-is-sync.sh && pnpm build"
73
+ "knip": "knip",
74
+ "test": "vitest --run",
75
+ "test:ui": "vitest --ui",
76
+ "test:watch": "vitest --watch",
77
+ "test:changed": "vitest --changed",
78
+ "test:playwright": "playwright test",
79
+ "test:coverage": "vitest run --coverage",
80
+ "test:all": "vitest --run && playwright test",
81
+ "lint": "pnpm tsc && pnpm tsc:isolated && pnpm eslint",
82
+ "eslint": "eslint src/ tests/ --fix",
83
+ "format": "oxfmt src/ tests/",
84
+ "tsc": "tsgo -p tsconfig.prod.json",
85
+ "tsc:isolated": "tsgo -p tsconfig.isolated.json",
86
+ "build": "pnpm lint && pnpm test:all && pnpm build:no-test",
87
+ "build:no-test": "tsdown",
88
+ "pre-publish": "pnpm build",
89
+ "hooks:install": "simple-git-hooks",
90
+ "hooks:uninstall": "git config --unset core.hooksPath || true && rm -rf .git/hooks/pre-commit"
74
91
  }
75
92
  }