zitejs 0.10.1-device.0 → 0.10.1

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