what-core 0.14.0 → 0.15.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.
- package/LICENSE +21 -0
- package/README.md +64 -38
- package/a11y.d.ts +128 -0
- package/data.d.ts +294 -0
- package/dist/a11y.js +510 -0
- package/dist/a11y.min.js +413 -0
- package/dist/actions.js +158 -0
- package/dist/actions.min.js +112 -0
- package/dist/animation.js +481 -0
- package/dist/animation.min.js +295 -0
- package/dist/async.js +180 -0
- package/dist/async.min.js +134 -0
- package/dist/components.js +577 -0
- package/dist/components.min.js +413 -0
- package/dist/data.js +1212 -0
- package/dist/data.min.js +918 -0
- package/dist/diagnostics.js +187 -0
- package/dist/diagnostics.min.js +134 -0
- package/dist/dom.js +796 -0
- package/dist/dom.min.js +603 -0
- package/dist/entries/a11y.js +43 -0
- package/dist/entries/a11y.min.js +43 -0
- package/dist/entries/data.js +29 -0
- package/dist/entries/data.min.js +29 -0
- package/dist/entries/dom.js +45 -0
- package/dist/entries/dom.min.js +45 -0
- package/dist/entries/form.js +31 -0
- package/dist/entries/form.min.js +31 -0
- package/dist/entries/internal.js +123 -0
- package/dist/entries/internal.min.js +123 -0
- package/dist/entries/motion.js +23 -0
- package/dist/entries/motion.min.js +23 -0
- package/dist/entries/ui.js +25 -0
- package/dist/entries/ui.min.js +25 -0
- package/dist/env.js +5 -0
- package/dist/env.min.js +5 -0
- package/dist/errors.js +1518 -0
- package/dist/errors.min.js +548 -0
- package/dist/form.js +936 -0
- package/dist/form.min.js +703 -0
- package/dist/guardrails.js +84 -0
- package/dist/guardrails.min.js +55 -0
- package/dist/h.js +232 -0
- package/dist/h.min.js +171 -0
- package/dist/head.js +241 -0
- package/dist/head.min.js +207 -0
- package/dist/helpers.js +126 -0
- package/dist/helpers.min.js +98 -0
- package/dist/hooks.js +255 -0
- package/dist/hooks.min.js +153 -0
- package/dist/hot.js +215 -0
- package/dist/hot.min.js +24 -0
- package/dist/hydration-data.js +495 -0
- package/dist/hydration-data.min.js +371 -0
- package/dist/import-changes.js +273 -0
- package/dist/import-changes.min.js +272 -0
- package/dist/index.js +95 -0
- package/dist/index.min.js +95 -227
- package/dist/jsx-dev-runtime.js +10 -0
- package/dist/jsx-dev-runtime.min.js +10 -1
- package/dist/jsx-runtime.js +27 -0
- package/dist/jsx-runtime.min.js +15 -1
- package/dist/live.js +54 -0
- package/dist/live.min.js +49 -0
- package/dist/markup-rules.js +250 -0
- package/dist/markup-rules.min.js +213 -0
- package/dist/reactive.js +3334 -0
- package/dist/reactive.min.js +2033 -0
- package/dist/render.js +4746 -0
- package/dist/render.min.js +2797 -1
- package/dist/scheduler.js +225 -0
- package/dist/scheduler.min.js +162 -0
- package/dist/selector.js +11 -0
- package/dist/selector.min.js +10 -0
- package/dist/server-context.js +148 -0
- package/dist/server-context.min.js +121 -0
- package/dist/skeleton.js +342 -0
- package/dist/skeleton.min.js +310 -0
- package/dist/store.js +72 -0
- package/dist/store.min.js +50 -0
- package/dist/testing.js +720 -0
- package/dist/testing.min.js +458 -1
- package/dist/vnode-adoption.js +19 -0
- package/dist/vnode-adoption.min.js +19 -0
- package/dist/vnode-renderer.js +61 -0
- package/dist/vnode-renderer.min.js +47 -0
- package/dom.d.ts +44 -0
- package/form.d.ts +218 -0
- package/hot.d.ts +35 -0
- package/index.d.ts +421 -736
- package/internal.d.ts +284 -0
- package/jsx-runtime.d.ts +160 -137
- package/markup-rules.d.ts +83 -0
- package/motion.d.ts +156 -0
- package/package.json +117 -3
- package/render.d.ts +278 -29
- package/src/a11y.js +64 -59
- package/src/actions.js +226 -0
- package/src/animation.js +105 -57
- package/src/async.js +259 -0
- package/src/components.js +495 -144
- package/src/data.js +1410 -1159
- package/src/diagnostics.js +263 -0
- package/src/dom.js +1159 -872
- package/src/entries/a11y.js +24 -0
- package/src/entries/data.js +17 -0
- package/src/entries/dom.js +29 -0
- package/src/entries/form.js +16 -0
- package/src/entries/internal.js +63 -0
- package/src/entries/motion.js +13 -0
- package/src/entries/ui.js +13 -0
- package/src/env-development.js +12 -0
- package/src/env.js +33 -0
- package/src/errors.js +1144 -168
- package/src/form.js +723 -225
- package/src/guardrails.js +38 -126
- package/src/h.js +227 -152
- package/src/head.js +189 -19
- package/src/helpers.js +47 -75
- package/src/hooks.js +233 -248
- package/src/hot.js +316 -0
- package/src/hydration-data.js +859 -16
- package/src/import-changes.js +156 -0
- package/src/index.js +38 -188
- package/src/jsx-dev-runtime.js +7 -14
- package/src/jsx-runtime.js +25 -9
- package/src/live.js +80 -0
- package/src/markup-rules.js +387 -0
- package/src/reactive.js +4400 -862
- package/src/render.js +6502 -2570
- package/src/scheduler.js +56 -21
- package/src/selector.js +31 -0
- package/src/server-context.js +252 -22
- package/src/skeleton.js +22 -12
- package/src/store.js +17 -31
- package/src/testing.js +389 -63
- package/src/vnode-adoption.js +48 -0
- package/src/vnode-renderer.js +114 -0
- package/testing.d.ts +81 -1
- package/ui.d.ts +20 -0
- package/dist/chunk-6YOUZ6T4.min.js +0 -1
- package/dist/chunk-FN6HXME3.min.js +0 -11
- package/dist/chunk-VKZY7JPN.min.js +0 -1
- package/src/agent-context.js +0 -127
- package/src/warnings.js +0 -193
package/src/data.js
CHANGED
|
@@ -1,513 +1,1050 @@
|
|
|
1
|
-
// What Framework - Data
|
|
2
|
-
// SWR-like data fetching with caching, revalidation, and optimistic updates
|
|
3
|
-
|
|
4
|
-
import { signal, effect, batch, computed, untrack, __DEV__ } from './reactive.js';
|
|
5
|
-
import { getCurrentComponent } from './dom.js';
|
|
6
|
-
|
|
7
|
-
// --- Reactive Cache ---
|
|
8
|
-
// Each cache key maps to shared signals so all components reading the same key
|
|
9
|
-
// see updates when ANY component mutates/revalidates that key.
|
|
10
|
-
// Shared per key: data signal, error signal, isValidating signal.
|
|
11
|
-
const cacheSignals = new Map(); // key -> signal(value)
|
|
12
|
-
const errorSignals = new Map(); // key -> signal(error)
|
|
13
|
-
const validatingSignals = new Map(); // key -> signal(boolean)
|
|
14
|
-
const cacheTimestamps = new Map(); // key -> last access time (for LRU)
|
|
15
|
-
const MAX_CACHE_SIZE = 200;
|
|
16
|
-
|
|
17
|
-
// --- Query key normalization ---
|
|
18
|
-
// Array keys are joined into the same flat string space as useSWR's string keys,
|
|
19
|
-
// so `useQuery({queryKey: ['todos']})` and `useSWR('todos')` share one cache
|
|
20
|
-
// entry by design. Every cache-facing entry point must normalize identically:
|
|
21
|
-
// useQuery used to be the only one that did, so `invalidateQueries(['todos'])`
|
|
22
|
-
// looked up a raw Array object as a Map key, found nothing, and silently did
|
|
23
|
-
// nothing. The documented shape was the broken one.
|
|
1
|
+
// What Framework - Data: one query cache on async values (docs/DATA.md).
|
|
24
2
|
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
3
|
+
// Every key the app reads is one entry, and every entry is one async value in
|
|
4
|
+
// the reactive graph (reactive.js _asyncComputed): what reads it waits for it
|
|
5
|
+
// the way it waits for any async value, a transition holds what its refetch
|
|
6
|
+
// reaches, settled() waits for its fetch, and a server render serializes it in
|
|
7
|
+
// the hydration channel under its key, so the client adopts it instead of
|
|
8
|
+
// fetching. On top of the entries:
|
|
9
|
+
//
|
|
10
|
+
// query(key, fetcher) the signal-native read: an async value whose key may
|
|
11
|
+
// be reactive (suspends, holds, pending(), refresh())
|
|
12
|
+
// useQuery, useSWR, the React-ecosystem shapes (TanStack Query, SWR):
|
|
13
|
+
// useInfiniteQuery, views that never suspend, with status flags
|
|
14
|
+
// useFetch
|
|
15
|
+
// invalidateQueries, invalidatePath, prefetchQuery, setQueryData,
|
|
16
|
+
// getQueryData, clearCache the cache, whichever hook reads it
|
|
17
|
+
//
|
|
18
|
+
// An entry's fetches are flights. One flight is current; a newer one
|
|
19
|
+
// supersedes it (aborting its signal), and a flight whose result can no longer
|
|
20
|
+
// be shown (its readers all left, or clearCache() ran) is killed: its result is
|
|
21
|
+
// dropped and nothing is delivered. Readers are observers: an entry with none
|
|
22
|
+
// is not fetched, and is dropped after its gcTime.
|
|
23
|
+
|
|
24
|
+
import {
|
|
25
|
+
signal,
|
|
26
|
+
effect,
|
|
27
|
+
computed,
|
|
28
|
+
untrack,
|
|
29
|
+
onCleanup,
|
|
30
|
+
getOwner,
|
|
31
|
+
createRoot,
|
|
32
|
+
runWithOwner,
|
|
33
|
+
_detached,
|
|
34
|
+
_asyncComputed,
|
|
35
|
+
_refresh,
|
|
36
|
+
_asyncStatus,
|
|
37
|
+
_asyncError,
|
|
38
|
+
_setAsyncValue,
|
|
39
|
+
_installSeedOps,
|
|
40
|
+
_isNotReady,
|
|
41
|
+
__DEV__,
|
|
42
|
+
} from './reactive.js';
|
|
43
|
+
import { _seedFor, getResource, getResourceError, _errorFromRecord, _loadedResource } from './hydration-data.js';
|
|
44
|
+
import { getServerContext, _isServerProcess } from './server-context.js';
|
|
45
|
+
import { report } from './diagnostics.js';
|
|
46
|
+
import { _enableSuspense, isHydrating } from './render.js';
|
|
47
|
+
|
|
48
|
+
const PLAIN = 0;
|
|
49
|
+
const INFINITE = 1;
|
|
50
|
+
|
|
51
|
+
// An entry's value before anything landed, or after clearCache(): no data.
|
|
52
|
+
const IDLE = /* @__PURE__ */ Object.freeze({ toString: () => '[what] no data' });
|
|
53
|
+
|
|
54
|
+
// What the next run of an entry's node does (entry.next).
|
|
55
|
+
const FETCH = 1; // start a flight
|
|
56
|
+
const ADOPT = 2; // wait for the flight already in flight (after a hard invalidation)
|
|
57
|
+
|
|
58
|
+
const DEFAULT_GC_TIME = 5 * 60 * 1000;
|
|
59
|
+
|
|
60
|
+
function noop() {}
|
|
61
|
+
|
|
62
|
+
// Every timer here is housekeeping or polling, which is no reason to keep a
|
|
63
|
+
// Node process alive.
|
|
64
|
+
function unrefTimer(timer) {
|
|
65
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
66
|
+
return timer;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// --- Keys ---
|
|
70
|
+
// Array keys are joined into the same flat string space as string keys, so
|
|
71
|
+
// `useQuery({ queryKey: ['todos'] })`, `useSWR('todos')` and `query('todos')`
|
|
72
|
+
// are one entry, and every entry point (invalidateQueries, getQueryData, the
|
|
73
|
+
// predicate a caller writes) sees the same spelling. Segments escape ':' so
|
|
74
|
+
// ['user', 'a:b'] cannot collide with ['user', 'a', 'b'].
|
|
75
|
+
// A function in a key array (a signal, a thunk) is read as part of the key:
|
|
76
|
+
// it names the entry of its current value, and, read where the key is
|
|
77
|
+
// tracked, moves the reader to a new entry when it changes.
|
|
78
|
+
function keyParts(key) {
|
|
79
|
+
return Array.isArray(key) && key.some((part) => typeof part === 'function')
|
|
80
|
+
? key.map((part) => (typeof part === 'function' ? part() : part))
|
|
81
|
+
: key;
|
|
82
|
+
}
|
|
83
|
+
|
|
28
84
|
function normalizeQueryKey(key) {
|
|
29
|
-
|
|
85
|
+
key = keyParts(key);
|
|
86
|
+
if (!Array.isArray(key)) return String(key);
|
|
30
87
|
return key
|
|
31
88
|
.map((part) => (typeof part === 'string' ? part : JSON.stringify(part) ?? String(part)))
|
|
32
89
|
.map((part) => part.replace(/([\\:])/g, '\\$1'))
|
|
33
90
|
.join(':');
|
|
34
91
|
}
|
|
35
92
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
93
|
+
const CHANNEL = 'query:';
|
|
94
|
+
|
|
95
|
+
// --- The cache ---
|
|
96
|
+
// The client keeps one cache per page. A server render keeps one per render
|
|
97
|
+
// (a request's data must never answer another request), released with it.
|
|
98
|
+
const clientCache = [new Map(), new Map()];
|
|
99
|
+
/** @type {WeakMap<object, Map<string, any>[]>} */
|
|
100
|
+
const serverCaches = new WeakMap();
|
|
101
|
+
|
|
102
|
+
function cacheOf(kind) {
|
|
103
|
+
const ctx = getServerContext();
|
|
104
|
+
if (ctx === null) {
|
|
105
|
+
if (!_isServerProcess()) return clientCache[kind];
|
|
106
|
+
// On a server, outside every render, loader and action: no request to
|
|
107
|
+
// bind to, and a cache every request shares would hand one user's data to
|
|
108
|
+
// another. The call gets an empty cache nothing else sees.
|
|
109
|
+
if (__DEV__) report('ERR_QUERY_OUTSIDE_RENDER');
|
|
110
|
+
return new Map();
|
|
44
111
|
}
|
|
45
|
-
|
|
112
|
+
let caches = serverCaches.get(ctx);
|
|
113
|
+
if (caches === undefined) serverCaches.set(ctx, caches = [new Map(), new Map()]);
|
|
114
|
+
return caches[kind];
|
|
46
115
|
}
|
|
47
116
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
117
|
+
// Server values the page carried, taken once per key: a key read again later
|
|
118
|
+
// (after it was dropped) fetches, it does not adopt the page's old value.
|
|
119
|
+
/** @type {Set<string>} */
|
|
120
|
+
const adopted = new Set();
|
|
121
|
+
let channelOpen = true;
|
|
122
|
+
|
|
123
|
+
function hydrationSeed(hash) {
|
|
124
|
+
if (!channelOpen || adopted.has(hash)) return null;
|
|
125
|
+
const value = getResource(CHANNEL + hash);
|
|
126
|
+
if (value !== undefined) {
|
|
127
|
+
adopted.add(hash);
|
|
128
|
+
return { value, track: false };
|
|
129
|
+
}
|
|
130
|
+
const record = getResourceError(CHANNEL + hash);
|
|
131
|
+
if (record === undefined) return null;
|
|
132
|
+
adopted.add(hash);
|
|
133
|
+
return { error: _errorFromRecord(record), track: false };
|
|
51
134
|
}
|
|
52
135
|
|
|
53
|
-
function
|
|
54
|
-
|
|
55
|
-
|
|
136
|
+
function entryFor(kind, hash, key, observer) {
|
|
137
|
+
const cache = cacheOf(kind);
|
|
138
|
+
let e = cache.get(hash);
|
|
139
|
+
if (e === undefined) {
|
|
140
|
+
e = newEntry(kind, hash, key, cache, observer);
|
|
141
|
+
cache.set(hash, e);
|
|
142
|
+
}
|
|
143
|
+
return e;
|
|
56
144
|
}
|
|
57
145
|
|
|
58
|
-
function
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
146
|
+
function newEntry(kind, hash, key, cache, observer) {
|
|
147
|
+
const e = {
|
|
148
|
+
kind,
|
|
149
|
+
hash,
|
|
150
|
+
key,
|
|
151
|
+
cache,
|
|
152
|
+
/** @type {any} */ node: null,
|
|
153
|
+
dispose: noop,
|
|
154
|
+
/** @type {any} */ flight: null,
|
|
155
|
+
next: 0,
|
|
156
|
+
/** @type {any} */ error: undefined,
|
|
157
|
+
version: 0,
|
|
158
|
+
updatedAt: 0,
|
|
159
|
+
fetchedAt: 0,
|
|
160
|
+
fetches: 0,
|
|
161
|
+
/** @type {any} */ last: null,
|
|
162
|
+
hydrated: false,
|
|
163
|
+
/** @type {Set<any>} */ observers: new Set(),
|
|
164
|
+
gcTime: DEFAULT_GC_TIME,
|
|
165
|
+
/** @type {any} */ timer: null,
|
|
166
|
+
/** @type {any} */ conf: observer !== null ? observer.conf : null,
|
|
167
|
+
/** @type {any} */ src: null,
|
|
168
|
+
/** @type {any} */ by: null,
|
|
169
|
+
/** @type {any} */ op: null,
|
|
170
|
+
/** @type {Set<string> | null} */ paths: null,
|
|
171
|
+
dir: kind === INFINITE ? signal(/** @type {string | null} */ (null)) : null,
|
|
172
|
+
// Moves at every landing: query() reads it, not the node, while the entry
|
|
173
|
+
// has no data, so the engine never sees "a value being refetched" there.
|
|
174
|
+
tick: signal(0),
|
|
175
|
+
/** @type {{ promise: Promise<any>, resolve: (v: any) => void, reject: (e: any) => void } | null} */ arrival: null,
|
|
176
|
+
dropped: false,
|
|
177
|
+
};
|
|
178
|
+
const ctx = getServerContext();
|
|
179
|
+
/** @type {any} */
|
|
180
|
+
let seed;
|
|
181
|
+
if (ctx !== null) {
|
|
182
|
+
seed = _seedFor(CHANNEL + hash, false);
|
|
183
|
+
} else {
|
|
184
|
+
seed = kind === PLAIN ? hydrationSeed(hash) : null;
|
|
185
|
+
if (seed !== null) {
|
|
186
|
+
e.hydrated = true;
|
|
187
|
+
e.updatedAt = Date.now();
|
|
188
|
+
if ('error' in seed) e.error = seed.error;
|
|
189
|
+
queueMicrotask(() => { e.hydrated = false; });
|
|
190
|
+
} else if (observer !== null && observer.initialData !== undefined) {
|
|
191
|
+
const initial = typeof observer.initialData === 'function' ? observer.initialData() : observer.initialData;
|
|
192
|
+
seed = { value: initial === undefined ? IDLE : initial, track: false };
|
|
193
|
+
if (initial !== undefined) e.updatedAt = observer.initialDataUpdatedAt ?? Date.now();
|
|
194
|
+
} else {
|
|
195
|
+
seed = { value: IDLE, track: false };
|
|
196
|
+
}
|
|
71
197
|
}
|
|
198
|
+
_installSeedOps();
|
|
199
|
+
const make = () => createRoot((dispose) => {
|
|
200
|
+
e.dispose = dispose;
|
|
201
|
+
e.node = _asyncComputed(run(e), seed);
|
|
202
|
+
});
|
|
203
|
+
// Entries outlive the component that first read them; a server render's
|
|
204
|
+
// belong to the render, which releases them with everything else it made.
|
|
205
|
+
if (ctx !== null && ctx.owner) runWithOwner(ctx.owner, make);
|
|
206
|
+
else _detached(make);
|
|
207
|
+
return e;
|
|
72
208
|
}
|
|
73
209
|
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
const revalidationSubscribers = new Map();
|
|
77
|
-
|
|
78
|
-
function subscribeToKey(key, revalidateFn) {
|
|
79
|
-
if (!revalidationSubscribers.has(key)) revalidationSubscribers.set(key, new Set());
|
|
80
|
-
revalidationSubscribers.get(key).add(revalidateFn);
|
|
210
|
+
// The function of an entry's node: what one run of it does.
|
|
211
|
+
function run(e) {
|
|
81
212
|
return () => {
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
213
|
+
const op = e.next;
|
|
214
|
+
e.next = 0;
|
|
215
|
+
if (op === ADOPT && e.flight !== null) return e.flight.promise;
|
|
216
|
+
if (op === 0) {
|
|
217
|
+
// A run nothing asked for (what the fetcher read changed, an error
|
|
218
|
+
// boundary's reset) while nothing would show the result: no request.
|
|
219
|
+
if (!wanted(e)) {
|
|
220
|
+
if (e.error !== undefined) throw e.error;
|
|
221
|
+
return untrack(() => e.node.peek());
|
|
222
|
+
}
|
|
223
|
+
// Otherwise it fetches as the active reader that attached last, whose
|
|
224
|
+
// callbacks hear it, as an invalidation's fetch does.
|
|
225
|
+
e.by = lastActive(e);
|
|
86
226
|
}
|
|
227
|
+
return startFlight(e).promise;
|
|
87
228
|
};
|
|
88
229
|
}
|
|
89
230
|
|
|
90
|
-
//
|
|
91
|
-
//
|
|
92
|
-
//
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
const clearCacheHandlers = new Set();
|
|
231
|
+
// --- Structural sharing ---
|
|
232
|
+
// TanStack Query's default (and what SWR's deep compare gives): a fetch that
|
|
233
|
+
// answers data equal to what the cache holds keeps the cached references, and
|
|
234
|
+
// one that changes part of it keeps every part it did not change. A refetch of
|
|
235
|
+
// a list with the same rows hands a keyed .map() the same row objects, so no
|
|
236
|
+
// row shows a replaced item and nothing its rows built (a component's state,
|
|
237
|
+
// an open menu) is rebuilt; a changed row is a new object, its neighbours are
|
|
238
|
+
// not. Only arrays and plain objects are compared; anything else is taken as
|
|
239
|
+
// it arrives.
|
|
240
|
+
|
|
241
|
+
function isPlainObject(v) {
|
|
242
|
+
if (v === null || typeof v !== 'object') return false;
|
|
243
|
+
const proto = Object.getPrototypeOf(v);
|
|
244
|
+
return proto === Object.prototype || proto === null;
|
|
245
|
+
}
|
|
106
246
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
247
|
+
/** `next`, reusing every part of `prev` it equals (prev itself when all of it does). */
|
|
248
|
+
export function replaceEqualDeep(prev, next) {
|
|
249
|
+
if (prev === next) return prev;
|
|
250
|
+
const array = Array.isArray(prev) && Array.isArray(next);
|
|
251
|
+
if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next;
|
|
252
|
+
const prevKeys = array ? null : Object.keys(prev);
|
|
253
|
+
const prevSize = prevKeys === null ? prev.length : prevKeys.length;
|
|
254
|
+
const nextKeys = array ? null : Object.keys(next);
|
|
255
|
+
const nextSize = nextKeys === null ? next.length : nextKeys.length;
|
|
256
|
+
const copy = array ? new Array(nextSize) : {};
|
|
257
|
+
let equal = 0;
|
|
258
|
+
for (let i = 0; i < nextSize; i++) {
|
|
259
|
+
const key = nextKeys === null ? i : nextKeys[i];
|
|
260
|
+
const was = prev[key];
|
|
261
|
+
const shared = (array || Object.prototype.hasOwnProperty.call(prev, key)) ? replaceEqualDeep(was, next[key]) : next[key];
|
|
262
|
+
copy[key] = shared;
|
|
263
|
+
if (shared === was && (array ? i < prevSize : Object.prototype.hasOwnProperty.call(prev, key))) equal++;
|
|
264
|
+
}
|
|
265
|
+
return prevSize === nextSize && equal === prevSize ? prev : copy;
|
|
110
266
|
}
|
|
111
267
|
|
|
112
|
-
|
|
113
|
-
|
|
268
|
+
// The option's value as the share function the fetch applies (null: none).
|
|
269
|
+
function sharing(option) {
|
|
270
|
+
if (option === false || option == null) return null;
|
|
271
|
+
return typeof option === 'function' ? option : replaceEqualDeep;
|
|
272
|
+
}
|
|
114
273
|
|
|
115
|
-
//
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
274
|
+
// Whether anything would show a fetch nothing asked for by name.
|
|
275
|
+
function wanted(e) {
|
|
276
|
+
if (getServerContext() !== null) return true;
|
|
277
|
+
for (const o of e.observers) if (o.active()) return true;
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
121
280
|
|
|
122
|
-
function
|
|
123
|
-
|
|
281
|
+
function valueOf(e) {
|
|
282
|
+
const v = untrack(() => e.node.peek());
|
|
283
|
+
return v === IDLE ? undefined : v;
|
|
124
284
|
}
|
|
125
285
|
|
|
126
|
-
|
|
127
|
-
|
|
286
|
+
// --- Flights ---
|
|
287
|
+
|
|
288
|
+
function startFlight(e) {
|
|
289
|
+
const prev = e.flight;
|
|
290
|
+
if (prev !== null) kill(e, prev, true);
|
|
291
|
+
const ac = new AbortController();
|
|
292
|
+
const op = e.op;
|
|
293
|
+
e.op = null;
|
|
294
|
+
const from = sourceOf(e);
|
|
295
|
+
const f = {
|
|
296
|
+
ac,
|
|
297
|
+
dead: false,
|
|
298
|
+
superseded: false,
|
|
299
|
+
by: e.by,
|
|
300
|
+
conf: from.conf,
|
|
301
|
+
key: from.key,
|
|
302
|
+
// A prefetchQuery waits on it (it started it, joined it, or a flight it
|
|
303
|
+
// waited on was superseded by this one): no reader unmounting cancels it.
|
|
304
|
+
keep: from.keep === true || (prev !== null && prev.keep),
|
|
305
|
+
op,
|
|
306
|
+
/** @type {any} */ promise: null,
|
|
307
|
+
failed: false,
|
|
308
|
+
/** @type {any} */ result: undefined,
|
|
309
|
+
/** @type {any} */ page: undefined,
|
|
310
|
+
started: Date.now(),
|
|
311
|
+
/** @type {(() => void) | null} */ onKill: null,
|
|
312
|
+
/** @type {any} */ at: null,
|
|
313
|
+
};
|
|
314
|
+
// How the flight's own promises reach it and its entry (retrying, watch):
|
|
315
|
+
// kill() empties it.
|
|
316
|
+
f.at = { e, f };
|
|
317
|
+
e.by = null;
|
|
318
|
+
e.flight = f;
|
|
319
|
+
e.fetchedAt = f.started;
|
|
320
|
+
e.fetches++;
|
|
321
|
+
let first;
|
|
322
|
+
try {
|
|
323
|
+
first = callFetcher(e, f);
|
|
324
|
+
} catch (err) {
|
|
325
|
+
// A fetcher that threw before it started, or read an input that is not
|
|
326
|
+
// ready: the node takes that as its run's answer. A throw is the entry's
|
|
327
|
+
// error, as a rejection would be; the query() whose run this is reads it
|
|
328
|
+
// from the entry at once, so the landing does not run it again.
|
|
329
|
+
e.flight = null;
|
|
330
|
+
f.dead = true;
|
|
331
|
+
if (_isNotReady(err)) e.version++;
|
|
332
|
+
else record(e, f, err, true);
|
|
333
|
+
throw err;
|
|
334
|
+
}
|
|
335
|
+
f.promise = retrying(f.at, first);
|
|
336
|
+
watch(f.at, f.promise);
|
|
337
|
+
return f;
|
|
128
338
|
}
|
|
129
339
|
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
340
|
+
// What a fetch of `e` calls, and with which key: the fetcher of whatever asked
|
|
341
|
+
// (an observer, or a prefetchQuery), with its key as it wrote it now (['q',
|
|
342
|
+
// 'a'] and 'q:a' name one entry); for a fetch the cache starts itself, the
|
|
343
|
+
// reader that attached last, as TanStack Query uses its last observer's
|
|
344
|
+
// options. An observer whose key has moved to another entry asks with the
|
|
345
|
+
// entry's own: the last attach's fetcher and key.
|
|
346
|
+
function sourceOf(e) {
|
|
347
|
+
for (const o of [e.by, e.src]) {
|
|
348
|
+
if (o != null && (o.hash === undefined || untrack(o.hash) === e.hash)) return o;
|
|
349
|
+
}
|
|
350
|
+
return e;
|
|
138
351
|
}
|
|
139
352
|
|
|
140
|
-
//
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
//
|
|
144
|
-
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
// `status` and useSWR's `isLoading` for what each one actually broke.
|
|
158
|
-
//
|
|
159
|
-
// Reading everything unconditionally fixes it whatever the promotion rule is:
|
|
160
|
-
// the dependency set never varies, so there is nothing left to lose.
|
|
353
|
+
// A flight's landing, and its observer's callbacks after it. Its own scope,
|
|
354
|
+
// holding the flight's link and nothing else: until its transport answers, the
|
|
355
|
+
// flight's promise is reachable from it (retrying), and a dropped flight's
|
|
356
|
+
// link is empty.
|
|
357
|
+
function watch(at, promise) {
|
|
358
|
+
// Before the engine lands the result: readers that re-run on the landing see
|
|
359
|
+
// the new version, so they can tell it from a refresh.
|
|
360
|
+
promise.then((v) => {
|
|
361
|
+
if (at.f !== null) landed(at.e, at.f, v, false);
|
|
362
|
+
}, (err) => {
|
|
363
|
+
if (at.f !== null) landed(at.e, at.f, err, true);
|
|
364
|
+
});
|
|
365
|
+
// After it: callbacks see the value in the cache.
|
|
366
|
+
promise.then(noop, noop).then(() => {
|
|
367
|
+
if (at.f !== null) deliver(at.e, at.f);
|
|
368
|
+
});
|
|
369
|
+
}
|
|
161
370
|
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
function
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
371
|
+
// The pending transport keeps this continuation until it answers. Read both
|
|
372
|
+
// the entry and the sharing function through the link that kill() clears.
|
|
373
|
+
function shareResult(at, result) {
|
|
374
|
+
return result.then((next) => {
|
|
375
|
+
if (at.f === null) return next;
|
|
376
|
+
const share = at.f.conf.share;
|
|
377
|
+
return share(valueOf(at.e), next);
|
|
378
|
+
});
|
|
169
379
|
}
|
|
170
380
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
381
|
+
function callFetcher(e, f) {
|
|
382
|
+
const conf = f.conf;
|
|
383
|
+
if (e.kind === PLAIN) {
|
|
384
|
+
const result = conf.run(f.key, f.ac.signal);
|
|
385
|
+
const share = conf.share;
|
|
386
|
+
if (share == null) return result;
|
|
387
|
+
// Structural sharing: what the fetch answers keeps every part of the
|
|
388
|
+
// cached value it equals, compared when it lands.
|
|
389
|
+
return result != null && typeof result.then === 'function'
|
|
390
|
+
? shareResult(f.at, result)
|
|
391
|
+
: share(valueOf(e), result);
|
|
392
|
+
}
|
|
393
|
+
const base = valueOf(e) ?? { pages: [], pageParams: [] };
|
|
394
|
+
const op = f.op || { param: conf.initialPageParam, place: 'first' };
|
|
395
|
+
// Through the flight's link, as retrying() holds it (see there).
|
|
396
|
+
const at = f.at;
|
|
397
|
+
return Promise.resolve(conf.run(f.key, op.param, f.ac.signal)).then((page) => {
|
|
398
|
+
if (at.f !== null) at.f.page = page;
|
|
399
|
+
if (op.place === 'next') return { pages: [...base.pages, page], pageParams: [...base.pageParams, op.param] };
|
|
400
|
+
if (op.place === 'previous') return { pages: [page, ...base.pages], pageParams: [op.param, ...base.pageParams] };
|
|
401
|
+
return { pages: [page], pageParams: [op.param] };
|
|
402
|
+
});
|
|
181
403
|
}
|
|
182
404
|
|
|
183
|
-
//
|
|
184
|
-
//
|
|
185
|
-
//
|
|
186
|
-
// the
|
|
187
|
-
//
|
|
188
|
-
//
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
// "something the thunk reads moved" down to "the gate flipped", which is the
|
|
202
|
-
// only event a query has any business reacting to.
|
|
203
|
-
//
|
|
204
|
-
// A boolean is still accepted and still behaves exactly as before: it reads no
|
|
205
|
-
// signals, so the mirroring effect tracks no dependencies and the reactive core
|
|
206
|
-
// releases it on the spot.
|
|
207
|
-
function createGate(enabled) {
|
|
208
|
-
const read = typeof enabled === 'function' ? enabled : () => enabled;
|
|
209
|
-
const gate = signal(untrack(() => !!read()));
|
|
210
|
-
scopedEffect(() => { gate.set(!!read()); });
|
|
211
|
-
return gate;
|
|
405
|
+
// The first attempt is called synchronously (what the fetcher reads before its
|
|
406
|
+
// first await is tracked); a failed attempt is retried after retryDelay, up to
|
|
407
|
+
// `retry` attempts in all, unless the flight is aborted meanwhile. The entry and
|
|
408
|
+
// the flight are read through the flight's link (`at`), which kill() empties: a
|
|
409
|
+
// transport that ignores the abort and never answers holds this frame, and
|
|
410
|
+
// through it nothing of the flight, its entry or the fetcher.
|
|
411
|
+
async function retrying(at, first) {
|
|
412
|
+
let pending = first;
|
|
413
|
+
for (let tries = 1; ; tries++) {
|
|
414
|
+
try {
|
|
415
|
+
return await pending;
|
|
416
|
+
} catch (err) {
|
|
417
|
+
if (at.f === null || tries >= attemptsOf(at.f.conf.retry, tries, err)) throw err;
|
|
418
|
+
await wait(at.f.conf.retryDelay(tries), at.f.ac.signal);
|
|
419
|
+
if (at.f === null) throw err;
|
|
420
|
+
pending = callFetcher(at.e, at.f);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
212
423
|
}
|
|
213
424
|
|
|
214
|
-
|
|
215
|
-
|
|
425
|
+
function attemptsOf(retry, tries, err) {
|
|
426
|
+
if (typeof retry === 'function') return retry(tries - 1, err) ? tries + 1 : tries;
|
|
427
|
+
if (retry === true) return Infinity;
|
|
428
|
+
if (retry === false) return 1;
|
|
429
|
+
return Math.max(1, Number(retry) || 0);
|
|
430
|
+
}
|
|
216
431
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
432
|
+
function wait(ms, abortSignal) {
|
|
433
|
+
return new Promise((resolve, reject) => {
|
|
434
|
+
const id = unrefTimer(setTimeout(resolve, ms));
|
|
435
|
+
abortSignal.addEventListener('abort', () => {
|
|
436
|
+
clearTimeout(id);
|
|
437
|
+
reject(new DOMException('Aborted', 'AbortError'));
|
|
438
|
+
}, { once: true });
|
|
439
|
+
});
|
|
440
|
+
}
|
|
225
441
|
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
442
|
+
function landed(e, f, result, failed) {
|
|
443
|
+
f.failed = failed;
|
|
444
|
+
f.result = result;
|
|
445
|
+
if (f.dead) return;
|
|
446
|
+
if (e.flight === f) e.flight = null;
|
|
447
|
+
record(e, f, result, failed);
|
|
448
|
+
if (f.keep) armGc(e);
|
|
449
|
+
e.tick((n) => n + 1);
|
|
450
|
+
}
|
|
231
451
|
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
452
|
+
// A fetch's result, on the entry.
|
|
453
|
+
function record(e, f, result, failed) {
|
|
454
|
+
e.version++;
|
|
455
|
+
const now = Date.now();
|
|
456
|
+
e.updatedAt = now;
|
|
457
|
+
e.error = failed ? result : undefined;
|
|
458
|
+
e.last = { at: now, ms: now - f.started, ok: !failed };
|
|
459
|
+
if (e.dir !== null) e.dir(null);
|
|
460
|
+
answer(e, result, failed);
|
|
461
|
+
}
|
|
237
462
|
|
|
238
|
-
|
|
239
|
-
|
|
463
|
+
// The entry got a value or an error: a query() waiting for its first one
|
|
464
|
+
// lands with it, and runs again to read the node from then on.
|
|
465
|
+
function arrive(e, result, failed) {
|
|
466
|
+
answer(e, result, failed);
|
|
467
|
+
e.tick((n) => n + 1);
|
|
468
|
+
}
|
|
240
469
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
body: body ? JSON.stringify(body) : undefined,
|
|
249
|
-
signal: abortSignal,
|
|
250
|
-
});
|
|
470
|
+
function answer(e, result, failed) {
|
|
471
|
+
const a = e.arrival;
|
|
472
|
+
if (a !== null) {
|
|
473
|
+
e.arrival = null;
|
|
474
|
+
(failed ? a.reject : a.resolve)(result);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
251
477
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
478
|
+
function arrival(e) {
|
|
479
|
+
if (e.arrival === null) {
|
|
480
|
+
/** @type {(value: any) => void} */
|
|
481
|
+
let resolve = noop;
|
|
482
|
+
/** @type {(error: any) => void} */
|
|
483
|
+
let reject = noop;
|
|
484
|
+
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
|
|
485
|
+
e.arrival = { promise, resolve, reject };
|
|
486
|
+
}
|
|
487
|
+
return e.arrival.promise;
|
|
488
|
+
}
|
|
255
489
|
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
490
|
+
// A flight's result is dropped: superseded by a newer flight, or nothing can
|
|
491
|
+
// show it any more.
|
|
492
|
+
function kill(e, f, superseded) {
|
|
493
|
+
if (f.dead) return;
|
|
494
|
+
f.dead = true;
|
|
495
|
+
f.superseded = superseded;
|
|
496
|
+
f.at.e = f.at.f = null;
|
|
497
|
+
f.ac.abort(droppedReason());
|
|
498
|
+
if (e.flight === f) e.flight = null;
|
|
499
|
+
if (f.onKill !== null) f.onKill();
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// What a dropped flight's signal aborts with. Its stack is read at once: until
|
|
503
|
+
// then an error holds the functions of the stack it was made on (the
|
|
504
|
+
// component code that dropped the flight), and a transport that ignores the
|
|
505
|
+
// abort may keep the signal, and with it the reason.
|
|
506
|
+
function droppedReason() {
|
|
507
|
+
const reason = new DOMException('The query was dropped.', 'AbortError');
|
|
508
|
+
void reason.stack;
|
|
509
|
+
return reason;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// The callbacks of the observer that asked for a flight, once its result is in
|
|
513
|
+
// the cache. A flight the cache started itself (an invalidation) belongs to
|
|
514
|
+
// the active observer that attached last.
|
|
515
|
+
function deliver(e, f) {
|
|
516
|
+
if (f.dead) return;
|
|
517
|
+
const o = f.by;
|
|
518
|
+
if (o === null || !o.alive) return;
|
|
519
|
+
if (f.failed) {
|
|
520
|
+
if (o.onError) o.onError(f.result, f.key);
|
|
521
|
+
if (o.onSettled) o.onSettled(null, f.result);
|
|
522
|
+
} else {
|
|
523
|
+
// An infinite query's callbacks hear the page that was fetched.
|
|
524
|
+
const value = e.kind === INFINITE ? f.page : f.result;
|
|
525
|
+
if (o.onSuccess) o.onSuccess(value, f.key);
|
|
526
|
+
if (o.onSettled) o.onSettled(value, null);
|
|
269
527
|
}
|
|
528
|
+
}
|
|
270
529
|
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
530
|
+
// What a fetch the caller asked for gave: its value (an infinite query's: the
|
|
531
|
+
// page it fetched), the value of the flight that superseded it, or undefined
|
|
532
|
+
// when its result was dropped.
|
|
533
|
+
function outcome(e, f) {
|
|
534
|
+
if (f.dead) return Promise.resolve(follow(e, f));
|
|
535
|
+
const settled = flightValue(f.at, f.promise);
|
|
536
|
+
// Dropped, it answers at once, without waiting for a transport that may
|
|
537
|
+
// ignore the abort: the newer flight is in place by the time this runs.
|
|
538
|
+
const dropped = new Promise((resolve) => {
|
|
539
|
+
const prev = f.onKill;
|
|
540
|
+
f.onKill = () => {
|
|
541
|
+
if (prev !== null) prev();
|
|
542
|
+
resolve(undefined);
|
|
276
543
|
};
|
|
277
|
-
});
|
|
544
|
+
}).then(() => follow(e, f));
|
|
545
|
+
return Promise.race([settled, dropped]);
|
|
546
|
+
}
|
|
278
547
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
error: () => error(),
|
|
282
|
-
isLoading: () => isLoading(),
|
|
283
|
-
refetch: fetchData,
|
|
284
|
-
mutate: (newData) => data.set(newData),
|
|
285
|
-
};
|
|
548
|
+
function follow(e, f) {
|
|
549
|
+
return f.superseded && e.flight !== null ? outcome(e, e.flight) : undefined;
|
|
286
550
|
}
|
|
287
551
|
|
|
288
|
-
//
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
const error = signal(null);
|
|
299
|
-
return {
|
|
300
|
-
data: () => data(),
|
|
301
|
-
error: () => error(),
|
|
302
|
-
isLoading: () => false,
|
|
303
|
-
isValidating: () => false,
|
|
304
|
-
mutate: (newData) => data.set(typeof newData === 'function' ? newData(data()) : newData),
|
|
305
|
-
revalidate: () => Promise.resolve(),
|
|
306
|
-
};
|
|
307
|
-
}
|
|
552
|
+
// What a flight's promise gives the caller of outcome(): its value (an
|
|
553
|
+
// infinite query's: the page it fetched) or its rejection, and never an answer
|
|
554
|
+
// once it is dropped, which outcome()'s other branch gives. Its own scope, like
|
|
555
|
+
// watch(), so it holds the flight's link and nothing else.
|
|
556
|
+
function flightValue(at, promise) {
|
|
557
|
+
return promise.then(
|
|
558
|
+
(v) => (at.f === null ? new Promise(noop) : at.e.kind === INFINITE ? at.f.page : v),
|
|
559
|
+
(err) => (at.f === null ? new Promise(noop) : Promise.reject(err)),
|
|
560
|
+
);
|
|
561
|
+
}
|
|
308
562
|
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
// `useSWR(['/api/user', id], ([url, id]) => ...)`, and how the cache spells a
|
|
323
|
-
// key internally is none of the fetcher's business.
|
|
324
|
-
const key = normalizeQueryKey(rawKey);
|
|
325
|
-
|
|
326
|
-
// Shared reactive cache signals — all useSWR instances with the same key
|
|
327
|
-
// read from these signals, so mutating from one component updates all others.
|
|
328
|
-
const cacheS = getCacheSignal(key);
|
|
329
|
-
const error = getErrorSignal(key);
|
|
330
|
-
const isValidating = getValidatingSignal(key);
|
|
331
|
-
const data = computed(() => cacheS() ?? fallbackData ?? null);
|
|
332
|
-
// Both reads are unconditional. See the note on conditional reads above
|
|
333
|
-
// scopedEffect: as `cacheS() == null && isValidating()` this computed dropped
|
|
334
|
-
// to a single dependency on any re-run that found the cache full (a mutate(),
|
|
335
|
-
// a setQueryData(), a second successful fetch), was promoted to a stable
|
|
336
|
-
// effect there, and never tracked isValidating again -- after which
|
|
337
|
-
// isLoading() answered false for the rest of the page's life, including with
|
|
338
|
-
// an empty cache and a request in flight, which is the one state it exists to
|
|
339
|
-
// report.
|
|
340
|
-
const isLoading = computed(() => {
|
|
341
|
-
const empty = cacheS() == null;
|
|
342
|
-
const fetching = isValidating();
|
|
343
|
-
return empty && fetching;
|
|
344
|
-
});
|
|
563
|
+
// Fetch an entry now, superseding what is in flight. `by` is the observer
|
|
564
|
+
// whose callbacks hear the result. Returns the node's refresh promise.
|
|
565
|
+
function fetchEntry(e, by, op) {
|
|
566
|
+
e.by = by;
|
|
567
|
+
e.op = op || null;
|
|
568
|
+
e.next = FETCH;
|
|
569
|
+
if (e.dir !== null) e.dir(op ? op.dir : 'next');
|
|
570
|
+
const refreshed = refreshNode(e);
|
|
571
|
+
e.next = 0;
|
|
572
|
+
e.by = null;
|
|
573
|
+
e.op = null;
|
|
574
|
+
return refreshed;
|
|
575
|
+
}
|
|
345
576
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
//
|
|
354
|
-
// It does NOT bypass request COALESCING, which is a different mechanism
|
|
355
|
-
// wearing a similar name. Every component reading a key subscribes
|
|
356
|
-
// separately, so one invalidateQueries() call fans out to N subscribers; the
|
|
357
|
-
// in-flight map is what collapses those back into one request. Skipping it
|
|
358
|
-
// opened N concurrent fetches of the same key whose responses then raced to
|
|
359
|
-
// write the cache.
|
|
360
|
-
//
|
|
361
|
-
// What force does change is WHICH in-flight request is acceptable. A response
|
|
362
|
-
// to a request that started before the data was invalidated is already stale,
|
|
363
|
-
// so it cannot answer the invalidation. One that started after it is a
|
|
364
|
-
// sibling subscriber's, and is exactly what we want to join.
|
|
365
|
-
async function revalidate({ force = false } = {}) {
|
|
366
|
-
const now = Date.now();
|
|
367
|
-
const epoch = currentEpoch(key);
|
|
368
|
-
|
|
369
|
-
// Deduplication: if there's already a request in flight, reuse it
|
|
370
|
-
if (inFlightRequests.has(key)) {
|
|
371
|
-
const existing = inFlightRequests.get(key);
|
|
372
|
-
const usable = force
|
|
373
|
-
? existing.epoch === epoch
|
|
374
|
-
: now - existing.timestamp < dedupingInterval;
|
|
375
|
-
if (usable) {
|
|
376
|
-
existing.refCount++;
|
|
377
|
-
return existing.promise;
|
|
378
|
-
}
|
|
379
|
-
}
|
|
577
|
+
// Automatic refreshes expose failures through the node. Handle the rejection
|
|
578
|
+
// even when the caller only needs to start the fetch.
|
|
579
|
+
function refreshNode(e) {
|
|
580
|
+
const refreshed = _refresh(e.node);
|
|
581
|
+
refreshed.then(noop, noop);
|
|
582
|
+
return refreshed;
|
|
583
|
+
}
|
|
380
584
|
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
}
|
|
585
|
+
function refetchOf(e, by, op) {
|
|
586
|
+
fetchEntry(e, by, op);
|
|
587
|
+
return e.flight !== null ? outcome(e, e.flight) : Promise.resolve(valueOf(e));
|
|
588
|
+
}
|
|
386
589
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
590
|
+
// Make `value` the entry's value now, dropping what is in flight. It lands as
|
|
591
|
+
// a fetch's would, so its readers run; the engine ends the node's run in
|
|
592
|
+
// flight, and a transition waiting for that run stops waiting.
|
|
593
|
+
function commitValue(e, value) {
|
|
594
|
+
if (e.flight !== null) kill(e, e.flight, false);
|
|
595
|
+
if (e.dir !== null) e.dir(null);
|
|
596
|
+
e.version++;
|
|
597
|
+
_setAsyncValue(e.node, value);
|
|
598
|
+
if (value !== IDLE) arrive(e, value, false);
|
|
599
|
+
else e.tick((n) => n + 1);
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// Land `value` in the entry now, as a fetch would.
|
|
603
|
+
function setEntry(e, value) {
|
|
604
|
+
e.updatedAt = Date.now();
|
|
605
|
+
e.error = undefined;
|
|
606
|
+
commitValue(e, value);
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function dropEntry(e) {
|
|
610
|
+
if (e.dropped) return;
|
|
611
|
+
e.dropped = true;
|
|
612
|
+
if (e.timer !== null) clearTimeout(e.timer);
|
|
613
|
+
if (e.flight !== null) kill(e, e.flight, false);
|
|
614
|
+
if (e.cache.get(e.hash) === e) e.cache.delete(e.hash);
|
|
615
|
+
e.dispose();
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// --- Observers ---
|
|
619
|
+
// Each query(), useQuery(), useSWR()... call is an observer of the entry its
|
|
620
|
+
// key names now. It counts as a reader of that entry from its first run until
|
|
621
|
+
// its owner is disposed or its key moves on; a key change hands it to the new
|
|
622
|
+
// key's entry. On a server render there are no observers: entries live as
|
|
623
|
+
// long as the render.
|
|
624
|
+
|
|
625
|
+
let pathTag = /** @type {string | null} */ (null);
|
|
626
|
+
|
|
627
|
+
// The path of the page a query is read on outside route data: what-router's,
|
|
628
|
+
// which it registers under this key once it is in use (the page's path as
|
|
629
|
+
// the app writes it, without the base, as route data is), else the address
|
|
630
|
+
// bar's.
|
|
631
|
+
const PAGE_PATH = Symbol.for('what.router.path.v1');
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* @internal Run `fn` and tag the entries its observers read with `path`, so
|
|
635
|
+
* invalidatePath(path) reaches them (the router's route data).
|
|
636
|
+
*/
|
|
637
|
+
export function _tagQueries(path, fn) {
|
|
638
|
+
const prev = pathTag;
|
|
639
|
+
pathTag = path;
|
|
640
|
+
try {
|
|
641
|
+
return fn();
|
|
642
|
+
} finally {
|
|
643
|
+
pathTag = prev;
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* @internal what-router: resolves once no entry read on `path` is fetching
|
|
649
|
+
* its first value: the data a page a navigation committed reads, and what
|
|
650
|
+
* that data makes fetch in turn.
|
|
651
|
+
*/
|
|
652
|
+
export function _pathLoaded(path) {
|
|
653
|
+
const waits = [];
|
|
654
|
+
for (const e of allEntries()) {
|
|
655
|
+
if (e.flight !== null && e.paths !== null && e.paths.has(path) && e.error === undefined && valueOf(e) === undefined) {
|
|
656
|
+
waits.push(outcome(e, e.flight).then(noop, noop));
|
|
393
657
|
}
|
|
394
|
-
|
|
395
|
-
|
|
658
|
+
}
|
|
659
|
+
return waits.length === 0 ? Promise.resolve() : Promise.all(waits).then(() => _pathLoaded(path));
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
function acquire(e, o) {
|
|
663
|
+
if (e.dropped) {
|
|
664
|
+
// Dropped (clearCache) between choosing it and attaching: take it back.
|
|
665
|
+
e.dropped = false;
|
|
666
|
+
if (!e.cache.has(e.hash)) e.cache.set(e.hash, e);
|
|
667
|
+
}
|
|
668
|
+
if (e.timer !== null) {
|
|
669
|
+
clearTimeout(e.timer);
|
|
670
|
+
e.timer = null;
|
|
671
|
+
}
|
|
672
|
+
// An entry is kept unread for the longest gcTime among its readers.
|
|
673
|
+
e.gcTime = e.observers.size === 0 ? o.gcTime : Math.max(e.gcTime, o.gcTime);
|
|
674
|
+
e.observers.add(o);
|
|
675
|
+
// The reader the cache's own fetches go through (sourceOf), and its fetcher
|
|
676
|
+
// and key for when it has moved on.
|
|
677
|
+
e.src = o;
|
|
678
|
+
e.conf = o.conf;
|
|
679
|
+
e.key = o.key;
|
|
680
|
+
const path = o.path ?? /** @type {any} */ (globalThis)[PAGE_PATH]?.() ?? (typeof location !== 'undefined' ? location.pathname : null);
|
|
681
|
+
if (path != null) (e.paths || (e.paths = new Set())).add(path);
|
|
682
|
+
}
|
|
396
683
|
|
|
397
|
-
|
|
684
|
+
function release(e, o) {
|
|
685
|
+
if (!e.observers.delete(o)) return;
|
|
686
|
+
// A reader that let go holds nothing through the entry (its last fetcher
|
|
687
|
+
// and key stay, as e.conf and e.key).
|
|
688
|
+
if (e.src === o) e.src = null;
|
|
689
|
+
if (e.observers.size > 0) return;
|
|
690
|
+
// Nothing shows this entry now: what the readers had in flight is cancelled
|
|
691
|
+
// (they keep the last value), a prefetch's runs on, and the entry is dropped
|
|
692
|
+
// once it has stayed unread for its gcTime.
|
|
693
|
+
if (e.flight !== null && !e.flight.keep) commitValue(e, untrack(() => e.node.peek()));
|
|
694
|
+
armGc(e);
|
|
695
|
+
}
|
|
398
696
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
697
|
+
function armGc(e) {
|
|
698
|
+
// A server flight can land outside its request context on hosts without
|
|
699
|
+
// async context storage. Only the page's own cache needs eviction timers.
|
|
700
|
+
if (e.cache !== clientCache[e.kind] || e.observers.size > 0 || e.dropped) return;
|
|
701
|
+
if (e.timer !== null) clearTimeout(e.timer);
|
|
702
|
+
e.timer = !e.flight?.keep && Number.isFinite(e.gcTime)
|
|
703
|
+
? unrefTimer(setTimeout(() => {
|
|
704
|
+
e.timer = null;
|
|
705
|
+
if (e.observers.size === 0) dropEntry(e);
|
|
706
|
+
}, e.gcTime))
|
|
707
|
+
: null;
|
|
708
|
+
}
|
|
402
709
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
cacheTimestamps.set(key, Date.now());
|
|
411
|
-
lastFetchTimestamps.set(key, Date.now());
|
|
412
|
-
if (onSuccess) onSuccess(result, rawKey);
|
|
413
|
-
return result;
|
|
414
|
-
} catch (e) {
|
|
415
|
-
if (abortSignal.aborted) return;
|
|
416
|
-
error.set(e);
|
|
417
|
-
if (onError) onError(e, rawKey);
|
|
418
|
-
throw e;
|
|
419
|
-
} finally {
|
|
420
|
-
if (!abortSignal.aborted) isValidating.set(false);
|
|
421
|
-
const flight = inFlightRequests.get(key);
|
|
422
|
-
if (flight) {
|
|
423
|
-
flight.refCount--;
|
|
424
|
-
if (flight.refCount <= 0) inFlightRequests.delete(key);
|
|
425
|
-
}
|
|
710
|
+
// An observer reads `e` now: it holds it, and lets go of the entries it read
|
|
711
|
+
// before.
|
|
712
|
+
function settle(o, e) {
|
|
713
|
+
for (const x of o.entries) {
|
|
714
|
+
if (x !== e) {
|
|
715
|
+
o.entries.delete(x);
|
|
716
|
+
release(x, o);
|
|
426
717
|
}
|
|
427
718
|
}
|
|
719
|
+
if (e !== null) hold(o, e);
|
|
720
|
+
o.entry = e;
|
|
721
|
+
}
|
|
428
722
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
// refetch unsubscribed the key and never resubscribed: from then on
|
|
435
|
-
// invalidateQueries() had no subscriber to call and silently did nothing.
|
|
436
|
-
// Re-subscribing per run keeps the two halves in the same lifecycle.
|
|
437
|
-
scopedEffect(() => {
|
|
438
|
-
const unsubscribe = subscribeToKey(key, () => revalidate({ force: true }).catch(() => {}));
|
|
439
|
-
// clearCache() empties this key's shared signals, but the request already on
|
|
440
|
-
// the wire is not in any Map it can walk: it landed after the clear and put
|
|
441
|
-
// the previous user's data back. See registerClearCacheHandler.
|
|
442
|
-
const releaseHandler = registerClearCacheHandler(() => {
|
|
443
|
-
if (abortController) {
|
|
444
|
-
abortController.abort();
|
|
445
|
-
abortController = null;
|
|
446
|
-
}
|
|
447
|
-
// isValidating is the SHARED signal for this key and clearCache has
|
|
448
|
-
// already set it false; the aborted request deliberately returns without
|
|
449
|
-
// touching it, so there is nothing left to reset here.
|
|
450
|
-
});
|
|
451
|
-
revalidate().catch(() => {});
|
|
452
|
-
// Cleanup: abort and unsubscribe on unmount
|
|
453
|
-
return () => {
|
|
454
|
-
if (abortController) abortController.abort();
|
|
455
|
-
unsubscribe();
|
|
456
|
-
releaseHandler();
|
|
457
|
-
};
|
|
458
|
-
});
|
|
723
|
+
function hold(o, e) {
|
|
724
|
+
if (o.entries.has(e)) return;
|
|
725
|
+
o.entries.add(e);
|
|
726
|
+
acquire(e, o);
|
|
727
|
+
}
|
|
459
728
|
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
729
|
+
// query()'s value reads a new key's entry before the observer's effect runs
|
|
730
|
+
// (a transition holds that effect until it commits): it holds the entry at
|
|
731
|
+
// once, and lets go of the old one after the evaluation, which must not
|
|
732
|
+
// change the graph it is reading.
|
|
733
|
+
function holdFromRead(o, e) {
|
|
734
|
+
if (getServerContext() !== null || !o.alive) return;
|
|
735
|
+
hold(o, e);
|
|
736
|
+
if (o.entries.size > 1 && !o.sweeping) {
|
|
737
|
+
o.sweeping = true;
|
|
738
|
+
queueMicrotask(() => {
|
|
739
|
+
o.sweeping = false;
|
|
740
|
+
if (o.alive) settle(o, untrack(o.current));
|
|
470
741
|
});
|
|
471
742
|
}
|
|
743
|
+
}
|
|
472
744
|
|
|
473
|
-
|
|
474
|
-
if (
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
745
|
+
function readKey(keyFn, lenient) {
|
|
746
|
+
if (!lenient) return keyParts(keyFn());
|
|
747
|
+
// SWR's contract: a key function (or a function in a key array) that
|
|
748
|
+
// throws, because its input is not there yet, means "not now", like a null
|
|
749
|
+
// key.
|
|
750
|
+
try {
|
|
751
|
+
return keyParts(keyFn());
|
|
752
|
+
} catch {
|
|
753
|
+
return null;
|
|
480
754
|
}
|
|
755
|
+
}
|
|
481
756
|
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
757
|
+
/**
|
|
758
|
+
* @param {number} kind
|
|
759
|
+
* @param {any} key a key, or a function returning one (null/false: none)
|
|
760
|
+
* @param {any} conf what fetches: { run, retry, retryDelay, ... }
|
|
761
|
+
* @param {any} opts { gate, staleTime, gcTime, initialData, callbacks, lenient }
|
|
762
|
+
*/
|
|
763
|
+
function observe(kind, key, conf, opts) {
|
|
764
|
+
const o = {
|
|
765
|
+
kind,
|
|
766
|
+
conf,
|
|
767
|
+
alive: true,
|
|
768
|
+
/** @type {any} */ entry: null,
|
|
769
|
+
/** @type {Set<any>} */ entries: new Set(),
|
|
770
|
+
/** @type {any} */ previous: null,
|
|
771
|
+
sweeping: false,
|
|
772
|
+
gate: opts.gate || null,
|
|
773
|
+
staleTime: opts.staleTime ?? 0,
|
|
774
|
+
gcTime: opts.gcTime ?? DEFAULT_GC_TIME,
|
|
775
|
+
initialData: opts.initialData,
|
|
776
|
+
initialDataUpdatedAt: opts.initialDataUpdatedAt,
|
|
777
|
+
onSuccess: opts.onSuccess,
|
|
778
|
+
onError: opts.onError,
|
|
779
|
+
onSettled: opts.onSettled,
|
|
780
|
+
path: pathTag,
|
|
781
|
+
active: () => o.alive && (o.gate === null || o.gate.peek()),
|
|
782
|
+
/** @type {() => any} */ current: noop,
|
|
783
|
+
// The key as this observer wrote it last: a new spelling of the same
|
|
784
|
+
// entry ('q:a', then ['q', 'a']) moves it without moving the entry.
|
|
785
|
+
/** @type {any} */ key: null,
|
|
786
|
+
/** @type {() => string | null} */ hash: () => null,
|
|
787
|
+
};
|
|
788
|
+
const keyFn = typeof key === 'function' ? key : () => key;
|
|
789
|
+
const hash = computed(() => {
|
|
790
|
+
const k = readKey(keyFn, opts.lenient);
|
|
791
|
+
o.key = k;
|
|
792
|
+
return k == null || k === false ? null : normalizeQueryKey(k);
|
|
793
|
+
});
|
|
794
|
+
o.hash = hash;
|
|
795
|
+
let last = null;
|
|
796
|
+
o.current = computed(() => {
|
|
797
|
+
const h = hash();
|
|
798
|
+
const e = h === null ? null : entryFor(kind, h, o.key, o);
|
|
799
|
+
// The entry the key named before: what keepPreviousData shows.
|
|
800
|
+
if (e !== last) {
|
|
801
|
+
if (last !== null) o.previous = last;
|
|
802
|
+
last = e;
|
|
803
|
+
}
|
|
804
|
+
return e;
|
|
805
|
+
});
|
|
806
|
+
if (getServerContext() !== null) return o;
|
|
807
|
+
|
|
808
|
+
let wasOpen = false;
|
|
809
|
+
effect(() => {
|
|
810
|
+
const e = o.current();
|
|
811
|
+
const open = o.gate === null || o.gate();
|
|
812
|
+
untrack(() => {
|
|
813
|
+
// An attach, or the gate opening, fetches what is stale. An entry the
|
|
814
|
+
// value already read (inside a transition that held this effect) was
|
|
815
|
+
// fetched then; what it got since is not news to refetch.
|
|
816
|
+
const attaching = e !== null && !o.entries.has(e);
|
|
817
|
+
const opening = open && !wasOpen;
|
|
818
|
+
wasOpen = open;
|
|
819
|
+
settle(o, e);
|
|
820
|
+
if (e !== null && open && (attaching || opening) && stale(e, o)) fetchEntry(e, o);
|
|
821
|
+
});
|
|
822
|
+
});
|
|
823
|
+
if (getOwner() !== null) {
|
|
824
|
+
onCleanup(() => {
|
|
825
|
+
o.alive = false;
|
|
826
|
+
settle(o, null);
|
|
489
827
|
});
|
|
490
828
|
}
|
|
829
|
+
return o;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
// Whether an observer attaching to `e` (or hearing focus, reconnect) fetches
|
|
833
|
+
// it: nothing in flight, and no value, a failure, or a value older than its
|
|
834
|
+
// staleTime. A value the page's data channel carried counts as fresh for the
|
|
835
|
+
// observers that attach in the task that adopted it.
|
|
836
|
+
function stale(e, o) {
|
|
837
|
+
if (e.flight !== null || e.hydrated) return false;
|
|
838
|
+
if (e.error !== undefined || valueOf(e) === undefined) return true;
|
|
839
|
+
// Stale once its age reaches staleTime, as in TanStack Query: with the
|
|
840
|
+
// default 0 a value is stale at once, even one written this millisecond
|
|
841
|
+
// (setQueryData, then a mount in the same tick, did not refetch).
|
|
842
|
+
return Date.now() - e.updatedAt >= o.staleTime;
|
|
843
|
+
}
|
|
491
844
|
|
|
845
|
+
// What a hook shows of the entry its key names now. Tracked: it re-runs when a
|
|
846
|
+
// fetch starts or ends and when the value changes. Never suspends.
|
|
847
|
+
function stateOf(o) {
|
|
848
|
+
if (getServerContext() !== null || isHydrating()) return firstState(o);
|
|
849
|
+
const e = o.current();
|
|
850
|
+
if (e === null) return { value: undefined, error: null, fetching: false, first: false, e };
|
|
851
|
+
const n = e.node;
|
|
852
|
+
const status = _asyncStatus(n);
|
|
853
|
+
// Subscribes to the value as well, without holding the reader: a value that
|
|
854
|
+
// is not ready, or failed, is what `status` already says.
|
|
855
|
+
try { n(); } catch { /* see status */ }
|
|
856
|
+
const v = n.peek();
|
|
492
857
|
return {
|
|
493
|
-
|
|
494
|
-
error: ()
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
const resolved = typeof newData === 'function' ? newData(cacheS.peek()) : newData;
|
|
499
|
-
cacheS.set(resolved); // Updates ALL components reading this key
|
|
500
|
-
cacheTimestamps.set(key, Date.now());
|
|
501
|
-
if (shouldRevalidate) {
|
|
502
|
-
revalidate().catch(() => {});
|
|
503
|
-
}
|
|
504
|
-
},
|
|
505
|
-
revalidate,
|
|
858
|
+
value: v === IDLE ? undefined : v,
|
|
859
|
+
error: status === 'errored' ? _asyncError(n) : null,
|
|
860
|
+
fetching: status === 'pending' || status === 'unresolved',
|
|
861
|
+
first: false,
|
|
862
|
+
e,
|
|
506
863
|
};
|
|
507
864
|
}
|
|
508
865
|
|
|
509
|
-
//
|
|
510
|
-
//
|
|
866
|
+
// A hook does not fetch on the server, and it renders the same there as in
|
|
867
|
+
// the hydration walk that adopts the server's DOM: its first state, with its
|
|
868
|
+
// own initialData and nothing else the cache holds. What a query() of the same
|
|
869
|
+
// key fetched depends on the order the server rendered the two in, which the
|
|
870
|
+
// client cannot know. An entry the page's loader filled is the exception: it
|
|
871
|
+
// was there before the render began, whatever the order, and the page names
|
|
872
|
+
// it (`loaded`), so a hook renders its value on the server and in the walk,
|
|
873
|
+
// as TanStack Query renders a query prefetched on the server. Right after the
|
|
874
|
+
// walk it shows the cache, with no request for a value the page carried.
|
|
875
|
+
const walked = /* @__PURE__ */ signal(0);
|
|
876
|
+
let walkEnding = false;
|
|
877
|
+
|
|
878
|
+
/** @type {WeakMap<object, Set<string>>} */
|
|
879
|
+
const loadedBy = new WeakMap();
|
|
880
|
+
|
|
881
|
+
function firstState(o) {
|
|
882
|
+
const ctx = getServerContext();
|
|
883
|
+
if (ctx === null) {
|
|
884
|
+
walked();
|
|
885
|
+
if (!walkEnding) {
|
|
886
|
+
walkEnding = true;
|
|
887
|
+
queueMicrotask(() => {
|
|
888
|
+
walkEnding = false;
|
|
889
|
+
walked((n) => n + 1);
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const h = untrack(o.hash);
|
|
894
|
+
if (h !== null && (ctx !== null ? loadedBy.get(ctx)?.has(h) : _loadedResource(CHANNEL + h))) {
|
|
895
|
+
const value = ctx !== null ? valueOf(untrack(o.current)) : getResource(CHANNEL + h);
|
|
896
|
+
return { value, error: null, fetching: false, first: false, e: null };
|
|
897
|
+
}
|
|
898
|
+
const initial = o.initialData;
|
|
899
|
+
return { value: typeof initial === 'function' ? untrack(initial) : initial, error: null, fetching: false, first: true, e: null };
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/**
|
|
903
|
+
* @internal The keys (`query:KEY`) of the entries a server render's loader
|
|
904
|
+
* filled, which have landed: what-server calls it once the loader has run,
|
|
905
|
+
* before the render begins, and the page carries them as `loaded`. The hooks
|
|
906
|
+
* of that render show their values (firstState).
|
|
907
|
+
*/
|
|
908
|
+
export function _loadedQueries(ctx) {
|
|
909
|
+
const done = new Set();
|
|
910
|
+
for (const [hash, e] of serverCaches.get(ctx)?.[PLAIN] ?? []) {
|
|
911
|
+
if (e.flight === null && e.error === undefined && valueOf(e) !== undefined) done.add(hash);
|
|
912
|
+
}
|
|
913
|
+
loadedBy.set(ctx, done);
|
|
914
|
+
return [...done].map((hash) => CHANNEL + hash);
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// The `enabled` gate, mirrored into a signal: an effect that reads the
|
|
918
|
+
// caller's thunk re-runs whenever anything it reads moves, and only a flip of
|
|
919
|
+
// the gate is news to a query.
|
|
920
|
+
function createGate(enabled) {
|
|
921
|
+
const read = typeof enabled === 'function' ? enabled : () => enabled;
|
|
922
|
+
const gate = signal(untrack(() => !!read()));
|
|
923
|
+
if (getServerContext() === null) effect(() => { gate(!!read()); });
|
|
924
|
+
return gate;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
function onWindow(o, events, check) {
|
|
928
|
+
if (getServerContext() !== null || typeof window === 'undefined') return;
|
|
929
|
+
effect(() => {
|
|
930
|
+
const handler = () => {
|
|
931
|
+
if (events[0] === 'visibilitychange' && document.visibilityState !== 'visible') return;
|
|
932
|
+
const e = o.entry;
|
|
933
|
+
if (e !== null && o.active() && check(e)) fetchEntry(e, o);
|
|
934
|
+
};
|
|
935
|
+
const target = events[0] === 'visibilitychange' ? document : window;
|
|
936
|
+
target.addEventListener(events[0], handler);
|
|
937
|
+
return () => target.removeEventListener(events[0], handler);
|
|
938
|
+
});
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
function poll(o, interval) {
|
|
942
|
+
if (!interval || getServerContext() !== null) return;
|
|
943
|
+
effect(() => {
|
|
944
|
+
const id = unrefTimer(setInterval(() => {
|
|
945
|
+
const e = o.entry;
|
|
946
|
+
if (e !== null && o.active() && e.flight === null) fetchEntry(e, o);
|
|
947
|
+
}, interval));
|
|
948
|
+
return () => clearInterval(id);
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function asArray(key) {
|
|
953
|
+
return Array.isArray(key) ? key : [key];
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
const defaultRetryDelay = (attempt) => Math.min(1000 * 2 ** attempt, 30000);
|
|
957
|
+
|
|
958
|
+
// --- query ---
|
|
959
|
+
|
|
960
|
+
/**
|
|
961
|
+
* The signal-native read of the cache: an async value for the entry `key`
|
|
962
|
+
* names now. `key` may be a function of signals; when it moves, the value
|
|
963
|
+
* fetches the new key's entry (or shows it at once, if it is cached) and keeps
|
|
964
|
+
* the old value meanwhile (`pending()`). Reading it before the first value
|
|
965
|
+
* lands holds the reader, or suspends its <Suspense>, like any async value;
|
|
966
|
+
* `refresh(q)` fetches the entry again. `fetcher(key, { signal })` gets the
|
|
967
|
+
* key as written.
|
|
968
|
+
*/
|
|
969
|
+
export function query(key, fetcher, options = {}) {
|
|
970
|
+
_enableSuspense();
|
|
971
|
+
const o = observe(PLAIN, key, {
|
|
972
|
+
run: (k, abortSignal) => fetcher(k, { signal: abortSignal }),
|
|
973
|
+
retry: options.retry ?? 1,
|
|
974
|
+
retryDelay: options.retryDelay ?? defaultRetryDelay,
|
|
975
|
+
}, {
|
|
976
|
+
staleTime: options.staleTime,
|
|
977
|
+
gcTime: options.gcTime,
|
|
978
|
+
initialData: options.initialData,
|
|
979
|
+
});
|
|
980
|
+
if (getServerContext() !== null) {
|
|
981
|
+
// A server render reads the key once, and nothing in it changes: the
|
|
982
|
+
// value is the entry's node, which belongs to the render and is in its
|
|
983
|
+
// data channel. It starts now, so sibling queries fetch side by side; a
|
|
984
|
+
// retried render finds it in the render's cache.
|
|
985
|
+
const e = untrack(o.current);
|
|
986
|
+
if (e === null) return _asyncComputed(noop, { value: undefined, track: false });
|
|
987
|
+
// Its first evaluation fetches, unless the render's store had it.
|
|
988
|
+
untrack(() => _asyncStatus(e.node));
|
|
989
|
+
return e.node;
|
|
990
|
+
}
|
|
991
|
+
/** @type {{ e: any, version: number } | null} */
|
|
992
|
+
let seen = null;
|
|
993
|
+
return _asyncComputed(() => {
|
|
994
|
+
const e = o.current();
|
|
995
|
+
if (e === null) {
|
|
996
|
+
seen = null;
|
|
997
|
+
return undefined;
|
|
998
|
+
}
|
|
999
|
+
holdFromRead(o, e);
|
|
1000
|
+
// A run with the same entry at the same version is not a change reaching
|
|
1001
|
+
// this value (every landing bumps the version first): it is a refresh()
|
|
1002
|
+
// of it, or an error boundary's reset. Fetch the entry again.
|
|
1003
|
+
const again = seen !== null && seen.e === e && seen.version === e.version;
|
|
1004
|
+
seen = { e, version: e.version };
|
|
1005
|
+
if (untrack(() => e.node.peek()) === IDLE) {
|
|
1006
|
+
// No data yet (a fetch that landed undefined is data): wait for the
|
|
1007
|
+
// entry's first landing, subscribed to the landing itself rather than to
|
|
1008
|
+
// the node, whose placeholder is not a value to show as pending.
|
|
1009
|
+
e.tick();
|
|
1010
|
+
if (again || (e.flight === null && e.error === undefined)) fetchEntry(e, o);
|
|
1011
|
+
seen.version = e.version;
|
|
1012
|
+
if (e.error !== undefined && e.flight === null) throw e.error;
|
|
1013
|
+
return arrival(e);
|
|
1014
|
+
}
|
|
1015
|
+
if (again) fetchEntry(e, o);
|
|
1016
|
+
seen.version = e.version;
|
|
1017
|
+
const read = attempt(e.node);
|
|
1018
|
+
if (read.waiting !== null) return read.waiting.then(() => settledValue(e));
|
|
1019
|
+
if (read.failed) throw read.value;
|
|
1020
|
+
return read.value;
|
|
1021
|
+
}, null);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// A tracked read of an entry's node that reports, instead of throwing, a value
|
|
1025
|
+
// that is not ready.
|
|
1026
|
+
function attempt(n) {
|
|
1027
|
+
try {
|
|
1028
|
+
return { value: n(), waiting: null, failed: false };
|
|
1029
|
+
} catch (err) {
|
|
1030
|
+
if (_isNotReady(err)) return { value: undefined, waiting: err, failed: false };
|
|
1031
|
+
return { value: err, waiting: null, failed: true };
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
function settledValue(e) {
|
|
1036
|
+
return untrack(() => {
|
|
1037
|
+
const n = e.node;
|
|
1038
|
+
if (_asyncStatus(n) === 'errored') throw _asyncError(n);
|
|
1039
|
+
const v = n.peek();
|
|
1040
|
+
return v === IDLE ? undefined : v;
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
// --- useQuery ---
|
|
1045
|
+
// TanStack Query's shape. `status` is 'idle' (nothing cached, nothing in
|
|
1046
|
+
// flight: a disabled query), 'loading', 'success' or 'error'; `fetchStatus`
|
|
1047
|
+
// is 'fetching' while a request is on the wire. `data()` never suspends.
|
|
511
1048
|
|
|
512
1049
|
export function useQuery(options) {
|
|
513
1050
|
const {
|
|
@@ -515,346 +1052,183 @@ export function useQuery(options) {
|
|
|
515
1052
|
queryFn,
|
|
516
1053
|
enabled = true,
|
|
517
1054
|
staleTime = 0,
|
|
518
|
-
cacheTime
|
|
1055
|
+
cacheTime,
|
|
1056
|
+
gcTime = cacheTime ?? DEFAULT_GC_TIME,
|
|
519
1057
|
refetchOnWindowFocus = true,
|
|
1058
|
+
refetchOnReconnect = true,
|
|
520
1059
|
refetchInterval = false,
|
|
521
1060
|
retry = 3,
|
|
522
|
-
retryDelay =
|
|
1061
|
+
retryDelay = defaultRetryDelay,
|
|
523
1062
|
onSuccess,
|
|
524
1063
|
onError,
|
|
525
1064
|
onSettled,
|
|
526
1065
|
select,
|
|
527
1066
|
placeholderData,
|
|
1067
|
+
keepPreviousData = false,
|
|
1068
|
+
initialData,
|
|
1069
|
+
initialDataUpdatedAt,
|
|
1070
|
+
structuralSharing = true,
|
|
528
1071
|
} = options;
|
|
529
1072
|
|
|
530
|
-
const key = normalizeQueryKey(queryKey);
|
|
531
1073
|
const gate = createGate(enabled);
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
//
|
|
543
|
-
//
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
);
|
|
552
|
-
const fetchStatus = signal('idle');
|
|
553
|
-
|
|
554
|
-
// A settled status only holds while the cache still holds what it settled on.
|
|
555
|
-
// The data lives in a SHARED signal that something this hook never hears
|
|
556
|
-
// about can empty -- clearCache() on logout, a sibling's
|
|
557
|
-
// setQueryData(key, null) -- and a per-hook status signal has no way to
|
|
558
|
-
// notice. That left status 'success' with data() === undefined, which walks
|
|
559
|
-
// the canonical guarded render
|
|
560
|
-
//
|
|
561
|
-
// if (q.isLoading()) return 'Loading...';
|
|
562
|
-
// if (q.isError()) return 'Error';
|
|
563
|
-
// if (q.isIdle()) return 'Idle';
|
|
564
|
-
// return q.data().name;
|
|
565
|
-
//
|
|
566
|
-
// past every guard and into a TypeError, at the one moment (logout) when
|
|
567
|
-
// clearCache is most likely to be called. Deriving keeps status and data
|
|
568
|
-
// moving together whatever emptied the entry, instead of requiring every
|
|
569
|
-
// writer of the shared cache to know about every hook reading it.
|
|
570
|
-
//
|
|
571
|
-
// All four reads are UNCONDITIONAL, and that is load-bearing rather than
|
|
572
|
-
// tidy. Written as `s === 'success' && cacheS() == null` this computed reads
|
|
573
|
-
// the cache only in the success branch, so a re-run that finds any other
|
|
574
|
-
// status reads rawStatus alone -- one dependency -- and the reactive core
|
|
575
|
-
// promotes it to a stable effect that can never subscribe to anything new.
|
|
576
|
-
// See the note on conditional reads above scopedEffect.
|
|
577
|
-
//
|
|
578
|
-
// A query created with `enabled: false` takes exactly that path and an
|
|
579
|
-
// enabled one does not, which is why this looked fixed: 'idle' -> 'loading'
|
|
580
|
-
// (refetch starts) is a one-dependency re-run, where an enabled query goes
|
|
581
|
-
// straight from 'loading' to 'success' in a batch that writes the cache too,
|
|
582
|
-
// and so keeps both dependencies. So after refetch() a disabled query's
|
|
583
|
-
// status was permanently deaf to its own cache, and clearCache() left it
|
|
584
|
-
// reporting 'success' with data() === undefined -- walking the guarded render
|
|
585
|
-
// above into the TypeError this computed was written to prevent, at logout,
|
|
586
|
-
// with the previous user's value still painted on screen.
|
|
587
|
-
const status = computed(() => {
|
|
588
|
-
const s = rawStatus();
|
|
589
|
-
const hasData = cacheS() != null;
|
|
590
|
-
const hasError = error() != null;
|
|
591
|
-
// 'loading' only when something really is on its way to refill the entry.
|
|
592
|
-
// clearCache() starts no request, so reporting 'loading' there would render
|
|
593
|
-
// a spinner that never comes down -- the same defect, moved.
|
|
594
|
-
const refilling = fetchStatus() === 'fetching';
|
|
595
|
-
const lostData = s === 'success' && !hasData;
|
|
596
|
-
const lostError = s === 'error' && !hasError;
|
|
597
|
-
if (lostData || lostError) return refilling ? 'loading' : 'idle';
|
|
598
|
-
return s;
|
|
599
|
-
});
|
|
600
|
-
|
|
601
|
-
let lastFetchTime = 0;
|
|
602
|
-
// The request this hook has in flight, and who asked for it. An AUTOMATIC
|
|
603
|
-
// fetch (mount, focus, polling, invalidation) belongs to the effect below and
|
|
604
|
-
// dies with it; a `manual` one was asked for by application code, and the
|
|
605
|
-
// effect's cleanup must leave it alone. One shared controller meant an
|
|
606
|
-
// unrelated re-render cancelled a button click's refetch(), whose promise
|
|
607
|
-
// then resolved with `undefined`.
|
|
608
|
-
/** @type {{ controller: AbortController, manual: boolean, direction?: string } | null} */
|
|
609
|
-
let inFlight = null;
|
|
610
|
-
let cleanupTimer = null;
|
|
611
|
-
|
|
612
|
-
// See the note on useSWR's revalidate: an invalidation must not be answered
|
|
613
|
-
// from the freshness window, or `invalidateQueries` becomes a no-op for every
|
|
614
|
-
// query with a staleTime.
|
|
615
|
-
//
|
|
616
|
-
// `manual` separates an explicit refetch() from AUTOMATIC fetching (mount,
|
|
617
|
-
// window focus, polling, invalidation). Only the automatic paths are gated by
|
|
618
|
-
// `enabled`: a call from application code is a direct request for data, and
|
|
619
|
-
// gating it left `enabled: false` + "fetch on a button click" with no
|
|
620
|
-
// supported form at all. The gate is peeked, not read reactively, because
|
|
621
|
-
// this function is also called from detached callbacks (a focus handler, an
|
|
622
|
-
// invalidation subscriber) where a tracked read would attach the gate to
|
|
623
|
-
// whatever effect happened to be running; the effect below does the tracked
|
|
624
|
-
// read.
|
|
625
|
-
async function fetchQuery({ force = false, manual = false } = {}) {
|
|
626
|
-
if (!manual && !gate.peek()) return;
|
|
627
|
-
|
|
628
|
-
// Check if data is still fresh
|
|
629
|
-
const now = Date.now();
|
|
630
|
-
if (!force && cacheS.peek() != null && now - lastFetchTime < staleTime) {
|
|
631
|
-
return cacheS.peek();
|
|
1074
|
+
const o = observe(PLAIN, queryKey, {
|
|
1075
|
+
run: (k, abortSignal) => queryFn({ queryKey: asArray(k), signal: abortSignal }),
|
|
1076
|
+
share: sharing(structuralSharing),
|
|
1077
|
+
retry,
|
|
1078
|
+
retryDelay,
|
|
1079
|
+
}, { gate, staleTime, gcTime, initialData, initialDataUpdatedAt, onSuccess, onError, onSettled });
|
|
1080
|
+
if (refetchOnWindowFocus) onWindow(o, ['visibilitychange'], (e) => stale(e, o));
|
|
1081
|
+
if (refetchOnReconnect) onWindow(o, ['online'], (e) => stale(e, o));
|
|
1082
|
+
poll(o, refetchInterval);
|
|
1083
|
+
|
|
1084
|
+
// select(), memoized on its input as TanStack Query does: the same cached
|
|
1085
|
+
// value gives the same selected value, so readers see no change.
|
|
1086
|
+
let selectedFrom = IDLE;
|
|
1087
|
+
let selected;
|
|
1088
|
+
const selectOf = (v) => {
|
|
1089
|
+
if (!select) return v;
|
|
1090
|
+
if (v !== selectedFrom) {
|
|
1091
|
+
selectedFrom = v;
|
|
1092
|
+
selected = select(v);
|
|
632
1093
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
if (cacheS.peek() == null) {
|
|
645
|
-
rawStatus.set('loading');
|
|
1094
|
+
return selected;
|
|
1095
|
+
};
|
|
1096
|
+
const view = () => {
|
|
1097
|
+
const s = stateOf(o);
|
|
1098
|
+
if (s.value != null) return { data: selectOf(s.value), placeholder: false, s };
|
|
1099
|
+
// keepPreviousData (or placeholderData: (previous) => ...): the data of
|
|
1100
|
+
// the key this query named before, while the new one loads.
|
|
1101
|
+
const before = o.previous !== null && o.previous !== s.e ? valueOf(o.previous) : undefined;
|
|
1102
|
+
if (before != null && (keepPreviousData || typeof placeholderData === 'function')) {
|
|
1103
|
+
const previous = select ? select(before) : before;
|
|
1104
|
+
return { data: typeof placeholderData === 'function' ? placeholderData(previous) : previous, placeholder: true, s };
|
|
646
1105
|
}
|
|
1106
|
+
const data = typeof placeholderData === 'function' ? placeholderData(undefined) : placeholderData;
|
|
1107
|
+
return { data, placeholder: data !== undefined, s };
|
|
1108
|
+
};
|
|
1109
|
+
const status = () => {
|
|
1110
|
+
const s = stateOf(o);
|
|
1111
|
+
if (s.error != null) return 'error';
|
|
1112
|
+
if (s.value != null) return 'success';
|
|
1113
|
+
return s.fetching || (s.first && gate.peek()) ? 'loading' : 'idle';
|
|
1114
|
+
};
|
|
647
1115
|
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
if (onSuccess) onSuccess(result);
|
|
664
|
-
if (onSettled) onSettled(result, null);
|
|
665
|
-
|
|
666
|
-
// Schedule cache cleanup (only if no active subscribers).
|
|
667
|
-
//
|
|
668
|
-
// Replaces the previous timer instead of arming another: every
|
|
669
|
-
// successful fetch used to add one and clear none, so a polling query
|
|
670
|
-
// accumulated pending Timeout objects at roughly (fetch rate x cacheTime).
|
|
671
|
-
if (cleanupTimer) clearTimeout(cleanupTimer);
|
|
672
|
-
cleanupTimer = unrefTimer(setTimeout(() => {
|
|
673
|
-
if (Date.now() - lastFetchTime >= cacheTime) {
|
|
674
|
-
const subs = revalidationSubscribers.get(key);
|
|
675
|
-
if (!subs || subs.size === 0) {
|
|
676
|
-
cacheSignals.delete(key);
|
|
677
|
-
errorSignals.delete(key);
|
|
678
|
-
validatingSignals.delete(key);
|
|
679
|
-
cacheTimestamps.delete(key);
|
|
680
|
-
lastFetchTimestamps.delete(key);
|
|
681
|
-
}
|
|
682
|
-
}
|
|
683
|
-
}, cacheTime));
|
|
684
|
-
|
|
685
|
-
return result;
|
|
686
|
-
} catch (e) {
|
|
687
|
-
if (abortSignal.aborted) return;
|
|
688
|
-
attempts++;
|
|
689
|
-
if (attempts < retry) {
|
|
690
|
-
// Abort-aware retry delay: cancel the wait if the component unmounts
|
|
691
|
-
await new Promise((resolve, reject) => {
|
|
692
|
-
const id = unrefTimer(setTimeout(resolve, retryDelay(attempts)));
|
|
693
|
-
abortSignal.addEventListener('abort', () => {
|
|
694
|
-
clearTimeout(id);
|
|
695
|
-
reject(new DOMException('Aborted', 'AbortError'));
|
|
696
|
-
}, { once: true });
|
|
697
|
-
}).catch(e => { if (e.name === 'AbortError') return; throw e; });
|
|
698
|
-
if (abortSignal.aborted) return;
|
|
699
|
-
return attemptFetch();
|
|
700
|
-
}
|
|
701
|
-
|
|
702
|
-
batch(() => {
|
|
703
|
-
error.set(e);
|
|
704
|
-
rawStatus.set('error');
|
|
705
|
-
fetchStatus.set('idle');
|
|
706
|
-
});
|
|
707
|
-
|
|
708
|
-
if (onError) onError(e);
|
|
709
|
-
if (onSettled) onSettled(null, e);
|
|
710
|
-
|
|
711
|
-
throw e;
|
|
712
|
-
}
|
|
713
|
-
}
|
|
1116
|
+
// Each accessor is a computed: a fetch that starts or lands without changing
|
|
1117
|
+
// what one returns (a background refetch of equal data, with structural
|
|
1118
|
+
// sharing) re-runs nothing that reads it. A region that reads data() keeps
|
|
1119
|
+
// what it rendered, as a React component keeps its children's state when
|
|
1120
|
+
// it renders the same elements again.
|
|
1121
|
+
const dataOf = computed(() => view().data);
|
|
1122
|
+
const placeholderOf = computed(() => view().placeholder);
|
|
1123
|
+
const statusOf = computed(status);
|
|
1124
|
+
const errorOf = computed(() => stateOf(o).error);
|
|
1125
|
+
const fetchingOf = computed(() => stateOf(o).fetching);
|
|
1126
|
+
const updatedAtOf = computed(() => {
|
|
1127
|
+
const e = stateOf(o).e;
|
|
1128
|
+
return e !== null ? e.updatedAt : 0;
|
|
1129
|
+
});
|
|
714
1130
|
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
1131
|
+
return {
|
|
1132
|
+
data: () => dataOf(),
|
|
1133
|
+
error: () => errorOf(),
|
|
1134
|
+
status: () => statusOf(),
|
|
1135
|
+
fetchStatus: () => (fetchingOf() ? 'fetching' : 'idle'),
|
|
1136
|
+
isLoading: () => statusOf() === 'loading',
|
|
1137
|
+
isError: () => statusOf() === 'error',
|
|
1138
|
+
isSuccess: () => statusOf() === 'success',
|
|
1139
|
+
isIdle: () => statusOf() === 'idle',
|
|
1140
|
+
isFetching: () => fetchingOf(),
|
|
1141
|
+
isPlaceholderData: () => placeholderOf(),
|
|
1142
|
+
isEnabled: () => gate(),
|
|
1143
|
+
dataUpdatedAt: () => updatedAtOf(),
|
|
1144
|
+
// An explicit request: never gated by `enabled`, never answered from the
|
|
1145
|
+
// freshness window. Resolves with the data it fetched.
|
|
1146
|
+
refetch: () => {
|
|
1147
|
+
const e = untrack(o.current);
|
|
1148
|
+
return e === null ? Promise.resolve(undefined) : refetchOf(e, o);
|
|
1149
|
+
},
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
723
1152
|
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
// The caller's promise then resolves with undefined, which is the right trade
|
|
731
|
-
// against painting a logged-out user's data: clearCache() is a nuke, and
|
|
732
|
-
// useInfiniteQuery has always treated it as one.
|
|
733
|
-
function resetOnClearCache() {
|
|
734
|
-
if (inFlight) {
|
|
735
|
-
inFlight.controller.abort();
|
|
736
|
-
inFlight = null;
|
|
737
|
-
}
|
|
738
|
-
// An aborted fetch deliberately returns without touching either status
|
|
739
|
-
// signal, so nothing else would ever clear them. fetchStatus is the one
|
|
740
|
-
// that must not be left behind: the derived status above reads it to decide
|
|
741
|
-
// whether an emptied entry is being refilled, so 'fetching' would describe
|
|
742
|
-
// a request that no longer exists as a load in progress, and render a
|
|
743
|
-
// spinner that never comes down.
|
|
744
|
-
batch(() => {
|
|
745
|
-
if (rawStatus.peek() !== 'idle') rawStatus.set('idle');
|
|
746
|
-
if (fetchStatus.peek() !== 'idle') fetchStatus.set('idle');
|
|
747
|
-
});
|
|
748
|
-
}
|
|
1153
|
+
// --- useSWR ---
|
|
1154
|
+
// SWR's shape: `data()` is the cached value (or fallbackData, or null),
|
|
1155
|
+
// `isLoading()` is "no data yet and fetching", `isValidating()` is "fetching".
|
|
1156
|
+
// A null, false or throwing key pauses it. `fetcher(key, { signal })` gets the
|
|
1157
|
+
// key as written. A fetch within `dedupingInterval` of the last one answers
|
|
1158
|
+
// a new reader, a focus or a reconnect.
|
|
749
1159
|
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
fetchQuery().catch(() => {});
|
|
763
|
-
} else if (!inFlight?.manual) {
|
|
764
|
-
// Turning a query off settles it. The cleanup below aborted anything the
|
|
765
|
-
// effect itself started, and an aborted request deliberately returns
|
|
766
|
-
// without touching either status signal, so nothing else would ever clear
|
|
767
|
-
// them. A request refetch() owns is still running, though, so this must
|
|
768
|
-
// not report 'idle' over the top of one.
|
|
769
|
-
batch(() => {
|
|
770
|
-
if (rawStatus.peek() === 'loading') rawStatus.set('idle');
|
|
771
|
-
if (fetchStatus.peek() !== 'idle') fetchStatus.set('idle');
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
return () => {
|
|
775
|
-
// Cancel only what this effect started. Cancelling a manual refetch here
|
|
776
|
-
// destroyed it without replacing it, and the caller saw nothing at all.
|
|
777
|
-
if (inFlight && !inFlight.manual) {
|
|
778
|
-
inFlight.controller.abort();
|
|
779
|
-
inFlight = null;
|
|
780
|
-
}
|
|
781
|
-
unsubscribe();
|
|
782
|
-
releaseHandler();
|
|
783
|
-
};
|
|
784
|
-
});
|
|
1160
|
+
export function useSWR(key, fetcher, options = {}) {
|
|
1161
|
+
const {
|
|
1162
|
+
revalidateOnFocus = true,
|
|
1163
|
+
revalidateOnReconnect = true,
|
|
1164
|
+
refreshInterval = 0,
|
|
1165
|
+
dedupingInterval = 2000,
|
|
1166
|
+
fallbackData,
|
|
1167
|
+
keepPreviousData = false,
|
|
1168
|
+
onSuccess,
|
|
1169
|
+
onError,
|
|
1170
|
+
structuralSharing = true,
|
|
1171
|
+
} = options;
|
|
785
1172
|
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
1173
|
+
const o = observe(PLAIN, key, {
|
|
1174
|
+
run: (k, abortSignal) => fetcher(k, { signal: abortSignal }),
|
|
1175
|
+
share: sharing(structuralSharing),
|
|
1176
|
+
retry: 1,
|
|
1177
|
+
retryDelay: defaultRetryDelay,
|
|
1178
|
+
}, { staleTime: dedupingInterval, onSuccess, onError, lenient: true });
|
|
1179
|
+
if (revalidateOnFocus) onWindow(o, ['visibilitychange'], (e) => stale(e, o));
|
|
1180
|
+
if (revalidateOnReconnect) onWindow(o, ['online'], (e) => stale(e, o));
|
|
1181
|
+
poll(o, refreshInterval);
|
|
1182
|
+
|
|
1183
|
+
const data = () => {
|
|
1184
|
+
const s = stateOf(o);
|
|
1185
|
+
if (s.value != null) return s.value;
|
|
1186
|
+
if (keepPreviousData && o.previous !== null && o.previous !== s.e) {
|
|
1187
|
+
const before = valueOf(o.previous);
|
|
1188
|
+
if (before != null) return before;
|
|
792
1189
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
fetchQuery().catch(() => {});
|
|
801
|
-
}
|
|
802
|
-
};
|
|
803
|
-
document.addEventListener('visibilitychange', handler);
|
|
804
|
-
return () => document.removeEventListener('visibilitychange', handler);
|
|
805
|
-
});
|
|
806
|
-
}
|
|
1190
|
+
return fallbackData ?? null;
|
|
1191
|
+
};
|
|
1192
|
+
const revalidate = () => {
|
|
1193
|
+
const e = untrack(o.current);
|
|
1194
|
+
if (e === null) return Promise.resolve(undefined);
|
|
1195
|
+
return e.flight !== null ? outcome(e, e.flight) : refetchOf(e, o);
|
|
1196
|
+
};
|
|
807
1197
|
|
|
808
|
-
//
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
}
|
|
1198
|
+
// Computeds, as useQuery's: a fetch that changes none of them re-runs no reader.
|
|
1199
|
+
const dataOf = computed(data);
|
|
1200
|
+
const errorOf = computed(() => stateOf(o).error);
|
|
1201
|
+
const loadingOf = computed(() => {
|
|
1202
|
+
const s = stateOf(o);
|
|
1203
|
+
return s.value == null && s.fetching;
|
|
1204
|
+
});
|
|
1205
|
+
const validatingOf = computed(() => stateOf(o).fetching);
|
|
817
1206
|
|
|
818
1207
|
return {
|
|
819
|
-
data: () =>
|
|
820
|
-
error: () =>
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
// swallows is a no-op the caller has no way to see, which is the same bug
|
|
835
|
-
// class that made invalidateQueries() a no-op.
|
|
836
|
-
refetch: () => fetchQuery({ force: true, manual: true }),
|
|
1208
|
+
data: () => dataOf(),
|
|
1209
|
+
error: () => errorOf(),
|
|
1210
|
+
isLoading: () => loadingOf(),
|
|
1211
|
+
isValidating: () => validatingOf(),
|
|
1212
|
+
// mutate(data, shouldRevalidate = true): put data in the cache for every
|
|
1213
|
+
// reader of the key, then fetch it again. mutate() alone revalidates.
|
|
1214
|
+
mutate: (...args) => {
|
|
1215
|
+
if (args.length === 0) return revalidate();
|
|
1216
|
+
const [next, shouldRevalidate = true] = args;
|
|
1217
|
+
const e = untrack(o.current);
|
|
1218
|
+
if (e === null) return Promise.resolve(undefined);
|
|
1219
|
+
setEntry(e, typeof next === 'function' ? next(valueOf(e) ?? null) : next);
|
|
1220
|
+
return shouldRevalidate ? refetchOf(e, o) : Promise.resolve(valueOf(e));
|
|
1221
|
+
},
|
|
1222
|
+
revalidate,
|
|
837
1223
|
};
|
|
838
1224
|
}
|
|
839
1225
|
|
|
840
|
-
// --- useInfiniteQuery
|
|
841
|
-
//
|
|
1226
|
+
// --- useInfiniteQuery ---
|
|
1227
|
+
// TanStack Query's shape: `data()` is `{ pages, pageParams }`; pageParams[i]
|
|
1228
|
+
// names pages[i]. The pages are one cache entry: invalidating its key
|
|
1229
|
+
// refetches page one and replaces the list. Explicit calls (fetchNextPage,
|
|
1230
|
+
// refetch) are not gated by `enabled`.
|
|
842
1231
|
|
|
843
|
-
// Every base query option used to fall into an unused `...rest`, so `enabled`,
|
|
844
|
-
// `select`, `retry`, `onSuccess` and the rest were accepted and silently
|
|
845
|
-
// dropped. Those are honoured here.
|
|
846
|
-
//
|
|
847
|
-
// DEFERRED, on purpose: joining the shared cache. `key` is normalized and used
|
|
848
|
-
// for the invalidation subscription, but the pages live in signals local to
|
|
849
|
-
// this hook rather than in cacheSignals, so staleTime/cacheTime, getQueryData,
|
|
850
|
-
// setQueryData and cross-component sharing do not reach an infinite query yet.
|
|
851
|
-
// The shared cache holds ONE value per key, and an infinite query holds a
|
|
852
|
-
// growing list plus its page params; storing that under the same key would
|
|
853
|
-
// collide head-on with a useQuery on the same key (each would serve the other
|
|
854
|
-
// the wrong shape) and hand setQueryData a structure it has no way to describe.
|
|
855
|
-
// That needs a cache entry with a declared kind, which is a design change, not
|
|
856
|
-
// a patch. The options that depend on it (staleTime, cacheTime, placeholderData,
|
|
857
|
-
// refetchOnWindowFocus, refetchInterval) are still not honoured.
|
|
858
1232
|
export function useInfiniteQuery(options) {
|
|
859
1233
|
const {
|
|
860
1234
|
queryKey,
|
|
@@ -863,466 +1237,343 @@ export function useInfiniteQuery(options) {
|
|
|
863
1237
|
getPreviousPageParam,
|
|
864
1238
|
initialPageParam,
|
|
865
1239
|
enabled = true,
|
|
1240
|
+
staleTime = 0,
|
|
1241
|
+
cacheTime,
|
|
1242
|
+
gcTime = cacheTime ?? DEFAULT_GC_TIME,
|
|
1243
|
+
refetchOnWindowFocus = false,
|
|
1244
|
+
refetchInterval = false,
|
|
866
1245
|
select,
|
|
867
1246
|
retry = 3,
|
|
868
|
-
retryDelay =
|
|
1247
|
+
retryDelay = defaultRetryDelay,
|
|
869
1248
|
onSuccess,
|
|
870
1249
|
onError,
|
|
871
1250
|
onSettled,
|
|
872
1251
|
} = options;
|
|
873
1252
|
|
|
874
1253
|
const gate = createGate(enabled);
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
const
|
|
885
|
-
const
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
const
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
// the effect's cleanup must not cancel one just because it re-ran.
|
|
901
|
-
/** @type {{ controller: AbortController, manual: boolean, direction?: string } | null} */
|
|
902
|
-
let inFlight = null;
|
|
903
|
-
|
|
904
|
-
// clearCache() reaches an infinite query through here, because its pages
|
|
905
|
-
// never entered cacheSignals for clearCache to empty. Same nuke: drop the
|
|
906
|
-
// pages, drop the error, and cancel anything in flight -- a request issued
|
|
907
|
-
// for the PREVIOUS user would otherwise land after the clear and put their
|
|
908
|
-
// rows back on screen, which is the whole thing we are preventing.
|
|
909
|
-
function resetOnClearCache() {
|
|
910
|
-
if (inFlight) {
|
|
911
|
-
inFlight.controller.abort();
|
|
912
|
-
inFlight = null;
|
|
913
|
-
}
|
|
914
|
-
batch(() => {
|
|
915
|
-
pages.set([]);
|
|
916
|
-
pageParams.set([]);
|
|
917
|
-
hasNextPage.set(true);
|
|
918
|
-
hasPreviousPage.set(false);
|
|
919
|
-
isFetchingNextPage.set(false);
|
|
920
|
-
isFetchingPreviousPage.set(false);
|
|
921
|
-
error.set(null);
|
|
922
|
-
// Nothing is in flight and the clear started nothing, so 'idle' -- the
|
|
923
|
-
// same honest report useQuery derives for an emptied entry.
|
|
924
|
-
status.set('idle');
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
|
|
928
|
-
// `replace` is a per-call argument, not a flag on the hook. As a flag it was
|
|
929
|
-
// set before the fetch and cleared only on success, so a refetch that aborted
|
|
930
|
-
// or failed left "replace the whole list" armed for whichever fetchNextPage()
|
|
931
|
-
// ran next, which silently deleted every loaded page.
|
|
932
|
-
async function fetchPage(pageParam, direction = 'next', { replace = false, manual = false } = {}) {
|
|
933
|
-
// Supersede the previous page fetch, whoever asked for it.
|
|
934
|
-
if (inFlight) inFlight.controller.abort();
|
|
935
|
-
const controller = new AbortController();
|
|
936
|
-
// `direction` is recorded so the finally below can tell whether the request
|
|
937
|
-
// that replaced this one owns the same loading flag. See the note there.
|
|
938
|
-
inFlight = { controller, manual, direction };
|
|
939
|
-
const { signal: abortSignal } = controller;
|
|
940
|
-
|
|
941
|
-
const loading = direction === 'next' ? isFetchingNextPage : isFetchingPreviousPage;
|
|
942
|
-
loading.set(true);
|
|
943
|
-
// Only the first page is 'loading'. Paging through an existing list keeps
|
|
944
|
-
// status 'success' and reports itself through isFetchingNextPage, so a list
|
|
945
|
-
// does not blink back to a spinner every time it grows.
|
|
946
|
-
if (pages.peek().length === 0) status.set('loading');
|
|
947
|
-
|
|
948
|
-
let attempts = 0;
|
|
949
|
-
|
|
950
|
-
try {
|
|
951
|
-
// Retry loop, with the same accounting as useQuery: `retry` is the total
|
|
952
|
-
// number of attempts, and the wait between them is abort-aware so an
|
|
953
|
-
// unmount cancels the pending retry instead of firing it into a dead
|
|
954
|
-
// component.
|
|
955
|
-
for (;;) {
|
|
956
|
-
try {
|
|
957
|
-
const result = await queryFn({
|
|
958
|
-
queryKey: Array.isArray(queryKey) ? queryKey : [queryKey],
|
|
959
|
-
pageParam,
|
|
960
|
-
signal: abortSignal,
|
|
961
|
-
});
|
|
962
|
-
|
|
963
|
-
if (abortSignal.aborted) return;
|
|
964
|
-
|
|
965
|
-
batch(() => {
|
|
966
|
-
if (replace) {
|
|
967
|
-
// Refetch: replace all pages with fresh first page (SWR pattern —
|
|
968
|
-
// old pages stayed visible during fetch, now swap atomically)
|
|
969
|
-
pages.set([result]);
|
|
970
|
-
pageParams.set([pageParam]);
|
|
971
|
-
} else if (direction === 'next') {
|
|
972
|
-
pages.set([...pages.peek(), result]);
|
|
973
|
-
pageParams.set([...pageParams.peek(), pageParam]);
|
|
974
|
-
} else {
|
|
975
|
-
pages.set([result, ...pages.peek()]);
|
|
976
|
-
pageParams.set([pageParam, ...pageParams.peek()]);
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
const nextParam = getNextPageParam?.(result, pages.peek());
|
|
980
|
-
hasNextPage.set(nextParam !== undefined);
|
|
981
|
-
|
|
982
|
-
if (getPreviousPageParam) {
|
|
983
|
-
const prevParam = getPreviousPageParam(result, pages.peek());
|
|
984
|
-
hasPreviousPage.set(prevParam !== undefined);
|
|
985
|
-
}
|
|
986
|
-
|
|
987
|
-
error.set(null);
|
|
988
|
-
status.set('success');
|
|
989
|
-
});
|
|
990
|
-
|
|
991
|
-
if (onSuccess) onSuccess(result);
|
|
992
|
-
if (onSettled) onSettled(result, null);
|
|
993
|
-
|
|
994
|
-
return result;
|
|
995
|
-
} catch (e) {
|
|
996
|
-
if (abortSignal.aborted) return;
|
|
997
|
-
attempts++;
|
|
998
|
-
if (attempts < retry) {
|
|
999
|
-
// Abort-aware retry delay: cancel the wait if the component unmounts
|
|
1000
|
-
await new Promise((resolve, reject) => {
|
|
1001
|
-
const id = unrefTimer(setTimeout(resolve, retryDelay(attempts)));
|
|
1002
|
-
abortSignal.addEventListener('abort', () => {
|
|
1003
|
-
clearTimeout(id);
|
|
1004
|
-
reject(new DOMException('Aborted', 'AbortError'));
|
|
1005
|
-
}, { once: true });
|
|
1006
|
-
}).catch((err) => { if (err.name === 'AbortError') return; throw err; });
|
|
1007
|
-
if (abortSignal.aborted) return;
|
|
1008
|
-
continue;
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
batch(() => {
|
|
1012
|
-
error.set(e);
|
|
1013
|
-
status.set('error');
|
|
1014
|
-
});
|
|
1015
|
-
|
|
1016
|
-
if (onError) onError(e);
|
|
1017
|
-
if (onSettled) onSettled(null, e);
|
|
1018
|
-
|
|
1019
|
-
throw e;
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
|
-
} finally {
|
|
1023
|
-
// Clear this direction's loading flag unless a LIVE request in the SAME
|
|
1024
|
-
// direction has taken it over.
|
|
1025
|
-
//
|
|
1026
|
-
// `if (!abortSignal.aborted)` alone was too blunt. It exists so that an
|
|
1027
|
-
// aborted fetch cannot report "not fetching" over the top of the fetch
|
|
1028
|
-
// that replaced it, which is only a risk when the replacement uses the
|
|
1029
|
-
// same flag. Every other abort left the flag stuck true with nothing
|
|
1030
|
-
// alive behind it: fetchPreviousPage() over a fetchNextPage() still in
|
|
1031
|
-
// flight left isFetchingNextPage() true for the rest of the page's life,
|
|
1032
|
-
// and so isFetching() with it, which is a "loading more" spinner that
|
|
1033
|
-
// never comes down. The effect's cleanup abort (a gate flip, or the query
|
|
1034
|
-
// function's own signals moving) does the same for whichever direction it
|
|
1035
|
-
// interrupted.
|
|
1036
|
-
const successor = inFlight && inFlight.controller !== controller ? inFlight : null;
|
|
1037
|
-
if (!abortSignal.aborted || !successor || successor.direction !== direction) {
|
|
1038
|
-
loading.set(false);
|
|
1039
|
-
}
|
|
1040
|
-
// Release ownership, unless a newer fetch already superseded this one.
|
|
1041
|
-
if (inFlight && inFlight.controller === controller) inFlight = null;
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
// Explicit call from application code, so never gated by `enabled` (the same
|
|
1046
|
-
// rule as useQuery's refetch). `manual` distinguishes the public refetch()
|
|
1047
|
-
// from the invalidation subscriber below, which is automatic fetching aimed
|
|
1048
|
-
// at a key and is owned by the effect.
|
|
1049
|
-
function refetchAll({ manual = false } = {}) {
|
|
1050
|
-
// Keep old pages visible during refetch (SWR pattern).
|
|
1051
|
-
// fetchPage swaps them atomically when the data arrives.
|
|
1052
|
-
return fetchPage(initialPageParam, 'next', { replace: true, manual });
|
|
1053
|
-
}
|
|
1054
|
-
|
|
1055
|
-
const view = computed(() => {
|
|
1056
|
-
const raw = { pages: pages(), pageParams: pageParams() };
|
|
1057
|
-
return select ? select(raw) : raw;
|
|
1058
|
-
});
|
|
1059
|
-
|
|
1060
|
-
// Initial fetch, plus the invalidation subscription for this key. See the
|
|
1061
|
-
// matching comment in useQuery for why the subscription lives INSIDE the
|
|
1062
|
-
// effect.
|
|
1063
|
-
scopedEffect(() => {
|
|
1064
|
-
// The normalized key was computed and then never used, so an infinite query
|
|
1065
|
-
// was invisible to invalidateQueries(). Refetching from the first page is
|
|
1066
|
-
// the only coherent answer for a list whose later pages may no longer exist
|
|
1067
|
-
// once the data behind it changed.
|
|
1068
|
-
const unsubscribe = subscribeToKey(key, () => {
|
|
1069
|
-
if (gate.peek()) refetchAll().catch(() => {});
|
|
1070
|
-
});
|
|
1071
|
-
const releaseHandler = registerClearCacheHandler(resetOnClearCache);
|
|
1072
|
-
// Tracked read of the MIRRORED gate: this effect re-runs when the gate
|
|
1073
|
-
// actually flips, not whenever some unrelated signal a gate thunk happens
|
|
1074
|
-
// to touch moves. See createGate.
|
|
1075
|
-
if (gate()) {
|
|
1076
|
-
// `replace`, because a re-run of this effect means an input to page one
|
|
1077
|
-
// changed (the query function read a signal that moved, or `enabled`
|
|
1078
|
-
// flipped). Appending in that case left a stale copy of page one sitting
|
|
1079
|
-
// above the fresh one, forever. On the first run the list is empty, so
|
|
1080
|
-
// replacing and appending are the same thing.
|
|
1081
|
-
fetchPage(initialPageParam, 'next', { replace: true }).catch(() => {});
|
|
1082
|
-
} else if (!inFlight?.manual) {
|
|
1083
|
-
// Turning it off settles it: the cleanup below aborted anything the
|
|
1084
|
-
// effect started, and an aborted page fetch returns without clearing its
|
|
1085
|
-
// own loading flag. A page an explicit call is still fetching is left
|
|
1086
|
-
// alone, and so is the status describing it.
|
|
1087
|
-
batch(() => {
|
|
1088
|
-
if (status.peek() === 'loading') status.set('idle');
|
|
1089
|
-
if (isFetchingNextPage.peek()) isFetchingNextPage.set(false);
|
|
1090
|
-
if (isFetchingPreviousPage.peek()) isFetchingPreviousPage.set(false);
|
|
1091
|
-
});
|
|
1092
|
-
}
|
|
1093
|
-
return () => {
|
|
1094
|
-
// Cancel only what this effect started; see the matching note in useQuery.
|
|
1095
|
-
if (inFlight && !inFlight.manual) {
|
|
1096
|
-
inFlight.controller.abort();
|
|
1097
|
-
inFlight = null;
|
|
1098
|
-
}
|
|
1099
|
-
unsubscribe();
|
|
1100
|
-
releaseHandler();
|
|
1101
|
-
};
|
|
1102
|
-
});
|
|
1103
|
-
|
|
1104
|
-
// Unmount cancels everything, including a page fetch the application asked
|
|
1105
|
-
// for that the effect's own cleanup spares.
|
|
1106
|
-
onComponentDispose(() => {
|
|
1107
|
-
if (inFlight) {
|
|
1108
|
-
inFlight.controller.abort();
|
|
1109
|
-
inFlight = null;
|
|
1110
|
-
}
|
|
1111
|
-
});
|
|
1254
|
+
const o = observe(INFINITE, queryKey, {
|
|
1255
|
+
run: (k, pageParam, abortSignal) => queryFn({ queryKey: asArray(k), pageParam, signal: abortSignal }),
|
|
1256
|
+
retry,
|
|
1257
|
+
retryDelay,
|
|
1258
|
+
initialPageParam,
|
|
1259
|
+
}, { gate, staleTime, gcTime, onSuccess, onError, onSettled });
|
|
1260
|
+
if (refetchOnWindowFocus) onWindow(o, ['visibilitychange'], (e) => stale(e, o));
|
|
1261
|
+
poll(o, refetchInterval);
|
|
1262
|
+
|
|
1263
|
+
const pagesOf = (s) => (s.value != null ? s.value : { pages: [], pageParams: [] });
|
|
1264
|
+
const status = () => {
|
|
1265
|
+
const s = stateOf(o);
|
|
1266
|
+
if (s.error != null) return 'error';
|
|
1267
|
+
if (s.value != null && s.value.pages.length > 0) return 'success';
|
|
1268
|
+
return s.fetching ? 'loading' : 'idle';
|
|
1269
|
+
};
|
|
1270
|
+
const direction = (dir) => {
|
|
1271
|
+
const s = stateOf(o);
|
|
1272
|
+
return s.fetching && s.e !== null && s.e.dir() === dir;
|
|
1273
|
+
};
|
|
1274
|
+
const page = (place, dir, param) => {
|
|
1275
|
+
const e = untrack(o.current);
|
|
1276
|
+
return e === null ? Promise.resolve(undefined) : refetchOf(e, o, { place, dir, param });
|
|
1277
|
+
};
|
|
1278
|
+
const first = (dir) => page('first', dir, initialPageParam);
|
|
1112
1279
|
|
|
1113
1280
|
return {
|
|
1114
|
-
data: () =>
|
|
1115
|
-
|
|
1116
|
-
|
|
1281
|
+
data: () => {
|
|
1282
|
+
const data = pagesOf(stateOf(o));
|
|
1283
|
+
return select ? select(data) : data;
|
|
1284
|
+
},
|
|
1285
|
+
error: () => stateOf(o).error,
|
|
1286
|
+
status,
|
|
1117
1287
|
isLoading: () => status() === 'loading',
|
|
1118
1288
|
isError: () => status() === 'error',
|
|
1119
1289
|
isSuccess: () => status() === 'success',
|
|
1120
1290
|
isIdle: () => status() === 'idle',
|
|
1121
|
-
isFetching: () =>
|
|
1291
|
+
isFetching: () => stateOf(o).fetching,
|
|
1122
1292
|
isEnabled: () => gate(),
|
|
1123
|
-
hasNextPage: () =>
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
//
|
|
1134
|
-
//
|
|
1135
|
-
// query's state is always the empty list, and the empty list had no last
|
|
1136
|
-
// page to derive a param from. So they called the user's callback with
|
|
1137
|
-
// `undefined`, and the documented callback shape
|
|
1138
|
-
// `(lastPage) => lastPage.nextCursor` throws on it -- while a defensive
|
|
1139
|
-
// `lastPage?.nextCursor` returns undefined and made the call a silent
|
|
1140
|
-
// no-op that fetched nothing. Either way refetch() was the only thing that
|
|
1141
|
-
// could load a disabled list, so "explicit calls run either way" was true
|
|
1142
|
-
// of one of the three. There is exactly one page it can mean here, and it
|
|
1143
|
-
// is the first one; asking a getNextPageParam what follows a page that does
|
|
1144
|
-
// not exist is not a question it can answer.
|
|
1145
|
-
//
|
|
1146
|
-
// `replace`, because this IS page one: it must land as the whole list, not
|
|
1147
|
-
// as an append onto whatever a racing call left behind.
|
|
1293
|
+
hasNextPage: () => {
|
|
1294
|
+
const { pages } = pagesOf(stateOf(o));
|
|
1295
|
+
return pages.length === 0 || (getNextPageParam ? getNextPageParam(pages[pages.length - 1], pages) !== undefined : false);
|
|
1296
|
+
},
|
|
1297
|
+
hasPreviousPage: () => {
|
|
1298
|
+
const { pages } = pagesOf(stateOf(o));
|
|
1299
|
+
return pages.length > 0 && getPreviousPageParam ? getPreviousPageParam(pages[0], pages) !== undefined : false;
|
|
1300
|
+
},
|
|
1301
|
+
isFetchingNextPage: () => direction('next'),
|
|
1302
|
+
isFetchingPreviousPage: () => direction('previous'),
|
|
1303
|
+
// An empty list has no last page to ask getNextPageParam about: the next
|
|
1304
|
+
// page of nothing is the first page.
|
|
1148
1305
|
fetchNextPage: async () => {
|
|
1149
|
-
const
|
|
1150
|
-
if (
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
const nextParam = getNextPageParam?.(loaded[loaded.length - 1], loaded);
|
|
1154
|
-
if (nextParam !== undefined) {
|
|
1155
|
-
return fetchPage(nextParam, 'next', { manual: true });
|
|
1156
|
-
}
|
|
1306
|
+
const { pages } = pagesOf(untrack(() => stateOf(o)));
|
|
1307
|
+
if (pages.length === 0) return first('next');
|
|
1308
|
+
const param = getNextPageParam?.(pages[pages.length - 1], pages);
|
|
1309
|
+
if (param !== undefined) return page('next', 'next', param);
|
|
1157
1310
|
},
|
|
1158
1311
|
fetchPreviousPage: async () => {
|
|
1159
|
-
const
|
|
1160
|
-
if (
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1312
|
+
const { pages } = pagesOf(untrack(() => stateOf(o)));
|
|
1313
|
+
if (pages.length === 0) return first('previous');
|
|
1314
|
+
const param = getPreviousPageParam?.(pages[0], pages);
|
|
1315
|
+
if (param !== undefined) return page('previous', 'previous', param);
|
|
1316
|
+
},
|
|
1317
|
+
refetch: () => first('next'),
|
|
1318
|
+
};
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// --- useFetch ---
|
|
1322
|
+
// One URL's JSON, from the cache. `url` may be a function of signals.
|
|
1323
|
+
|
|
1324
|
+
export function useFetch(url, options = {}) {
|
|
1325
|
+
const {
|
|
1326
|
+
method = 'GET',
|
|
1327
|
+
body,
|
|
1328
|
+
headers = {},
|
|
1329
|
+
transform = (data) => data,
|
|
1330
|
+
initialData = null,
|
|
1331
|
+
fetch: request = globalThis.fetch,
|
|
1332
|
+
} = options;
|
|
1333
|
+
const keyOf = (u) => (u == null ? null : ['what:fetch', method, u, body ?? null]);
|
|
1334
|
+
const key = typeof url === 'function' ? () => keyOf(url()) : keyOf(url);
|
|
1335
|
+
const o = observe(PLAIN, key, {
|
|
1336
|
+
run: async (k, abortSignal) => {
|
|
1337
|
+
const response = await request(k[2], {
|
|
1338
|
+
method,
|
|
1339
|
+
headers: { 'Content-Type': 'application/json', ...headers },
|
|
1340
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
1341
|
+
signal: abortSignal,
|
|
1342
|
+
});
|
|
1343
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
|
1344
|
+
return transform(await response.json());
|
|
1345
|
+
},
|
|
1346
|
+
retry: 1,
|
|
1347
|
+
retryDelay: defaultRetryDelay,
|
|
1348
|
+
}, {});
|
|
1349
|
+
return {
|
|
1350
|
+
data: () => stateOf(o).value ?? initialData,
|
|
1351
|
+
error: () => stateOf(o).error,
|
|
1352
|
+
isLoading: () => {
|
|
1353
|
+
const s = stateOf(o);
|
|
1354
|
+
return s.fetching || (s.e !== null && s.value === undefined && s.error === null && s.e.fetches === 0);
|
|
1355
|
+
},
|
|
1356
|
+
// Never rejects: a failure shows in error().
|
|
1357
|
+
refetch: () => {
|
|
1358
|
+
const e = untrack(o.current);
|
|
1359
|
+
return e === null ? Promise.resolve() : refetchOf(e, o).then(noop, noop);
|
|
1360
|
+
},
|
|
1361
|
+
mutate: (next) => {
|
|
1362
|
+
const e = untrack(o.current);
|
|
1363
|
+
if (e !== null) setEntry(e, next);
|
|
1169
1364
|
},
|
|
1170
|
-
refetch: () => refetchAll({ manual: true }),
|
|
1171
1365
|
};
|
|
1172
1366
|
}
|
|
1173
1367
|
|
|
1174
|
-
// ---
|
|
1368
|
+
// --- The cache, whichever hook reads it ---
|
|
1175
1369
|
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
const
|
|
1181
|
-
|
|
1182
|
-
return keys;
|
|
1370
|
+
function allEntries() {
|
|
1371
|
+
const ctx = getServerContext();
|
|
1372
|
+
const caches = ctx === null ? clientCache : (serverCaches.get(ctx) || []);
|
|
1373
|
+
const out = [];
|
|
1374
|
+
for (const cache of caches) for (const e of cache.values()) out.push(e);
|
|
1375
|
+
return out;
|
|
1183
1376
|
}
|
|
1184
1377
|
|
|
1185
|
-
|
|
1186
|
-
const
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
//
|
|
1191
|
-
//
|
|
1192
|
-
|
|
1193
|
-
// below already looks in both places.
|
|
1194
|
-
for (const key of allKnownKeys()) {
|
|
1195
|
-
if (keyOrPredicate(key)) keysToInvalidate.push(key);
|
|
1196
|
-
}
|
|
1197
|
-
} else if (Array.isArray(keyOrPredicate) && !exact) {
|
|
1198
|
-
// An array key is a PREFIX: invalidateQueries(['todos']) invalidates
|
|
1199
|
-
// ['todos', 1] and ['todos', {done: true}] too, which is what the shape
|
|
1200
|
-
// implies and what every peer library does. Matching is on segment
|
|
1201
|
-
// boundaries, so ['todo'] never matches 'todos'.
|
|
1202
|
-
const prefix = normalizeQueryKey(keyOrPredicate);
|
|
1378
|
+
function matching(target, exact) {
|
|
1379
|
+
const out = [];
|
|
1380
|
+
if (typeof target === 'function') {
|
|
1381
|
+
for (const e of allEntries()) if (target(e.hash)) out.push(e);
|
|
1382
|
+
} else if (Array.isArray(target) && !exact) {
|
|
1383
|
+
// An array key is a prefix, on segment boundaries: ['todos'] matches
|
|
1384
|
+
// ['todos', 1], never 'todosx'.
|
|
1385
|
+
const prefix = normalizeQueryKey(target);
|
|
1203
1386
|
const scoped = prefix + ':';
|
|
1204
|
-
for (const
|
|
1205
|
-
if (key === prefix || (typeof key === 'string' && key.startsWith(scoped))) {
|
|
1206
|
-
keysToInvalidate.push(key);
|
|
1207
|
-
}
|
|
1208
|
-
}
|
|
1387
|
+
for (const e of allEntries()) if (e.hash === prefix || e.hash.startsWith(scoped)) out.push(e);
|
|
1209
1388
|
} else {
|
|
1210
|
-
|
|
1389
|
+
const exactKey = normalizeQueryKey(target);
|
|
1390
|
+
for (const e of allEntries()) if (e.hash === exactKey) out.push(e);
|
|
1211
1391
|
}
|
|
1392
|
+
return out;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
// The active reader that attached last: an invalidation fetches as it.
|
|
1396
|
+
function lastActive(e) {
|
|
1397
|
+
let last = null;
|
|
1398
|
+
// Among the readers that read it now: one whose key has just moved to
|
|
1399
|
+
// another entry still holds this one until its effect runs.
|
|
1400
|
+
for (const o of e.observers) if (o.active() && untrack(o.hash) === e.hash) last = o;
|
|
1401
|
+
return last;
|
|
1402
|
+
}
|
|
1212
1403
|
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
if (
|
|
1224
|
-
|
|
1404
|
+
// Mark an entry stale and fetch it now if something shows it; a `hard`
|
|
1405
|
+
// invalidation empties it first (a request already in flight still refills
|
|
1406
|
+
// it). Resolves when the refetch has landed.
|
|
1407
|
+
function invalidateEntry(e, hard) {
|
|
1408
|
+
e.updatedAt = 0;
|
|
1409
|
+
if (hard) {
|
|
1410
|
+
const f = e.flight;
|
|
1411
|
+
e.version++;
|
|
1412
|
+
e.error = undefined;
|
|
1413
|
+
_setAsyncValue(e.node, null);
|
|
1414
|
+
if (f !== null && !f.dead) {
|
|
1415
|
+
e.next = ADOPT;
|
|
1416
|
+
refreshNode(e);
|
|
1417
|
+
e.next = 0;
|
|
1225
1418
|
}
|
|
1226
1419
|
}
|
|
1420
|
+
const by = lastActive(e);
|
|
1421
|
+
if (by === null) return e.flight !== null ? outcome(e, e.flight).then(noop, noop) : Promise.resolve();
|
|
1422
|
+
if (hard && e.flight !== null) return outcome(e, e.flight).then(noop, noop);
|
|
1423
|
+
return refetchOf(e, by).then(noop, noop);
|
|
1227
1424
|
}
|
|
1228
1425
|
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Mark the entries `keyOrPredicate` names stale, and fetch again those
|
|
1428
|
+
* something shows (inside a transition, the refetch joins it). An array key is
|
|
1429
|
+
* a prefix unless `exact`; a predicate gets each normalized key. `hard`
|
|
1430
|
+
* empties them first. Resolves when the refetches have landed; never rejects.
|
|
1431
|
+
*/
|
|
1432
|
+
export function invalidateQueries(keyOrPredicate, options = {}) {
|
|
1433
|
+
const { hard = false, exact = false } = options;
|
|
1434
|
+
const entries = matching(keyOrPredicate, exact);
|
|
1435
|
+
// Server actions record the normalized cache entries they actually touched.
|
|
1436
|
+
if (__DEV__ && arguments[2]) {
|
|
1437
|
+
for (const e of entries) arguments[2].add(e.hash);
|
|
1438
|
+
}
|
|
1439
|
+
return Promise.all(entries.map((e) => invalidateEntry(e, hard))).then(noop);
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
const revalidationCallbacks = new Map();
|
|
1443
|
+
|
|
1444
|
+
/**
|
|
1445
|
+
* Call `callback` whenever `invalidatePath(path)` runs (a server action that
|
|
1446
|
+
* revalidates `path`). Returns the unsubscribe.
|
|
1447
|
+
*/
|
|
1448
|
+
export function onRevalidate(path, callback) {
|
|
1449
|
+
if (!revalidationCallbacks.has(path)) revalidationCallbacks.set(path, new Set());
|
|
1450
|
+
revalidationCallbacks.get(path).add(callback);
|
|
1451
|
+
return () => {
|
|
1452
|
+
revalidationCallbacks.get(path)?.delete(callback);
|
|
1453
|
+
};
|
|
1237
1454
|
}
|
|
1238
1455
|
|
|
1456
|
+
/**
|
|
1457
|
+
* The client side of a revalidated path: the entries read on `path` (the
|
|
1458
|
+
* route data and every query read while the page was at that path) are
|
|
1459
|
+
* invalidated, and the onRevalidate callbacks for it run. Resolves when the
|
|
1460
|
+
* refetches have landed.
|
|
1461
|
+
*/
|
|
1462
|
+
export function invalidatePath(path) {
|
|
1463
|
+
const callbacks = revalidationCallbacks.get(path);
|
|
1464
|
+
if (callbacks) {
|
|
1465
|
+
for (const cb of callbacks) {
|
|
1466
|
+
try { cb(); } catch (e) { console.error('[what] Revalidation error:', e); }
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
const waits = [];
|
|
1470
|
+
for (const e of allEntries()) if (e.paths !== null && e.paths.has(path)) waits.push(invalidateEntry(e, false));
|
|
1471
|
+
return Promise.all(waits).then(noop);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
/**
|
|
1475
|
+
* Fetch `key` into the cache unless it holds a value fresher than
|
|
1476
|
+
* `staleTime`, and resolve with it. Rejects with a failed fetch's error.
|
|
1477
|
+
*/
|
|
1478
|
+
export function prefetchQuery(key, fetcher, options = {}) {
|
|
1479
|
+
key = keyParts(key);
|
|
1480
|
+
const e = entryFor(PLAIN, normalizeQueryKey(key), key, null);
|
|
1481
|
+
// Its fetch calls its own fetcher with its own key, whoever else reads the
|
|
1482
|
+
// entry; with no reader, the cache's own fetches use them too.
|
|
1483
|
+
const own = { conf: { run: (k, abortSignal) => fetcher(k, { signal: abortSignal }), share: sharing(options.structuralSharing ?? true), retry: options.retry ?? 1, retryDelay: defaultRetryDelay }, key, keep: true };
|
|
1484
|
+
if (e.observers.size === 0) {
|
|
1485
|
+
e.conf = own.conf;
|
|
1486
|
+
e.key = key;
|
|
1487
|
+
}
|
|
1488
|
+
const v = valueOf(e);
|
|
1489
|
+
let done;
|
|
1490
|
+
if (e.flight !== null) {
|
|
1491
|
+
// It joins the fetch in flight, which then runs to completion for it.
|
|
1492
|
+
e.flight.keep = true;
|
|
1493
|
+
done = outcome(e, e.flight);
|
|
1494
|
+
} else if (v !== undefined && e.error === undefined && Date.now() - e.updatedAt <= (options.staleTime ?? 0)) done = Promise.resolve(v);
|
|
1495
|
+
else {
|
|
1496
|
+
const refreshed = fetchEntry(e, own);
|
|
1497
|
+
// A synchronous throw already ended the flight. The node's refresh
|
|
1498
|
+
// promise carries its error even when the cache still has an older value.
|
|
1499
|
+
done = e.flight !== null ? outcome(e, e.flight) : refreshed;
|
|
1500
|
+
}
|
|
1501
|
+
armGc(e);
|
|
1502
|
+
return done;
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
/** Put `updater` (a value, or a function of the current one) in the cache now. */
|
|
1239
1506
|
export function setQueryData(key, updater) {
|
|
1240
|
-
key =
|
|
1241
|
-
const
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
cacheTimestamps.set(key, Date.now());
|
|
1507
|
+
key = keyParts(key);
|
|
1508
|
+
const e = entryFor(PLAIN, normalizeQueryKey(key), key, null);
|
|
1509
|
+
setEntry(e, typeof updater === 'function' ? updater(valueOf(e)) : updater);
|
|
1510
|
+
armGc(e);
|
|
1245
1511
|
}
|
|
1246
1512
|
|
|
1513
|
+
/** The cached value: undefined for a key with nothing cached, null for one emptied by a hard invalidation. */
|
|
1247
1514
|
export function getQueryData(key) {
|
|
1248
|
-
|
|
1249
|
-
return
|
|
1515
|
+
const e = cacheOf(PLAIN).get(normalizeQueryKey(key));
|
|
1516
|
+
return e === undefined ? undefined : valueOf(e);
|
|
1250
1517
|
}
|
|
1251
1518
|
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
// logout), and the next getCacheSignal() for that key minted a FRESH signal, so
|
|
1259
|
-
// every later write (setQueryData, a sibling component's fetch, prefetchQuery)
|
|
1260
|
-
// landed somewhere the mounted component was not reading. That contradicts the
|
|
1261
|
-
// documented promise that components sharing a key share one set of signals.
|
|
1262
|
-
//
|
|
1263
|
-
// So: every key is EMPTIED IN PLACE, which is the only write that reaches what
|
|
1264
|
-
// is currently on screen. It is emptied to `undefined`, not `null`, so the
|
|
1265
|
-
// entry reads as ABSENT afterwards: getQueryData() answers `undefined` for a
|
|
1266
|
-
// cleared key whether or not the object had to be kept alive for a consumer.
|
|
1267
|
-
// That matters because "is anything still reading this?" is a guess, and it is
|
|
1268
|
-
// a wrong one for a hook created OUTSIDE a component (a module-scope store
|
|
1269
|
-
// query is never disposed, so its subscription is immortal); callers have no
|
|
1270
|
-
// business being able to tell those two cases apart.
|
|
1271
|
-
//
|
|
1272
|
-
// Dropping the entry is then purely about reclaiming memory, and the guess is
|
|
1273
|
-
// free to be wrong: a key whose emptied signals are kept reads exactly like one
|
|
1274
|
-
// whose entry went away.
|
|
1275
|
-
//
|
|
1276
|
-
// Deliberately NOT cleared: revalidationSubscribers. A subscriber is the live
|
|
1277
|
-
// wiring between a mounted component and its key; dropping it would deafen
|
|
1278
|
-
// every mounted query to invalidateQueries() forever, which is the same
|
|
1279
|
-
// detachment bug in the other channel. Subscriptions are owned by the effect
|
|
1280
|
-
// that created them and are released on unmount.
|
|
1519
|
+
/**
|
|
1520
|
+
* Empty the cache (logout). What is in flight is dropped, so no response
|
|
1521
|
+
* requested before the clear lands after it; entries something shows stay
|
|
1522
|
+
* attached to their readers, empty; the rest are forgotten. The page's
|
|
1523
|
+
* server data is not adopted again.
|
|
1524
|
+
*/
|
|
1281
1525
|
export function clearCache() {
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
cacheTimestamps.set(key, Date.now());
|
|
1291
|
-
} else {
|
|
1292
|
-
cacheSignals.delete(key);
|
|
1293
|
-
errorSignals.delete(key);
|
|
1294
|
-
validatingSignals.delete(key);
|
|
1295
|
-
cacheTimestamps.delete(key);
|
|
1296
|
-
}
|
|
1526
|
+
channelOpen = false;
|
|
1527
|
+
for (const e of allEntries()) {
|
|
1528
|
+
if (e.observers.size > 0) {
|
|
1529
|
+
e.error = undefined;
|
|
1530
|
+
e.updatedAt = 0;
|
|
1531
|
+
commitValue(e, IDLE);
|
|
1532
|
+
} else {
|
|
1533
|
+
dropEntry(e);
|
|
1297
1534
|
}
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1298
1537
|
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
inFlightRequests.clear();
|
|
1310
|
-
keyEpochs.clear();
|
|
1538
|
+
function messageOf(error) {
|
|
1539
|
+
return error == null ? null : String((error && error.message) || error);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
function statusOf(e) {
|
|
1543
|
+
const status = _asyncStatus(e.node);
|
|
1544
|
+
if (status === 'errored') return 'error';
|
|
1545
|
+
const value = valueOf(e);
|
|
1546
|
+
if (status === 'pending' || status === 'unresolved') return value === undefined || value === null ? 'loading' : 'refreshing';
|
|
1547
|
+
return value === undefined || value === null ? 'idle' : 'success';
|
|
1311
1548
|
}
|
|
1312
1549
|
|
|
1313
1550
|
/**
|
|
1314
|
-
*
|
|
1315
|
-
*
|
|
1551
|
+
* @internal The cache for devtools (what_cache): each entry's key, kind,
|
|
1552
|
+
* status, value, error, readers, last fetch and how often its value changed.
|
|
1316
1553
|
*/
|
|
1317
1554
|
export function __getCacheSnapshot() {
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1555
|
+
return untrack(() => allEntries().map((e) => ({
|
|
1556
|
+
key: e.hash,
|
|
1557
|
+
kind: e.kind === INFINITE ? 'infinite' : 'query',
|
|
1558
|
+
status: statusOf(e),
|
|
1559
|
+
data: valueOf(e),
|
|
1560
|
+
error: messageOf(e.error !== undefined ? e.error : (_asyncStatus(e.node) === 'errored' ? _asyncError(e.node) : null)),
|
|
1561
|
+
isValidating: e.flight !== null,
|
|
1562
|
+
observers: e.observers.size,
|
|
1563
|
+
updatedAt: e.updatedAt || null,
|
|
1564
|
+
fetches: e.fetches,
|
|
1565
|
+
lastFetch: e.last,
|
|
1566
|
+
version: e.version,
|
|
1567
|
+
paths: e.paths !== null ? [...e.paths] : [],
|
|
1568
|
+
})));
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/**
|
|
1572
|
+
* @internal what_invalidate_cache: invalidate the entries under `key` (all of
|
|
1573
|
+
* them when it is omitted) and report how many matched.
|
|
1574
|
+
*/
|
|
1575
|
+
export function __invalidateFromDevtools(key) {
|
|
1576
|
+
const entries = key == null ? allEntries() : matching(key, false);
|
|
1577
|
+
for (const e of entries) invalidateEntry(e, false);
|
|
1578
|
+
return entries.map((e) => e.hash);
|
|
1328
1579
|
}
|