zitejs 0.10.1-device.0 → 0.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/auth/actions.js +0 -2
- package/dist/cjs/auth/client.js +0 -5
- package/dist/cjs/auth/useAuth.test.js +0 -1
- package/dist/cjs/caller/index.js +16 -5
- package/dist/cjs/check/index.js +10 -4
- package/dist/cjs/start/build/entries.d.ts +5 -0
- package/dist/cjs/start/build/entries.js +37 -12
- package/dist/cjs/start/build/roleIds.d.ts +11 -0
- package/dist/cjs/start/build/roleIds.js +59 -0
- package/dist/cjs/start/describe/schema.d.ts +574 -0
- package/dist/cjs/start/describe/schema.js +178 -0
- package/dist/cjs/start/protocol.d.ts +7 -0
- package/dist/cjs/start/protocol.js +27 -3
- package/dist/cjs/start/serve/authHookNames.d.ts +3 -0
- package/dist/cjs/start/serve/authHookNames.js +13 -0
- package/dist/cjs/vite/index.js +0 -41
- package/dist/cjs/vite/index.test.js +0 -36
- package/dist/esm/auth/actions.js +0 -2
- package/dist/esm/auth/client.js +0 -5
- package/dist/esm/auth/useAuth.test.js +0 -1
- package/dist/esm/caller/index.js +15 -4
- package/dist/esm/check/index.js +10 -4
- package/dist/esm/start/build/entries.d.ts +5 -0
- package/dist/esm/start/build/entries.js +37 -13
- package/dist/esm/start/build/roleIds.d.ts +11 -0
- package/dist/esm/start/build/roleIds.js +54 -0
- package/dist/esm/start/build/vite.js +0 -4
- package/dist/esm/start/classicOnly.js +3 -3
- package/dist/esm/start/describe/schema.d.ts +574 -0
- package/dist/esm/start/describe/schema.js +175 -0
- package/dist/esm/start/describe/schema.test-d.d.ts +1 -0
- package/dist/esm/start/describe/schema.test-d.js +23 -0
- package/dist/esm/start/index.d.ts +1 -1
- package/dist/esm/start/protocol.d.ts +7 -0
- package/dist/esm/start/protocol.js +17 -2
- package/dist/esm/start/roles.d.ts +10 -2
- package/dist/esm/start/serve/authHookNames.d.ts +3 -0
- package/dist/esm/start/serve/authHookNames.js +9 -0
- package/dist/esm/start/serve/authHooks.d.ts +2 -4
- package/dist/esm/start/serve/authHooks.js +2 -8
- package/dist/esm/start/version.d.ts +1 -1
- package/dist/esm/start/version.js +1 -1
- package/dist/esm/vite/index.js +0 -41
- package/dist/esm/vite/index.test.js +0 -36
- package/package.json +5 -13
- package/tsconfig/start.json +40 -0
- package/dist/cjs/internal/browserMode.d.ts +0 -2
- package/dist/cjs/internal/browserMode.js +0 -18
- package/dist/cjs/internal/deviceCache.d.ts +0 -11
- package/dist/cjs/internal/deviceCache.js +0 -29
- package/dist/cjs/query/deviceCache.d.ts +0 -14
- package/dist/cjs/query/deviceCache.js +0 -304
- package/dist/cjs/query/index.d.ts +0 -19
- package/dist/cjs/query/index.js +0 -369
- package/dist/esm/internal/browserMode.d.ts +0 -2
- package/dist/esm/internal/browserMode.js +0 -15
- package/dist/esm/internal/deviceCache.d.ts +0 -11
- package/dist/esm/internal/deviceCache.js +0 -24
- package/dist/esm/query/deviceCache.d.ts +0 -14
- package/dist/esm/query/deviceCache.js +0 -301
- package/dist/esm/query/index.d.ts +0 -19
- package/dist/esm/query/index.js +0 -366
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.keepOnDevice = keepOnDevice;
|
|
4
|
-
const react_query_1 = require("@tanstack/react-query");
|
|
5
|
-
const browserMode_js_1 = require("../internal/browserMode.js");
|
|
6
|
-
const deviceCache_js_1 = require("../internal/deviceCache.js");
|
|
7
|
-
const SIGNED_OUT = 'anon';
|
|
8
|
-
// Kept data seeds the screen until its refetch lands, so not much older.
|
|
9
|
-
const MAX_AGE_MS = 3 * 24 * 60 * 60_000;
|
|
10
|
-
// localStorage holds about 5 MB per origin; leave room for the app's own keys.
|
|
11
|
-
const MAX_CHARS = 2_000_000;
|
|
12
|
-
const SAVE_EVERY_MS = 10_000;
|
|
13
|
-
const read = (key) => {
|
|
14
|
-
try {
|
|
15
|
-
return JSON.parse(localStorage.getItem(key) ?? 'null') ?? undefined;
|
|
16
|
-
}
|
|
17
|
-
catch {
|
|
18
|
-
return undefined;
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
const readOwner = () => read(deviceCache_js_1.DEVICE_CACHE_OWNER_KEY);
|
|
22
|
-
const writeOwner = (owner) => {
|
|
23
|
-
try {
|
|
24
|
-
localStorage.setItem(deviceCache_js_1.DEVICE_CACHE_OWNER_KEY, JSON.stringify(owner));
|
|
25
|
-
}
|
|
26
|
-
catch { }
|
|
27
|
-
};
|
|
28
|
-
const dropKept = () => {
|
|
29
|
-
try {
|
|
30
|
-
localStorage.removeItem(deviceCache_js_1.DEVICE_CACHE_KEY);
|
|
31
|
-
}
|
|
32
|
-
catch { }
|
|
33
|
-
};
|
|
34
|
-
const isFresh = (query) => Date.now() - query.state.dataUpdatedAt < MAX_AGE_MS;
|
|
35
|
-
const statusOf = (error) => error?.status;
|
|
36
|
-
/**
|
|
37
|
-
* Comes back from JSON as it went in, as an endpoint's answer does. A Date
|
|
38
|
-
* would come back a string and a Map an empty object, and a page reading them
|
|
39
|
-
* would break on every reload.
|
|
40
|
-
*/
|
|
41
|
-
const isPlainJson = (value, parents = []) => {
|
|
42
|
-
if (value === null || typeof value === 'string')
|
|
43
|
-
return true;
|
|
44
|
-
if (typeof value === 'boolean')
|
|
45
|
-
return true;
|
|
46
|
-
if (typeof value === 'number')
|
|
47
|
-
return Number.isFinite(value);
|
|
48
|
-
if (typeof value !== 'object' || parents.includes(value))
|
|
49
|
-
return false;
|
|
50
|
-
const proto = Object.getPrototypeOf(value);
|
|
51
|
-
if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
|
|
52
|
-
return false;
|
|
53
|
-
}
|
|
54
|
-
parents.push(value);
|
|
55
|
-
const plain = Object.values(value).every(v => isPlainJson(v, parents));
|
|
56
|
-
parents.pop();
|
|
57
|
-
return plain;
|
|
58
|
-
};
|
|
59
|
-
// An infinite list refetches every page it holds, so keep the first.
|
|
60
|
-
const firstPageOnly = (data) => {
|
|
61
|
-
const list = data;
|
|
62
|
-
return Array.isArray(list?.pages) && Array.isArray(list?.pageParams)
|
|
63
|
-
? { pages: list.pages.slice(0, 1), pageParams: list.pageParams.slice(0, 1) }
|
|
64
|
-
: data;
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* The build id when this page may keep data on the device, 'memory' when the
|
|
68
|
-
* app or the platform says it mustn't, undefined when it can't. A preview's
|
|
69
|
-
* endpoints run as the editor's token or a "Preview as" session and an old
|
|
70
|
-
* sign-in's as its stored token, so get-session wouldn't say whose data it is.
|
|
71
|
-
*/
|
|
72
|
-
const deviceCacheMode = () => {
|
|
73
|
-
if ((0, browserMode_js_1.getMode)() !== 'live')
|
|
74
|
-
return undefined;
|
|
75
|
-
if (window._ziteUsageToken)
|
|
76
|
-
return undefined;
|
|
77
|
-
try {
|
|
78
|
-
if (localStorage.getItem('zite.auth.token'))
|
|
79
|
-
return undefined;
|
|
80
|
-
}
|
|
81
|
-
catch {
|
|
82
|
-
return undefined;
|
|
83
|
-
}
|
|
84
|
-
const meta = (name) => document.querySelector(`meta[name="${name}"]`)?.content;
|
|
85
|
-
if (meta('zite-device-cache') === 'memory')
|
|
86
|
-
return 'memory';
|
|
87
|
-
return meta('zite-build');
|
|
88
|
-
};
|
|
89
|
-
/**
|
|
90
|
-
* Keeps what the app's queries return in localStorage for whoever is signed
|
|
91
|
-
* in, so a reload or a return visit shows it at once and then refetches it.
|
|
92
|
-
*
|
|
93
|
-
* Signed-out visitors' data is shown before the first render; a signed-in
|
|
94
|
-
* user's only once get-session confirms the same user. Each save is labelled
|
|
95
|
-
* with who get-session last said this page is for, so any sign-in or sign-out
|
|
96
|
-
* this page hears of (zitejs/auth on this page, another tab, a 401) clears the
|
|
97
|
-
* device and the screen when the answer changes.
|
|
98
|
-
*/
|
|
99
|
-
function keepOnDevice(client, { onOwnerChange } = {}) {
|
|
100
|
-
const mode = deviceCacheMode();
|
|
101
|
-
if (mode === 'memory')
|
|
102
|
-
dropKept();
|
|
103
|
-
if (mode === undefined || mode === 'memory')
|
|
104
|
-
return;
|
|
105
|
-
const build = mode;
|
|
106
|
-
// Who get-session last said this page is for, and when that was asked.
|
|
107
|
-
let confirmed;
|
|
108
|
-
let confirmedAt = 0;
|
|
109
|
-
let checking;
|
|
110
|
-
let askAgain = false;
|
|
111
|
-
let unsaved = false;
|
|
112
|
-
// Shown from the device and not yet refetched. Kept on the next save even
|
|
113
|
-
// once TanStack has dropped the query from memory.
|
|
114
|
-
const restored = new Map();
|
|
115
|
-
const restore = (kept) => {
|
|
116
|
-
const queries = kept.queries.filter(isFresh);
|
|
117
|
-
(0, react_query_1.hydrate)(client, { mutations: [], queries });
|
|
118
|
-
for (const query of queries) {
|
|
119
|
-
// hydrate keeps anything fresher already cached.
|
|
120
|
-
const cached = client.getQueryCache().get(query.queryHash);
|
|
121
|
-
if (cached?.state.dataUpdatedAt === query.state.dataUpdatedAt) {
|
|
122
|
-
restored.set(query.queryHash, query);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
// Shown at once, then asked again on mount: it may be days old, and the
|
|
126
|
-
// live client's staleTime would otherwise trust it for a minute.
|
|
127
|
-
void client.invalidateQueries({
|
|
128
|
-
predicate: query => restored.has(query.queryHash),
|
|
129
|
-
refetchType: 'none',
|
|
130
|
-
});
|
|
131
|
-
};
|
|
132
|
-
const askSession = async () => {
|
|
133
|
-
const res = await fetch('/api/auth/get-session', {
|
|
134
|
-
credentials: 'include',
|
|
135
|
-
cache: 'no-store',
|
|
136
|
-
});
|
|
137
|
-
// An internal app's revoked access is no one.
|
|
138
|
-
if (res.status === 401)
|
|
139
|
-
return SIGNED_OUT;
|
|
140
|
-
if (!res.ok)
|
|
141
|
-
return undefined;
|
|
142
|
-
const body = (await res.json());
|
|
143
|
-
return body?.user?.id ?? SIGNED_OUT;
|
|
144
|
-
};
|
|
145
|
-
// Nothing is saved while this runs, and it asks again when the session
|
|
146
|
-
// changes meanwhile, so the answer is never older than what it's used for.
|
|
147
|
-
const check = () => (checking ??= (async () => {
|
|
148
|
-
let owner;
|
|
149
|
-
let askedAt;
|
|
150
|
-
do {
|
|
151
|
-
askAgain = false;
|
|
152
|
-
askedAt = Date.now();
|
|
153
|
-
owner = await askSession().catch(() => undefined);
|
|
154
|
-
} while (askAgain);
|
|
155
|
-
confirmed = owner;
|
|
156
|
-
confirmedAt = askedAt;
|
|
157
|
-
})().finally(() => (checking = undefined)));
|
|
158
|
-
// What's cached was fetched for whoever was signed in before, so when that
|
|
159
|
-
// changed, it goes from the device and the screen. `claimed`: who another
|
|
160
|
-
// tab now says the device is for (null once someone signed out there). If
|
|
161
|
-
// that isn't who this page finds, the session changed under it unseen.
|
|
162
|
-
const onSessionChange = async (claimed) => {
|
|
163
|
-
const before = confirmed;
|
|
164
|
-
if (checking)
|
|
165
|
-
askAgain = true;
|
|
166
|
-
await check();
|
|
167
|
-
if (confirmed === undefined)
|
|
168
|
-
return;
|
|
169
|
-
// Unknown before only while this page's first check ran: someone signed
|
|
170
|
-
// in or out on this page then, unless it's another tab agreeing.
|
|
171
|
-
const changedHere = before !== confirmed && (before !== undefined || claimed === undefined);
|
|
172
|
-
const changedElsewhere = claimed !== undefined && claimed !== confirmed;
|
|
173
|
-
if (!changedHere && !changedElsewhere)
|
|
174
|
-
return;
|
|
175
|
-
dropKept();
|
|
176
|
-
writeOwner({ owner: confirmed, at: confirmedAt });
|
|
177
|
-
restored.clear();
|
|
178
|
-
onOwnerChange?.();
|
|
179
|
-
void client.resetQueries();
|
|
180
|
-
};
|
|
181
|
-
const save = () => {
|
|
182
|
-
if (!unsaved)
|
|
183
|
-
return;
|
|
184
|
-
if (confirmed === undefined || checking) {
|
|
185
|
-
// A check that failed (offline at startup) is tried again here.
|
|
186
|
-
if (!checking)
|
|
187
|
-
void check();
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
// What's on screen may be a pending write's patch, not what the server has.
|
|
191
|
-
if (client.isMutating() > 0)
|
|
192
|
-
return;
|
|
193
|
-
const owner = readOwner();
|
|
194
|
-
// Someone signed out here, or in or out in another tab, after this page
|
|
195
|
-
// last asked who it's for.
|
|
196
|
-
if (owner && owner.owner !== confirmed && owner.at > confirmedAt)
|
|
197
|
-
return;
|
|
198
|
-
const inMemory = (0, react_query_1.dehydrate)(client, {
|
|
199
|
-
shouldDehydrateQuery: (query) => query.state.status === 'success' &&
|
|
200
|
-
query.meta?.persist !== false &&
|
|
201
|
-
isFresh(query),
|
|
202
|
-
}).queries.map(query => ({
|
|
203
|
-
...query,
|
|
204
|
-
state: { ...query.state, data: firstPageOnly(query.state.data) },
|
|
205
|
-
}));
|
|
206
|
-
const dropped = [...restored.values()].filter(query => !client.getQueryCache().get(query.queryHash) && isFresh(query));
|
|
207
|
-
const parts = [];
|
|
208
|
-
let size = 0;
|
|
209
|
-
for (const query of [...inMemory, ...dropped].sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)) {
|
|
210
|
-
if (!isPlainJson(query.state.data))
|
|
211
|
-
continue;
|
|
212
|
-
let json;
|
|
213
|
-
try {
|
|
214
|
-
json = JSON.stringify(query);
|
|
215
|
-
}
|
|
216
|
-
catch {
|
|
217
|
-
continue; // a key or meta that isn't JSON
|
|
218
|
-
}
|
|
219
|
-
if (size + json.length > MAX_CHARS)
|
|
220
|
-
continue;
|
|
221
|
-
parts.push(json);
|
|
222
|
-
size += json.length;
|
|
223
|
-
}
|
|
224
|
-
try {
|
|
225
|
-
localStorage.setItem(deviceCache_js_1.DEVICE_CACHE_KEY, `{"v":2,"owner":${JSON.stringify(confirmed)},"build":${JSON.stringify(build)},"queries":[${parts.join(',')}]}`);
|
|
226
|
-
writeOwner({ owner: confirmed, at: Date.now() });
|
|
227
|
-
unsaved = false;
|
|
228
|
-
}
|
|
229
|
-
catch {
|
|
230
|
-
dropKept();
|
|
231
|
-
}
|
|
232
|
-
};
|
|
233
|
-
const kept = read(deviceCache_js_1.DEVICE_CACHE_KEY);
|
|
234
|
-
const usable = kept?.v === 2 && kept.build === build ? kept : undefined;
|
|
235
|
-
if (kept && !usable)
|
|
236
|
-
dropKept();
|
|
237
|
-
if (usable?.owner === SIGNED_OUT)
|
|
238
|
-
restore(usable);
|
|
239
|
-
void check().then(() => {
|
|
240
|
-
if (confirmed === undefined || !usable)
|
|
241
|
-
return;
|
|
242
|
-
if (usable.owner === confirmed) {
|
|
243
|
-
if (confirmed !== SIGNED_OUT)
|
|
244
|
-
restore(usable);
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
dropKept();
|
|
248
|
-
writeOwner({ owner: confirmed, at: confirmedAt });
|
|
249
|
-
});
|
|
250
|
-
let saveTimer;
|
|
251
|
-
client.getQueryCache().subscribe(event => {
|
|
252
|
-
if (event.type === 'removed') {
|
|
253
|
-
unsaved = true;
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
if (event.type !== 'updated')
|
|
257
|
-
return;
|
|
258
|
-
const { action, query } = event;
|
|
259
|
-
if (action.type === 'success') {
|
|
260
|
-
if (!action.manual)
|
|
261
|
-
restored.delete(query.queryHash);
|
|
262
|
-
unsaved = true;
|
|
263
|
-
saveTimer ??= setTimeout(() => {
|
|
264
|
-
saveTimer = undefined;
|
|
265
|
-
save();
|
|
266
|
-
}, SAVE_EVERY_MS);
|
|
267
|
-
}
|
|
268
|
-
else if (action.type === 'error') {
|
|
269
|
-
const status = statusOf(action.error);
|
|
270
|
-
// Shown from the device, then refused: leave it as a reload would.
|
|
271
|
-
if (restored.delete(query.queryHash) &&
|
|
272
|
-
(status === 401 || status === 403 || status === 404)) {
|
|
273
|
-
unsaved = true;
|
|
274
|
-
void client.resetQueries({ queryKey: query.queryKey, exact: true });
|
|
275
|
-
}
|
|
276
|
-
// A signed-out visitor's 401 is expected; a signed-in user's session
|
|
277
|
-
// may have ended.
|
|
278
|
-
if (status === 401 &&
|
|
279
|
-
confirmed !== undefined &&
|
|
280
|
-
confirmed !== SIGNED_OUT) {
|
|
281
|
-
void onSessionChange();
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
|
-
document.addEventListener('visibilitychange', () => {
|
|
286
|
-
if (document.visibilityState === 'hidden')
|
|
287
|
-
save();
|
|
288
|
-
});
|
|
289
|
-
window.addEventListener('pagehide', save);
|
|
290
|
-
// Back from the back/forward cache, where storage events don't arrive.
|
|
291
|
-
window.addEventListener('pageshow', event => {
|
|
292
|
-
if (event.persisted)
|
|
293
|
-
void onSessionChange();
|
|
294
|
-
});
|
|
295
|
-
window.addEventListener(deviceCache_js_1.SESSION_CHANGED_EVENT, () => void onSessionChange());
|
|
296
|
-
window.addEventListener('storage', event => {
|
|
297
|
-
if (event.key !== deviceCache_js_1.DEVICE_CACHE_OWNER_KEY && event.key !== null)
|
|
298
|
-
return;
|
|
299
|
-
const claimed = readOwner()?.owner ?? null;
|
|
300
|
-
if (confirmed !== undefined && claimed === confirmed)
|
|
301
|
-
return;
|
|
302
|
-
void onSessionChange(claimed);
|
|
303
|
-
});
|
|
304
|
-
}
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import { QueryClient } from '@tanstack/react-query';
|
|
2
|
-
/**
|
|
3
|
-
* A classic app's TanStack Query client, which its `src/main.tsx` provides.
|
|
4
|
-
* Pages read with useQuery and write with useMutation; this adds what they
|
|
5
|
-
* shouldn't each have to write:
|
|
6
|
-
* - a refused write puts back what its onMutate patched (when no other
|
|
7
|
-
* write is pending), and once the last write settles, what's on screen
|
|
8
|
-
* refetches;
|
|
9
|
-
* - when anyone changes the app's database (another user, another app, the
|
|
10
|
-
* table editor, an automation), what's on screen refetches by itself;
|
|
11
|
-
* - in an app whose zite.config.json says `"deviceCache": "disk"`, what
|
|
12
|
-
* queries return is kept on the device for whoever is signed in, so a
|
|
13
|
-
* reload shows it at once (see `keepOnDevice`).
|
|
14
|
-
*
|
|
15
|
-
* A query that is costly to run again (an AI call, a rate-limited integration)
|
|
16
|
-
* opts out of both refetches with `meta: { live: false }`, and one whose data
|
|
17
|
-
* mustn't stay on the device with `meta: { persist: false }`.
|
|
18
|
-
*/
|
|
19
|
-
export declare const queryClient: QueryClient;
|
package/dist/cjs/query/index.js
DELETED
|
@@ -1,369 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.queryClient = void 0;
|
|
4
|
-
const react_query_1 = require("@tanstack/react-query");
|
|
5
|
-
const deviceCache_js_1 = require("./deviceCache.js");
|
|
6
|
-
const takesRefetches = (query) => query.meta?.live !== false;
|
|
7
|
-
const isInfinite = (query) => {
|
|
8
|
-
const data = query.state.data;
|
|
9
|
-
return Array.isArray(data?.pages) && Array.isArray(data?.pageParams);
|
|
10
|
-
};
|
|
11
|
-
const refetchOnScreen = (client) => {
|
|
12
|
-
void client.invalidateQueries({ predicate: takesRefetches });
|
|
13
|
-
};
|
|
14
|
-
// Whether live updates are watching the database right now.
|
|
15
|
-
let live = false;
|
|
16
|
-
// How what's on screen catches up once the last pending write has settled.
|
|
17
|
-
// Live updates replace it.
|
|
18
|
-
let afterWrites = refetchOnScreen;
|
|
19
|
-
let writeFailed = false;
|
|
20
|
-
// Counts reads that landed, so a write can tell which cached data came from
|
|
21
|
-
// the server after it started and which was set by hand.
|
|
22
|
-
let reads = 0;
|
|
23
|
-
const readAt = new WeakMap();
|
|
24
|
-
// What the queries that take refetches held when each pending write started.
|
|
25
|
-
const snapshots = new Map();
|
|
26
|
-
let writesStarted = 0;
|
|
27
|
-
/** Queries set by hand since the write started, with what they held before. */
|
|
28
|
-
const setByHandSince = (client, snapshot) => [...snapshot.data].filter(([query, before]) => client.getQueryCache().get(query.queryHash) === query &&
|
|
29
|
-
query.state.data !== before &&
|
|
30
|
-
(readAt.get(query) ?? 0) <= snapshot.reads);
|
|
31
|
-
const patchOnScreen = (client) => client.isMutating() > 0 &&
|
|
32
|
-
[...snapshots.values()].some(snapshot => setByHandSince(client, snapshot).some(([query]) => query.isActive()));
|
|
33
|
-
function createQueryClient() {
|
|
34
|
-
const client = new react_query_1.QueryClient({
|
|
35
|
-
defaultOptions: {
|
|
36
|
-
queries: {
|
|
37
|
-
// While live updates watch the database, a mount or a focus within a
|
|
38
|
-
// minute reuses what's cached; data they don't watch (integrations)
|
|
39
|
-
// still refreshes after that. Without them, refetch as usual.
|
|
40
|
-
staleTime: () => (live ? 60_000 : 0),
|
|
41
|
-
retry: 1,
|
|
42
|
-
},
|
|
43
|
-
},
|
|
44
|
-
mutationCache: new react_query_1.MutationCache({
|
|
45
|
-
// Runs before the page's own onMutate: keep what's cached, and stop
|
|
46
|
-
// reads on screen that would paint over the page's patch. First loads
|
|
47
|
-
// and infinite lists go on, since a cancelled page would stall
|
|
48
|
-
// scrolling.
|
|
49
|
-
onMutate: async (_variables, mutation) => {
|
|
50
|
-
writesStarted += 1;
|
|
51
|
-
snapshots.set(mutation, {
|
|
52
|
-
reads,
|
|
53
|
-
writes: writesStarted,
|
|
54
|
-
data: new Map(client
|
|
55
|
-
.getQueryCache()
|
|
56
|
-
.findAll({ predicate: takesRefetches })
|
|
57
|
-
.filter(q => q.state.data !== undefined)
|
|
58
|
-
.map(q => [q, q.state.data])),
|
|
59
|
-
});
|
|
60
|
-
await client.cancelQueries({
|
|
61
|
-
type: 'active',
|
|
62
|
-
predicate: q => q.state.data !== undefined && takesRefetches(q) && !isInfinite(q),
|
|
63
|
-
});
|
|
64
|
-
},
|
|
65
|
-
// Puts back what was set by hand since a refused write started, when it
|
|
66
|
-
// was the only write: with others pending or started since, some of
|
|
67
|
-
// that is theirs. Either way the refetch after the last write follows.
|
|
68
|
-
onError: (_error, _variables, _context, mutation) => {
|
|
69
|
-
writeFailed = true;
|
|
70
|
-
const snapshot = snapshots.get(mutation);
|
|
71
|
-
if (!snapshot ||
|
|
72
|
-
snapshot.writes !== writesStarted ||
|
|
73
|
-
client.isMutating() > 1) {
|
|
74
|
-
return;
|
|
75
|
-
}
|
|
76
|
-
for (const [query, before] of setByHandSince(client, snapshot)) {
|
|
77
|
-
client.setQueryData(query.queryKey, before);
|
|
78
|
-
}
|
|
79
|
-
},
|
|
80
|
-
}),
|
|
81
|
-
});
|
|
82
|
-
client.getQueryCache().subscribe(event => {
|
|
83
|
-
if (event.type === 'updated' &&
|
|
84
|
-
event.action.type === 'success' &&
|
|
85
|
-
!event.action.manual) {
|
|
86
|
-
readAt.set(event.query, ++reads);
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
// Not in onSettled: a write still counts as pending there and while the
|
|
90
|
-
// page's own onSettled runs, and in 5.74.9 a page callback that throws
|
|
91
|
-
// skips the cache's onSettled. This event always comes.
|
|
92
|
-
client.getMutationCache().subscribe(event => {
|
|
93
|
-
if (event.type !== 'updated' ||
|
|
94
|
-
(event.action.type !== 'success' && event.action.type !== 'error')) {
|
|
95
|
-
return;
|
|
96
|
-
}
|
|
97
|
-
snapshots.delete(event.mutation);
|
|
98
|
-
if (client.isMutating() > 0)
|
|
99
|
-
return;
|
|
100
|
-
const failed = writeFailed;
|
|
101
|
-
writeFailed = false;
|
|
102
|
-
afterWrites(client, failed);
|
|
103
|
-
});
|
|
104
|
-
return client;
|
|
105
|
-
}
|
|
106
|
-
const CHANGES_PATH = '/__zite/changes';
|
|
107
|
-
// A hidden tab keeps listening this long, so a quick tab switch costs nothing.
|
|
108
|
-
const HIDDEN_GRACE_MS = 30_000;
|
|
109
|
-
const MIN_POLL_GAP_MS = 1_000;
|
|
110
|
-
const MIN_REFRESH_GAP_MS = 2_000;
|
|
111
|
-
const MAX_REFRESH_GAP_MS = 10_000;
|
|
112
|
-
const QUIET_MS = 60_000;
|
|
113
|
-
const MAX_BACKOFF_MS = 5 * 60_000;
|
|
114
|
-
const MAX_ASKED_WAIT_MS = 60 * 60_000;
|
|
115
|
-
const OWN_CHANGE_WAIT_MS = 3_000;
|
|
116
|
-
// The platform answers within about 35 s; past this the connection died
|
|
117
|
-
// quietly (a laptop waking, a network switch).
|
|
118
|
-
const REQUEST_TIMEOUT_MS = 60_000;
|
|
119
|
-
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
120
|
-
// A wait the server or a proxy sets. This code ships inside published apps, so
|
|
121
|
-
// a bad value must neither flood the platform nor stall a tab for good.
|
|
122
|
-
const serverMs = (value, max) => typeof value === 'number' && value > 0 ? Math.min(value, max) : undefined;
|
|
123
|
-
/**
|
|
124
|
-
* One request per tab, held open by the platform until the database's change
|
|
125
|
-
* counter moves. It never carries data: when something changed, the queries on
|
|
126
|
-
* screen refetch through the app's own endpoints, so each user still sees only
|
|
127
|
-
* what those endpoints allow.
|
|
128
|
-
*/
|
|
129
|
-
function startLiveUpdates(client) {
|
|
130
|
-
let seq;
|
|
131
|
-
let hiddenSince;
|
|
132
|
-
let leftPage = false;
|
|
133
|
-
let backoffMs = 0;
|
|
134
|
-
let refreshGapMs = MIN_REFRESH_GAP_MS;
|
|
135
|
-
// More room between refetches, when the server asks for it (`minRefreshMs`).
|
|
136
|
-
let serverMinGapMs = 0;
|
|
137
|
-
let lastRefreshAt = 0;
|
|
138
|
-
let refetches = 0;
|
|
139
|
-
let request;
|
|
140
|
-
let wake;
|
|
141
|
-
let endBackoff;
|
|
142
|
-
// Settled writes waiting for their own change to come back.
|
|
143
|
-
let ownChange;
|
|
144
|
-
let changedDuringWrites = false;
|
|
145
|
-
const listening = () => !leftPage &&
|
|
146
|
-
navigator.onLine &&
|
|
147
|
-
(hiddenSince === undefined || Date.now() - hiddenSince < HIDDEN_GRACE_MS) &&
|
|
148
|
-
client
|
|
149
|
-
.getQueryCache()
|
|
150
|
-
.findAll({ type: 'active', predicate: takesRefetches }).length > 0;
|
|
151
|
-
const nudge = () => wake?.();
|
|
152
|
-
// Back in view or online: ask now rather than finish a backoff after errors.
|
|
153
|
-
const resume = () => {
|
|
154
|
-
nudge();
|
|
155
|
-
endBackoff?.();
|
|
156
|
-
};
|
|
157
|
-
const hide = () => {
|
|
158
|
-
hiddenSince = Date.now();
|
|
159
|
-
setTimeout(() => {
|
|
160
|
-
if (!listening())
|
|
161
|
-
request?.abort();
|
|
162
|
-
}, HIDDEN_GRACE_MS);
|
|
163
|
-
};
|
|
164
|
-
document.addEventListener('visibilitychange', () => {
|
|
165
|
-
if (document.visibilityState === 'hidden')
|
|
166
|
-
return hide();
|
|
167
|
-
hiddenSince = undefined;
|
|
168
|
-
resume();
|
|
169
|
-
});
|
|
170
|
-
// A tab opened in the background hears no change of visibility until shown.
|
|
171
|
-
if (document.visibilityState === 'hidden')
|
|
172
|
-
hide();
|
|
173
|
-
window.addEventListener('online', resume);
|
|
174
|
-
window.addEventListener('offline', () => request?.abort());
|
|
175
|
-
// A request left open keeps the page out of the back/forward cache.
|
|
176
|
-
window.addEventListener('pagehide', () => {
|
|
177
|
-
leftPage = true;
|
|
178
|
-
request?.abort();
|
|
179
|
-
});
|
|
180
|
-
window.addEventListener('pageshow', () => {
|
|
181
|
-
leftPage = false;
|
|
182
|
-
resume();
|
|
183
|
-
});
|
|
184
|
-
// Any change to the cache: a query mounting, or one switched on later with
|
|
185
|
-
// `enabled`, may be the first on screen.
|
|
186
|
-
client.getQueryCache().subscribe(nudge);
|
|
187
|
-
const refetchNow = () => {
|
|
188
|
-
clearTimeout(ownChange);
|
|
189
|
-
ownChange = undefined;
|
|
190
|
-
changedDuringWrites = false;
|
|
191
|
-
lastRefreshAt = Date.now();
|
|
192
|
-
refetches += 1;
|
|
193
|
-
refetchOnScreen(client);
|
|
194
|
-
};
|
|
195
|
-
// A write that changed the database hears about it here like any other
|
|
196
|
-
// change, so it refetches once, on that notice. One that left the database
|
|
197
|
-
// alone, or whose notice is lost, refetches after a moment, and a refused
|
|
198
|
-
// one, which sends no notice, at once.
|
|
199
|
-
afterWrites = (_client, failed) => {
|
|
200
|
-
clearTimeout(ownChange);
|
|
201
|
-
if (!live || failed || changedDuringWrites)
|
|
202
|
-
return refetchNow();
|
|
203
|
-
ownChange = setTimeout(() => {
|
|
204
|
-
ownChange = undefined;
|
|
205
|
-
if (client.isMutating() === 0)
|
|
206
|
-
refetchNow();
|
|
207
|
-
}, OWN_CHANGE_WAIT_MS);
|
|
208
|
-
};
|
|
209
|
-
const refresh = async () => {
|
|
210
|
-
// A pending write refetches when it settles, which covers this change.
|
|
211
|
-
// One whose patch is on screen has to: refetching now would paint over
|
|
212
|
-
// it before the server has it.
|
|
213
|
-
const leaveToWrites = () => {
|
|
214
|
-
if (client.isMutating() === 0)
|
|
215
|
-
return false;
|
|
216
|
-
changedDuringWrites = true;
|
|
217
|
-
return patchOnScreen(client);
|
|
218
|
-
};
|
|
219
|
-
if (leaveToWrites())
|
|
220
|
-
return;
|
|
221
|
-
if (ownChange)
|
|
222
|
-
return refetchNow();
|
|
223
|
-
const refetchesBefore = refetches;
|
|
224
|
-
// Changes that keep coming (a busy database, or a read whose endpoint
|
|
225
|
-
// writes) space refetches out, up to 10 s apart until things go quiet.
|
|
226
|
-
const sinceLast = Date.now() - lastRefreshAt;
|
|
227
|
-
const nextGapMs = sinceLast < QUIET_MS
|
|
228
|
-
? Math.min(refreshGapMs * 2, MAX_REFRESH_GAP_MS)
|
|
229
|
-
: MIN_REFRESH_GAP_MS;
|
|
230
|
-
const gap = Math.max(nextGapMs, serverMinGapMs);
|
|
231
|
-
// Spread out so the open tabs of a busy app don't all refetch at once.
|
|
232
|
-
await sleep(Math.max(0, gap - sinceLast) + 200 + Math.random() * 1300);
|
|
233
|
-
// A write that settled meanwhile already refetched.
|
|
234
|
-
if (refetches !== refetchesBefore || leaveToWrites())
|
|
235
|
-
return;
|
|
236
|
-
refreshGapMs = nextGapMs;
|
|
237
|
-
refetchNow();
|
|
238
|
-
};
|
|
239
|
-
const backOff = (askedMs) => {
|
|
240
|
-
live = false;
|
|
241
|
-
backoffMs =
|
|
242
|
-
askedMs ?? Math.min(MAX_BACKOFF_MS, Math.max(2_000, backoffMs * 2));
|
|
243
|
-
// Spread out, and never sooner than asked.
|
|
244
|
-
return Math.min(MAX_ASKED_WAIT_MS, Math.max(MIN_POLL_GAP_MS, backoffMs) * (1 + Math.random() / 2));
|
|
245
|
-
};
|
|
246
|
-
const run = async () => {
|
|
247
|
-
for (;;) {
|
|
248
|
-
if (!listening()) {
|
|
249
|
-
await new Promise(resolve => (wake = resolve));
|
|
250
|
-
continue;
|
|
251
|
-
}
|
|
252
|
-
const startedAt = Date.now();
|
|
253
|
-
const firstAsk = seq === undefined;
|
|
254
|
-
const url = seq === undefined
|
|
255
|
-
? CHANGES_PATH
|
|
256
|
-
: `${CHANGES_PATH}?since=${encodeURIComponent(seq)}`;
|
|
257
|
-
const thisRequest = new AbortController();
|
|
258
|
-
request = thisRequest;
|
|
259
|
-
let timedOut = false;
|
|
260
|
-
const timeout = setTimeout(() => {
|
|
261
|
-
timedOut = true;
|
|
262
|
-
thisRequest.abort();
|
|
263
|
-
}, REQUEST_TIMEOUT_MS);
|
|
264
|
-
let pause = MIN_POLL_GAP_MS;
|
|
265
|
-
let afterError = false;
|
|
266
|
-
let changed = false;
|
|
267
|
-
try {
|
|
268
|
-
// The editor preview's caller token, as endpoint calls send it.
|
|
269
|
-
const token = window._ziteUsageToken;
|
|
270
|
-
const response = await fetch(url, {
|
|
271
|
-
signal: thisRequest.signal,
|
|
272
|
-
cache: 'no-store',
|
|
273
|
-
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
|
|
274
|
-
});
|
|
275
|
-
const isJson = response.headers
|
|
276
|
-
.get('content-type')
|
|
277
|
-
?.includes('application/json');
|
|
278
|
-
// Signed out, or a host without live updates (an app published before
|
|
279
|
-
// them answers with the page itself): stop until the page reloads.
|
|
280
|
-
// Any other error, an error page from a proxy included, is retried.
|
|
281
|
-
if (response.status === 401 ||
|
|
282
|
-
response.status === 404 ||
|
|
283
|
-
(response.ok && !isJson)) {
|
|
284
|
-
live = false;
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
const body = response.ok ? await response.json() : {};
|
|
288
|
-
serverMinGapMs = serverMs(body.minRefreshMs, MAX_BACKOFF_MS) ?? 0;
|
|
289
|
-
const retryInMs = serverMs(body.retryInMs, MAX_ASKED_WAIT_MS);
|
|
290
|
-
if (!response.ok || typeof body.seq !== 'string') {
|
|
291
|
-
const retryAfterMs = serverMs(Number(response.headers.get('Retry-After')) * 1000, MAX_ASKED_WAIT_MS);
|
|
292
|
-
afterError = retryAfterMs === undefined;
|
|
293
|
-
pause = backOff(retryAfterMs);
|
|
294
|
-
}
|
|
295
|
-
else if (retryInMs) {
|
|
296
|
-
// The server isn't watching for now (switched off, or busy). It
|
|
297
|
-
// answers with the `since` it was given, so `seq` stays as it is.
|
|
298
|
-
pause = backOff(retryInMs);
|
|
299
|
-
}
|
|
300
|
-
else if (!firstAsk &&
|
|
301
|
-
!body.changed &&
|
|
302
|
-
Date.now() - startedAt < MIN_POLL_GAP_MS) {
|
|
303
|
-
// "Nothing changed" said at once means the server couldn't wait.
|
|
304
|
-
seq = body.seq;
|
|
305
|
-
pause = backOff();
|
|
306
|
-
}
|
|
307
|
-
else {
|
|
308
|
-
live = true;
|
|
309
|
-
backoffMs = 0;
|
|
310
|
-
seq = body.seq;
|
|
311
|
-
changed = body.changed === true;
|
|
312
|
-
}
|
|
313
|
-
}
|
|
314
|
-
catch {
|
|
315
|
-
// Aborted because the tab was hidden, went offline, left the page or
|
|
316
|
-
// the connection died: catch up from `seq` once it's back. A request
|
|
317
|
-
// that went unanswered says nothing is watching meanwhile.
|
|
318
|
-
if (thisRequest.signal.aborted) {
|
|
319
|
-
if (timedOut)
|
|
320
|
-
live = false;
|
|
321
|
-
continue;
|
|
322
|
-
}
|
|
323
|
-
afterError = true;
|
|
324
|
-
pause = backOff();
|
|
325
|
-
}
|
|
326
|
-
finally {
|
|
327
|
-
clearTimeout(timeout);
|
|
328
|
-
}
|
|
329
|
-
if (changed)
|
|
330
|
-
await refresh();
|
|
331
|
-
await new Promise(resolve => {
|
|
332
|
-
const timer = setTimeout(resolve, pause);
|
|
333
|
-
if (afterError) {
|
|
334
|
-
endBackoff = () => {
|
|
335
|
-
clearTimeout(timer);
|
|
336
|
-
resolve();
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
});
|
|
340
|
-
endBackoff = undefined;
|
|
341
|
-
}
|
|
342
|
-
};
|
|
343
|
-
void run();
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* A classic app's TanStack Query client, which its `src/main.tsx` provides.
|
|
347
|
-
* Pages read with useQuery and write with useMutation; this adds what they
|
|
348
|
-
* shouldn't each have to write:
|
|
349
|
-
* - a refused write puts back what its onMutate patched (when no other
|
|
350
|
-
* write is pending), and once the last write settles, what's on screen
|
|
351
|
-
* refetches;
|
|
352
|
-
* - when anyone changes the app's database (another user, another app, the
|
|
353
|
-
* table editor, an automation), what's on screen refetches by itself;
|
|
354
|
-
* - in an app whose zite.config.json says `"deviceCache": "disk"`, what
|
|
355
|
-
* queries return is kept on the device for whoever is signed in, so a
|
|
356
|
-
* reload shows it at once (see `keepOnDevice`).
|
|
357
|
-
*
|
|
358
|
-
* A query that is costly to run again (an AI call, a rate-limited integration)
|
|
359
|
-
* opts out of both refetches with `meta: { live: false }`, and one whose data
|
|
360
|
-
* mustn't stay on the device with `meta: { persist: false }`.
|
|
361
|
-
*/
|
|
362
|
-
exports.queryClient = createQueryClient();
|
|
363
|
-
// Not under automation (screenshots, tests), where an open request keeps the
|
|
364
|
-
// page from ever going idle.
|
|
365
|
-
if (typeof window !== 'undefined' && !navigator.webdriver) {
|
|
366
|
-
// A failing write mustn't put back what the previous user saw.
|
|
367
|
-
(0, deviceCache_js_1.keepOnDevice)(exports.queryClient, { onOwnerChange: () => snapshots.clear() });
|
|
368
|
-
startLiveUpdates(exports.queryClient);
|
|
369
|
-
}
|