@opentf/afw 0.38.0 → 0.40.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/core/fn-codec.js +9 -0
- package/core/route.d.ts +33 -0
- package/core/route.js +12 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/jsx-runtime.d.ts +46 -2
- package/macros.d.ts +13 -0
- package/package.json +1 -1
- package/runtime/dom.d.ts +2 -0
- package/runtime/dom.js +57 -8
- package/runtime/error-boundary.js +11 -1
- package/runtime/hmr.js +99 -10
- package/runtime/hydrate.d.ts +4 -0
- package/runtime/hydrate.js +44 -0
- package/runtime/index.d.ts +1 -0
- package/runtime/index.js +1 -0
- package/runtime/invalidate.d.ts +7 -4
- package/runtime/invalidate.js +150 -38
- package/runtime/mutate.d.ts +16 -0
- package/runtime/mutate.js +79 -0
- package/runtime/portal.js +3 -1
- package/runtime/query-cache.js +265 -0
- package/runtime/resource.d.ts +24 -0
- package/runtime/resource.js +203 -44
- package/runtime/revalidate.js +39 -0
- package/runtime/route-data.d.ts +9 -3
- package/runtime/route-data.js +28 -7
- package/runtime/route-match.js +29 -4
- package/runtime/router.d.ts +9 -0
- package/runtime/router.js +93 -8
- package/runtime/server-function.js +78 -8
- package/server/index.d.ts +25 -2
- package/server/index.js +2 -1
- package/server/render.js +32 -7
- package/server/server-functions.js +101 -4
- package/server/ssg-runtime.js +32 -0
package/runtime/invalidate.js
CHANGED
|
@@ -3,32 +3,51 @@
|
|
|
3
3
|
//
|
|
4
4
|
// const todos = resource(() => listTodos({ done: false }));
|
|
5
5
|
// await addTodo({ title });
|
|
6
|
-
// invalidate(listTodos);
|
|
7
|
-
// invalidate();
|
|
6
|
+
// invalidate(listTodos); // every live resource that called listTodos
|
|
7
|
+
// invalidate(getTodo, { id: 1 }); // only those that called getTodo({ id: 1 })
|
|
8
|
+
// invalidate(); // every live resource, and the page's loader data
|
|
8
9
|
//
|
|
9
|
-
// A resource records the server
|
|
10
|
-
// synchronous part, which is where `() => listTodos(args)` calls them). A fetcher
|
|
11
|
-
//
|
|
10
|
+
// A resource records the server function calls its fetcher makes while it starts (the
|
|
11
|
+
// synchronous part, which is where `() => listTodos(args)` calls them). A fetcher that
|
|
12
|
+
// calls one after an `await` names it with `resource(fn, { invalidatedBy: [...] })`.
|
|
13
|
+
//
|
|
14
|
+
// Cached entries (query-cache.js) are marked stale too, so a view that is not on
|
|
15
|
+
// screen fetches again when it next mounts instead of showing the old data.
|
|
12
16
|
//
|
|
13
17
|
// Browser only: on the server nothing is live, and `invalidate()` resolves at once.
|
|
14
18
|
|
|
19
|
+
import { callKey, endpointOfKey, markStale, peek } from "./query-cache.js";
|
|
20
|
+
|
|
15
21
|
const byEndpoint = new Map(); // endpoint → Set of live resource entries
|
|
22
|
+
const byKey = new Map(); // call key → Set of live resource entries
|
|
23
|
+
// endpoint → resources that name it in `invalidatedBy`: they cannot know the input, so
|
|
24
|
+
// any call of it refetches them.
|
|
25
|
+
const byNamed = new Map();
|
|
16
26
|
const live = new Set(); // every live resource entry
|
|
17
|
-
let tracking = null; //
|
|
27
|
+
let tracking = null; // what a starting fetcher calls: { endpoints, keys, staleTime }
|
|
18
28
|
let refreshRoute = null; // the router's loader-data reload, once an app is mounted
|
|
19
29
|
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Record a server function call by the fetcher that is starting (the browser stub).
|
|
32
|
+
* Returns the starting resource's `staleTime`, or undefined outside a resource.
|
|
33
|
+
*/
|
|
34
|
+
export function trackServerCall(endpoint, key) {
|
|
35
|
+
if (!tracking) return undefined;
|
|
36
|
+
tracking.endpoints.add(endpoint);
|
|
37
|
+
if (key) tracking.keys.add(key);
|
|
38
|
+
return tracking.staleTime;
|
|
23
39
|
}
|
|
24
40
|
|
|
25
|
-
/**
|
|
26
|
-
|
|
41
|
+
/**
|
|
42
|
+
* Run `start` and return its result with the server function calls it made: their
|
|
43
|
+
* `endpoints` and call `keys`. `staleTime` is what those calls may serve from cache.
|
|
44
|
+
*/
|
|
45
|
+
export function withTracking(start, { staleTime = 0 } = {}) {
|
|
27
46
|
const previous = tracking;
|
|
28
|
-
const
|
|
29
|
-
tracking =
|
|
47
|
+
const deps = { endpoints: new Set(), keys: new Set(), staleTime };
|
|
48
|
+
tracking = deps;
|
|
30
49
|
try {
|
|
31
|
-
return { result: start(), endpoints };
|
|
50
|
+
return { result: start(), endpoints: deps.endpoints, keys: deps.keys };
|
|
32
51
|
} finally {
|
|
33
52
|
tracking = previous;
|
|
34
53
|
}
|
|
@@ -40,27 +59,93 @@ export function endpointOf(fn) {
|
|
|
40
59
|
return typeof fn === "function" && typeof fn.endpoint === "string" ? fn.endpoint : null;
|
|
41
60
|
}
|
|
42
61
|
|
|
43
|
-
|
|
44
|
-
|
|
62
|
+
function add(map, k, entry) {
|
|
63
|
+
let set = map.get(k);
|
|
64
|
+
if (!set) map.set(k, (set = new Set()));
|
|
65
|
+
set.add(entry);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function remove(map, k, entry) {
|
|
69
|
+
const set = map.get(k);
|
|
70
|
+
set?.delete(entry);
|
|
71
|
+
if (set?.size === 0) map.delete(k);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* A live resource `entry` (`{ refetch }`) now depends on `endpoints` and call `keys`,
|
|
76
|
+
* plus the `named` endpoints of its `invalidatedBy`.
|
|
77
|
+
*/
|
|
78
|
+
export function registerResource(entry, endpoints, keys = new Set(), named = []) {
|
|
45
79
|
unregisterResource(entry);
|
|
46
|
-
entry.endpoints = endpoints;
|
|
80
|
+
entry.endpoints = new Set([...endpoints, ...named]);
|
|
81
|
+
entry.keys = keys;
|
|
82
|
+
entry.named = named;
|
|
47
83
|
live.add(entry);
|
|
48
|
-
for (const endpoint of endpoints)
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
set.add(entry);
|
|
52
|
-
}
|
|
84
|
+
for (const endpoint of entry.endpoints) add(byEndpoint, endpoint, entry);
|
|
85
|
+
for (const key of keys) add(byKey, key, entry);
|
|
86
|
+
for (const endpoint of named) add(byNamed, endpoint, entry);
|
|
53
87
|
}
|
|
54
88
|
|
|
55
89
|
/** A resource stopped (paused or disposed). */
|
|
56
90
|
export function unregisterResource(entry) {
|
|
57
91
|
live.delete(entry);
|
|
58
|
-
for (const endpoint of entry.endpoints ?? [])
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (set?.size === 0) byEndpoint.delete(endpoint);
|
|
62
|
-
}
|
|
92
|
+
for (const endpoint of entry.endpoints ?? []) remove(byEndpoint, endpoint, entry);
|
|
93
|
+
for (const key of entry.keys ?? []) remove(byKey, key, entry);
|
|
94
|
+
for (const endpoint of entry.named ?? []) remove(byNamed, endpoint, entry);
|
|
63
95
|
entry.endpoints = undefined;
|
|
96
|
+
entry.keys = undefined;
|
|
97
|
+
entry.named = undefined;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The server function calls live resources show, `[endpoint, input]`, at most `max`
|
|
102
|
+
* (an action sends them so it can refresh them in its response).
|
|
103
|
+
*/
|
|
104
|
+
export function liveCalls(max) {
|
|
105
|
+
const calls = [];
|
|
106
|
+
for (const key of byKey.keys()) {
|
|
107
|
+
const call = peek(key)?.call;
|
|
108
|
+
if (call) calls.push(call);
|
|
109
|
+
if (calls.length >= max) break;
|
|
110
|
+
}
|
|
111
|
+
return calls;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The cached data for `key` changed outside a fetch (`setQueryData`, an optimistic
|
|
116
|
+
* overlay, an action's refresh): resources whose fetcher made that call re-run it
|
|
117
|
+
* against the cache. Resources that show the entry directly already heard the write.
|
|
118
|
+
*/
|
|
119
|
+
export function cacheChanged(key) {
|
|
120
|
+
for (const entry of [...(byKey.get(key) ?? [])]) entry.fromCache?.(key);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* After an action refreshed `endpoints` and sent `freshKeys` back: everything else those
|
|
125
|
+
* endpoints cached is stale, and live resources the response did not cover refetch, as
|
|
126
|
+
* do the `stale` targets (`{ endpoint, key }`) it could not run.
|
|
127
|
+
*/
|
|
128
|
+
export async function settleRefresh(endpoints, freshKeys, stale) {
|
|
129
|
+
const eps = new Set(endpoints);
|
|
130
|
+
const targets = stale.map(({ endpoint, key }) => ({ endpoint, key }));
|
|
131
|
+
markStale((key, entry) => {
|
|
132
|
+
if (freshKeys.has(key)) return false;
|
|
133
|
+
if (targets.some((target) => hits(target, key, entry))) return true;
|
|
134
|
+
const endpoint = endpointOfKey(key);
|
|
135
|
+
return (endpoint && eps.has(endpoint)) || [...eps].some((ep) => entry.deps?.endpoints.has(ep));
|
|
136
|
+
});
|
|
137
|
+
const resources = new Set();
|
|
138
|
+
for (const ep of eps) {
|
|
139
|
+
for (const entry of byEndpoint.get(ep) ?? []) {
|
|
140
|
+
const own = [...(entry.keys ?? [])].filter((k) => endpointOfKey(k) === ep);
|
|
141
|
+
if (own.length === 0 || own.some((k) => !freshKeys.has(k))) resources.add(entry);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const { endpoint, key } of targets) {
|
|
145
|
+
const found = key ? [...(byKey.get(key) ?? []), ...(byNamed.get(endpoint) ?? [])] : byEndpoint.get(endpoint) ?? [];
|
|
146
|
+
for (const entry of found) resources.add(entry);
|
|
147
|
+
}
|
|
148
|
+
await Promise.all([...resources].map((entry) => entry.refetch()));
|
|
64
149
|
}
|
|
65
150
|
|
|
66
151
|
/** The router's hook for reloading the current page's loader data (`mountApp`). */
|
|
@@ -69,21 +154,48 @@ export function setRouteDataRefresher(fn) {
|
|
|
69
154
|
}
|
|
70
155
|
|
|
71
156
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
|
|
157
|
+
* Split `invalidate()`'s arguments into targets: a server function alone means all of
|
|
158
|
+
* its calls; a value right after one narrows it to the call with that input.
|
|
159
|
+
*/
|
|
160
|
+
function targetsOf(args) {
|
|
161
|
+
const targets = [];
|
|
162
|
+
for (let i = 0; i < args.length; i++) {
|
|
163
|
+
const endpoint = endpointOf(args[i]);
|
|
164
|
+
if (!endpoint) throw new TypeError("invalidate() takes server functions imported from a .server module, each optionally followed by its input");
|
|
165
|
+
if (i + 1 < args.length && typeof args[i + 1] !== "function") {
|
|
166
|
+
targets.push({ endpoint, key: callKey(endpoint, args[++i]) });
|
|
167
|
+
} else {
|
|
168
|
+
targets.push({ endpoint, key: null });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return targets;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Does a cached entry depend on a target? Its own key, or what its fetcher called. */
|
|
175
|
+
function hits(target, key, entry) {
|
|
176
|
+
if (target.key) return key === target.key || !!entry.deps?.keys.has(target.key);
|
|
177
|
+
return endpointOfKey(key) === target.endpoint || !!entry.deps?.endpoints.has(target.endpoint);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Refetch the live resources that called the given server functions (as imported from a
|
|
182
|
+
* `.server` module), each optionally followed by its input to target one call. With no
|
|
183
|
+
* arguments: every live resource, and the current page's loader data. Resolves when the
|
|
184
|
+
* refetches settle; a failed refetch shows on its resource, it does not reject here.
|
|
75
185
|
*/
|
|
76
|
-
export async function invalidate(...
|
|
186
|
+
export async function invalidate(...args) {
|
|
77
187
|
if (typeof document === "undefined") return;
|
|
78
|
-
if (
|
|
188
|
+
if (args.length === 0) {
|
|
189
|
+
markStale();
|
|
79
190
|
await Promise.all([...[...live].map((entry) => entry.refetch()), refreshRoute?.()]);
|
|
80
191
|
return;
|
|
81
192
|
}
|
|
82
|
-
const targets =
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
193
|
+
const targets = targetsOf(args);
|
|
194
|
+
markStale((key, entry) => targets.some((target) => hits(target, key, entry)));
|
|
195
|
+
const resources = new Set();
|
|
196
|
+
for (const { endpoint, key } of targets) {
|
|
197
|
+
const found = key ? [...(byKey.get(key) ?? []), ...(byNamed.get(endpoint) ?? [])] : byEndpoint.get(endpoint) ?? [];
|
|
198
|
+
for (const entry of found) resources.add(entry);
|
|
87
199
|
}
|
|
88
|
-
await Promise.all([...
|
|
200
|
+
await Promise.all([...resources].map((entry) => entry.refetch()));
|
|
89
201
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
type ServerFn<I, O> = ((input: I, options?: any) => Promise<O>) & { endpoint?: string };
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Store data for one server function call: `value`, or `value(current)` for a function.
|
|
5
|
+
* Every resource showing the call updates; nothing is fetched.
|
|
6
|
+
*/
|
|
7
|
+
export function setQueryData<I, O>(fn: ServerFn<I, O>, input: I, value: O | ((current: O | undefined) => O)): void;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Show `update(data)` on every cached call of `fn` until `promise` settles, then take it
|
|
11
|
+
* off: the action's refreshed data shows on success, the previous data on failure.
|
|
12
|
+
* Returns `promise`'s outcome.
|
|
13
|
+
*/
|
|
14
|
+
export function optimistic<T, I, O>(promise: Promise<T>, fn: ServerFn<I, O>, update: (data: O) => O): Promise<T>;
|
|
15
|
+
/** Show `update(data)` on the cached call of `fn` with `input` until `promise` settles. */
|
|
16
|
+
export function optimistic<T, I, O>(promise: Promise<T>, fn: ServerFn<I, O>, input: I, update: (data: O) => O): Promise<T>;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Writing to the query cache (docs/DATA.md §3): after an action, from a realtime push,
|
|
2
|
+
// or optimistically while an action runs.
|
|
3
|
+
//
|
|
4
|
+
// setQueryData(getTodo, { id: 1 }, (todo) => ({ ...todo, done: true }));
|
|
5
|
+
// await optimistic(addTodo({ title }), listTodos, (todos) => [...todos, { title }]);
|
|
6
|
+
//
|
|
7
|
+
// An action that calls `refresh()` on the server sends fresh query data with its
|
|
8
|
+
// response; the browser stub hands it to `applyRefresh`, so the page updates in the
|
|
9
|
+
// same round trip.
|
|
10
|
+
|
|
11
|
+
import { cacheChanged, endpointOf, settleRefresh } from "./invalidate.js";
|
|
12
|
+
import { addOverlay, allEntries, callKey, endpointOfKey, peek, write } from "./query-cache.js";
|
|
13
|
+
|
|
14
|
+
function endpointFrom(fn, name) {
|
|
15
|
+
const endpoint = endpointOf(fn);
|
|
16
|
+
if (!endpoint) throw new TypeError(`${name}() takes a server function imported from a .server module`);
|
|
17
|
+
return endpoint;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Store data for one server function call: `value`, or `value(current)` when it is a
|
|
22
|
+
* function. Every resource showing the call updates; nothing is fetched.
|
|
23
|
+
*/
|
|
24
|
+
export function setQueryData(fn, input, value) {
|
|
25
|
+
const endpoint = endpointFrom(fn, "setQueryData");
|
|
26
|
+
const key = callKey(endpoint, input);
|
|
27
|
+
const current = peek(key);
|
|
28
|
+
const next = typeof value === "function" ? value(current?.data) : value;
|
|
29
|
+
const e = write(key, next);
|
|
30
|
+
e.call ??= [endpoint, input];
|
|
31
|
+
cacheChanged(key);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Show `update(data)` for a server function's cached calls until `promise` settles,
|
|
36
|
+
* then take it off: the fresh data an action's `refresh()` sent shows on success, the
|
|
37
|
+
* previous data on failure. `optimistic(promise, fn, update)` covers every cached
|
|
38
|
+
* input of `fn`; `optimistic(promise, fn, input, update)` one. Returns `promise`'s
|
|
39
|
+
* outcome.
|
|
40
|
+
*/
|
|
41
|
+
export function optimistic(promise, fn, ...rest) {
|
|
42
|
+
const endpoint = endpointFrom(fn, "optimistic");
|
|
43
|
+
const update = rest.length >= 2 ? rest[1] : rest[0];
|
|
44
|
+
if (typeof update !== "function") throw new TypeError("optimistic(promise, fn, [input], update): update must be a function");
|
|
45
|
+
const only = rest.length >= 2 ? callKey(endpoint, rest[0]) : null;
|
|
46
|
+
const removals = [];
|
|
47
|
+
for (const [key, e] of allEntries()) {
|
|
48
|
+
if (!e.hasData || (only ? key !== only : endpointOfKey(key) !== endpoint)) continue;
|
|
49
|
+
removals.push([key, addOverlay(e, update)]);
|
|
50
|
+
}
|
|
51
|
+
for (const [key] of removals) cacheChanged(key);
|
|
52
|
+
return Promise.resolve(promise).finally(() => {
|
|
53
|
+
for (const [key, remove] of removals) {
|
|
54
|
+
remove();
|
|
55
|
+
cacheChanged(key);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Apply an action's `refresh` payload: write the fresh calls, mark the rest of the
|
|
62
|
+
* refreshed endpoints stale, and refetch what the response did not cover. Resolves once
|
|
63
|
+
* those refetches settle.
|
|
64
|
+
*/
|
|
65
|
+
export async function applyRefresh({ fresh = [], stale = [], endpoints = [] } = {}) {
|
|
66
|
+
const written = fresh.map(([endpoint, input, data]) => ({ endpoint, input, data, key: callKey(endpoint, input) }));
|
|
67
|
+
const freshKeys = new Set(written.map((w) => w.key));
|
|
68
|
+
const pending = settleRefresh(
|
|
69
|
+
endpoints,
|
|
70
|
+
freshKeys,
|
|
71
|
+
stale.map(([endpoint, ...input]) => ({ endpoint, key: input.length ? callKey(endpoint, input[0]) : null })),
|
|
72
|
+
);
|
|
73
|
+
for (const { endpoint, input, data, key } of written) {
|
|
74
|
+
const e = write(key, data);
|
|
75
|
+
e.call ??= [endpoint, input];
|
|
76
|
+
cacheChanged(key);
|
|
77
|
+
}
|
|
78
|
+
await pending;
|
|
79
|
+
}
|
package/runtime/portal.js
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
// native top layer (`<dialog>.showModal()`, the popover API) is usually a better
|
|
15
15
|
// fit than a portal — Portal is the general escape hatch for everything else.
|
|
16
16
|
|
|
17
|
+
import { moveNode } from "./dom.js";
|
|
17
18
|
import { afterHydration } from "./hydrate.js";
|
|
18
19
|
|
|
19
20
|
function resolveTarget(to) {
|
|
@@ -54,7 +55,8 @@ export class PortalElement extends HTMLElement {
|
|
|
54
55
|
n.setAttribute("data-afw-portal", "");
|
|
55
56
|
}
|
|
56
57
|
}
|
|
57
|
-
|
|
58
|
+
// Moved, not re-inserted, where the browser can: the children keep their state.
|
|
59
|
+
for (const n of this._moved) moveNode(target, n, null);
|
|
58
60
|
}
|
|
59
61
|
|
|
60
62
|
disconnectedCallback() {
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
// The query cache (docs/DATA.md §3): server function results and keyed resources,
|
|
2
|
+
// shared by every caller in the page.
|
|
3
|
+
//
|
|
4
|
+
// • Dedupe — identical calls in flight share one request. The request is aborted only
|
|
5
|
+
// once every caller has aborted.
|
|
6
|
+
// • Freshness — an entry younger than a caller's `staleTime` answers without a request.
|
|
7
|
+
// The default `staleTime` is 0, so the cache shares requests but always revalidates.
|
|
8
|
+
// • Sync reads — a resource that knows its key up front (`resource(source, listTodos)`
|
|
9
|
+
// or `{ key }`) shows a cached entry at once, so a remount skips the loading state.
|
|
10
|
+
// • Lifetime — an entry no resource uses is dropped `gcTime` (default 5 minutes) after
|
|
11
|
+
// its last use. Sweeps run as the cache is used; there are no timers.
|
|
12
|
+
//
|
|
13
|
+
// Keys: `endpoint + encoded input`, with plain-object keys sorted, so `{ a, b }` and
|
|
14
|
+
// `{ b, a }` are the same entry. Cached data is shared: treat it as immutable.
|
|
15
|
+
//
|
|
16
|
+
// Overlays: `optimistic()` stacks an updater on an entry while an action runs. Readers
|
|
17
|
+
// see the entry's *view* (its data through every overlay); fetches and writes replace
|
|
18
|
+
// the data underneath, and the overlay comes off when the action settles.
|
|
19
|
+
|
|
20
|
+
import { encode } from "../core/fn-codec.js";
|
|
21
|
+
|
|
22
|
+
export const DEFAULT_GC_TIME = 5 * 60_000;
|
|
23
|
+
const SWEEP_EVERY = 1000;
|
|
24
|
+
|
|
25
|
+
const entries = new Map(); // key → entry
|
|
26
|
+
let lastSweep = 0;
|
|
27
|
+
|
|
28
|
+
const now = () => Date.now();
|
|
29
|
+
|
|
30
|
+
/** Plain objects with sorted keys, recursively; other values as they are. */
|
|
31
|
+
function canonical(value, seen = new Map()) {
|
|
32
|
+
if (value === null || typeof value !== "object") return value;
|
|
33
|
+
if (seen.has(value)) return seen.get(value);
|
|
34
|
+
if (Array.isArray(value)) {
|
|
35
|
+
const out = [];
|
|
36
|
+
seen.set(value, out);
|
|
37
|
+
for (const item of value) out.push(canonical(item, seen));
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
const proto = Object.getPrototypeOf(value);
|
|
41
|
+
if (proto !== Object.prototype && proto !== null) return value; // Date, Map, … encode as they are
|
|
42
|
+
const out = {};
|
|
43
|
+
seen.set(value, out);
|
|
44
|
+
for (const k of Object.keys(value).sort()) {
|
|
45
|
+
// defineProperty: a `__proto__` key stays an own property, as the codec keeps it.
|
|
46
|
+
Object.defineProperty(out, k, { value: canonical(value[k], seen), enumerable: true, writable: true, configurable: true });
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The cache key of a server function call. */
|
|
52
|
+
export function callKey(endpoint, input) {
|
|
53
|
+
return `${endpoint}\u0000${encode(canonical(input))}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The cache key a resource's `key` option names. */
|
|
57
|
+
export function customKey(key) {
|
|
58
|
+
return `key\u0000${encode(canonical(key))}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The endpoint part of a call key, or null for a custom key. */
|
|
62
|
+
export function endpointOfKey(key) {
|
|
63
|
+
const i = key.indexOf("\u0000");
|
|
64
|
+
const head = key.slice(0, i);
|
|
65
|
+
return head === "key" ? null : head;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function sweep(force = false) {
|
|
69
|
+
const t = now();
|
|
70
|
+
if (!force && t - lastSweep < SWEEP_EVERY) return;
|
|
71
|
+
lastSweep = t;
|
|
72
|
+
for (const [key, e] of entries) {
|
|
73
|
+
if (e.users === 0 && !e.flight && t - e.idleSince >= e.gcTime) entries.delete(key);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function entryFor(key) {
|
|
78
|
+
sweep();
|
|
79
|
+
let e = entries.get(key);
|
|
80
|
+
if (!e) {
|
|
81
|
+
e = {
|
|
82
|
+
key,
|
|
83
|
+
data: undefined,
|
|
84
|
+
hasData: false,
|
|
85
|
+
updatedAt: 0,
|
|
86
|
+
stale: false, // invalidated: never fresh, whatever the staleTime
|
|
87
|
+
flight: null,
|
|
88
|
+
listeners: new Set(),
|
|
89
|
+
users: 0,
|
|
90
|
+
idleSince: now(),
|
|
91
|
+
gcTime: DEFAULT_GC_TIME,
|
|
92
|
+
// What the fetcher behind a custom key called (endpoints and call keys), so a
|
|
93
|
+
// cache hit, which runs no fetcher, still registers for `invalidate()`.
|
|
94
|
+
deps: null,
|
|
95
|
+
// The server function call behind the entry, `[endpoint, input]` (an action sends
|
|
96
|
+
// the shown calls so it can refresh them), or null for a custom key.
|
|
97
|
+
call: null,
|
|
98
|
+
overlays: [],
|
|
99
|
+
};
|
|
100
|
+
entries.set(key, e);
|
|
101
|
+
}
|
|
102
|
+
return e;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The entry for `key`, if one exists (no entry is created). */
|
|
106
|
+
export function peek(key) {
|
|
107
|
+
return entries.get(key);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** What readers see of `e`: its data through every optimistic overlay. */
|
|
111
|
+
export function viewOf(e) {
|
|
112
|
+
let value = e.data;
|
|
113
|
+
for (const overlay of e.overlays) value = overlay(value);
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Tell the resources showing `e` that its view changed. */
|
|
118
|
+
function notify(e) {
|
|
119
|
+
if (e.listeners.size === 0) return;
|
|
120
|
+
const value = viewOf(e);
|
|
121
|
+
for (const listener of [...e.listeners]) listener(value);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Every entry, for invalidation and optimistic updates (`[key, entry]`). */
|
|
125
|
+
export function allEntries() {
|
|
126
|
+
return entries.entries();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Does `e` hold data younger than `staleTime`? */
|
|
130
|
+
export function isFresh(e, staleTime) {
|
|
131
|
+
return !!e?.hasData && !e.stale && now() - e.updatedAt < staleTime;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Store `data` under `key` and tell the resources that show it. */
|
|
135
|
+
export function write(key, data, deps) {
|
|
136
|
+
const e = entryFor(key);
|
|
137
|
+
e.data = data;
|
|
138
|
+
e.hasData = true;
|
|
139
|
+
e.updatedAt = now();
|
|
140
|
+
e.stale = false;
|
|
141
|
+
if (deps) e.deps = deps;
|
|
142
|
+
if (e.users === 0) e.idleSince = e.updatedAt;
|
|
143
|
+
notify(e);
|
|
144
|
+
return e;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Stack `overlay` on `e` (an optimistic update); returns its removal. */
|
|
148
|
+
export function addOverlay(e, overlay) {
|
|
149
|
+
e.overlays.push(overlay);
|
|
150
|
+
notify(e);
|
|
151
|
+
return () => {
|
|
152
|
+
const i = e.overlays.indexOf(overlay);
|
|
153
|
+
if (i === -1) return;
|
|
154
|
+
e.overlays.splice(i, 1);
|
|
155
|
+
notify(e);
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The data for `key`: a fresh entry's data, the request already in flight, or a new
|
|
161
|
+
* request made with `start(signal)`. `signal` aborts this caller only; the request
|
|
162
|
+
* stops once every caller has aborted.
|
|
163
|
+
*/
|
|
164
|
+
export function fetchShared(key, start, { signal, staleTime = 0, deps, call } = {}) {
|
|
165
|
+
const e = entryFor(key);
|
|
166
|
+
if (call) e.call ??= call;
|
|
167
|
+
if (isFresh(e, staleTime)) return Promise.resolve(viewOf(e));
|
|
168
|
+
if (!e.flight) {
|
|
169
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
170
|
+
const flight = { controller, active: 0, entry: e, promise: null };
|
|
171
|
+
// The async IIFE starts the request synchronously and turns a throw into a rejection.
|
|
172
|
+
flight.promise = (async () => start(controller?.signal))().then(
|
|
173
|
+
(data) => {
|
|
174
|
+
// A detached flight (invalidated, or aborted by all callers) writes nothing.
|
|
175
|
+
if (e.flight === flight) {
|
|
176
|
+
e.flight = null;
|
|
177
|
+
write(key, data, deps?.());
|
|
178
|
+
return viewOf(e); // through any optimistic overlay still on it
|
|
179
|
+
}
|
|
180
|
+
return data;
|
|
181
|
+
},
|
|
182
|
+
(error) => {
|
|
183
|
+
if (e.flight === flight) e.flight = null;
|
|
184
|
+
throw error;
|
|
185
|
+
},
|
|
186
|
+
);
|
|
187
|
+
e.flight = flight;
|
|
188
|
+
}
|
|
189
|
+
return join(e.flight, signal);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function join(flight, signal) {
|
|
193
|
+
flight.active++;
|
|
194
|
+
if (!signal) return flight.promise;
|
|
195
|
+
if (signal.aborted) {
|
|
196
|
+
leave(flight);
|
|
197
|
+
return Promise.reject(signal.reason);
|
|
198
|
+
}
|
|
199
|
+
return new Promise((resolve, reject) => {
|
|
200
|
+
const onAbort = () => {
|
|
201
|
+
leave(flight);
|
|
202
|
+
reject(signal.reason);
|
|
203
|
+
};
|
|
204
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
205
|
+
flight.promise.then(
|
|
206
|
+
(v) => {
|
|
207
|
+
signal.removeEventListener("abort", onAbort);
|
|
208
|
+
resolve(v);
|
|
209
|
+
},
|
|
210
|
+
(error) => {
|
|
211
|
+
signal.removeEventListener("abort", onAbort);
|
|
212
|
+
reject(error);
|
|
213
|
+
},
|
|
214
|
+
);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function leave(flight) {
|
|
219
|
+
if (--flight.active > 0) return;
|
|
220
|
+
if (flight.entry.flight === flight) flight.entry.flight = null;
|
|
221
|
+
flight.controller?.abort();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* A resource shows `key`: it hears every write and keeps the entry alive. Returns the
|
|
226
|
+
* unsubscribe function.
|
|
227
|
+
*/
|
|
228
|
+
export function subscribe(key, listener, { gcTime = DEFAULT_GC_TIME } = {}) {
|
|
229
|
+
const e = entryFor(key);
|
|
230
|
+
e.users++;
|
|
231
|
+
// The longest `gcTime` among the entry's current users wins.
|
|
232
|
+
e.gcTime = e.users === 1 ? gcTime : Math.max(e.gcTime, gcTime);
|
|
233
|
+
e.listeners.add(listener);
|
|
234
|
+
let done = false;
|
|
235
|
+
return () => {
|
|
236
|
+
if (done) return;
|
|
237
|
+
done = true;
|
|
238
|
+
e.listeners.delete(listener);
|
|
239
|
+
if (--e.users === 0) e.idleSince = now();
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Mark entries stale and detach their requests in flight, so the next read fetches
|
|
245
|
+
* again. `match(key, entry)` picks them; with none, every entry.
|
|
246
|
+
*/
|
|
247
|
+
export function markStale(match) {
|
|
248
|
+
for (const [key, e] of entries) {
|
|
249
|
+
if (match && !match(key, e)) continue;
|
|
250
|
+
e.stale = true;
|
|
251
|
+
e.flight = null;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Drop every entry (tests only). */
|
|
256
|
+
export function __resetQueryCache() {
|
|
257
|
+
entries.clear();
|
|
258
|
+
lastSweep = 0;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** How many entries are cached (tests only). */
|
|
262
|
+
export function __queryCacheSize() {
|
|
263
|
+
sweep(true);
|
|
264
|
+
return entries.size;
|
|
265
|
+
}
|
package/runtime/resource.d.ts
CHANGED
|
@@ -2,6 +2,11 @@ export interface Resource<T> {
|
|
|
2
2
|
readonly data: T | undefined;
|
|
3
3
|
readonly loading: boolean;
|
|
4
4
|
readonly error: unknown;
|
|
5
|
+
/**
|
|
6
|
+
* Re-run the fetcher with the current source value, ignoring `staleTime`. Resolves
|
|
7
|
+
* with the new data (undefined if a newer run superseded it) and rejects when the
|
|
8
|
+
* fetch fails; the failure also shows on `error`. Returns undefined while paused.
|
|
9
|
+
*/
|
|
5
10
|
refetch(): Promise<T | undefined> | undefined;
|
|
6
11
|
}
|
|
7
12
|
export interface ResourceOptions<T> {
|
|
@@ -15,7 +20,26 @@ export interface ResourceOptions<T> {
|
|
|
15
20
|
* a failed refetch.
|
|
16
21
|
*/
|
|
17
22
|
errors?: "inline";
|
|
23
|
+
/**
|
|
24
|
+
* Cache the result under this key (or the key this function returns for the source
|
|
25
|
+
* value): every resource with the key shares one request and shows the same data. A
|
|
26
|
+
* server function fetcher is cached by its endpoint and input without one.
|
|
27
|
+
*/
|
|
28
|
+
key?: unknown | ((value: any) => unknown);
|
|
29
|
+
/** Milliseconds cached data answers without a request. Default 0: always revalidate. */
|
|
30
|
+
staleTime?: number;
|
|
31
|
+
/** Milliseconds an unused cache entry is kept. Default 5 minutes. */
|
|
32
|
+
gcTime?: number;
|
|
33
|
+
/** Abort a run that takes longer than this many milliseconds; `error` is a TimeoutError. */
|
|
34
|
+
timeout?: number;
|
|
35
|
+
/**
|
|
36
|
+
* Refetch when the tab becomes visible again (`"focus"`) or the browser reconnects
|
|
37
|
+
* (`"online"`), once the data is older than `staleTime`. Off by default.
|
|
38
|
+
*/
|
|
39
|
+
revalidateOn?: "focus" | "online" | Array<"focus" | "online">;
|
|
18
40
|
}
|
|
41
|
+
/** A server function without input: `resource(listTodos)`. */
|
|
42
|
+
export function resource<T>(fetcher: (input: undefined, options?: { signal?: AbortSignal }) => Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
19
43
|
export function resource<T>(fetcher: (value: true, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
20
44
|
export function resource<S, T>(source: () => S, fetcher: (value: NonNullable<Exclude<S, false>>, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
|
|
21
45
|
export function __setResourceServer(value: boolean | null): void;
|