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,2 +0,0 @@
1
- /** Whether this page is a live app or one of the platform's previews (the editor, snapshots, sandboxes). */
2
- export declare function getMode(): 'live' | 'preview';
@@ -1,15 +0,0 @@
1
- /** Whether this page is a live app or one of the platform's previews (the editor, snapshots, sandboxes). */
2
- export function getMode() {
3
- if (typeof window === 'undefined')
4
- return 'preview';
5
- const host = window.location.host;
6
- return host.startsWith('zite-editor') ||
7
- host.startsWith('zite-action-') ||
8
- host.startsWith('zite-snapshot-') ||
9
- host.endsWith('.zite-dev-sandbox.com') ||
10
- host.endsWith('.zite-sandbox.com') ||
11
- host.endsWith('.zite-dev-app.com') ||
12
- host.endsWith('.zite-app.com')
13
- ? 'preview'
14
- : 'live';
15
- }
@@ -1,11 +0,0 @@
1
- export declare const DEVICE_CACHE_KEY = "zite:query-cache";
2
- export declare const DEVICE_CACHE_OWNER_KEY = "zite:query-cache:owner";
3
- export declare const SESSION_CHANGED_EVENT = "zite:session-changed";
4
- /**
5
- * Clears what the app kept on this device, and stops every tab from saving it
6
- * again until it has checked who is signed in. Runs before a sign-out reaches
7
- * the server, so it holds offline too.
8
- */
9
- export declare const forgetDeviceCache: () => void;
10
- /** Who is signed in on this page changed: forget, and have zitejs/query check again. */
11
- export declare const sessionChanged: () => void;
@@ -1,24 +0,0 @@
1
- // What zitejs/query keeps on the device. An app has its own origin, so one key.
2
- export const DEVICE_CACHE_KEY = 'zite:query-cache';
3
- // Who that belongs to, kept apart so every tab can check it cheaply.
4
- export const DEVICE_CACHE_OWNER_KEY = 'zite:query-cache:owner';
5
- export const SESSION_CHANGED_EVENT = 'zite:session-changed';
6
- /**
7
- * Clears what the app kept on this device, and stops every tab from saving it
8
- * again until it has checked who is signed in. Runs before a sign-out reaches
9
- * the server, so it holds offline too.
10
- */
11
- export const forgetDeviceCache = () => {
12
- try {
13
- localStorage.setItem(DEVICE_CACHE_OWNER_KEY, JSON.stringify({ owner: null, at: Date.now() }));
14
- localStorage.removeItem(DEVICE_CACHE_KEY);
15
- }
16
- catch { }
17
- };
18
- /** Who is signed in on this page changed: forget, and have zitejs/query check again. */
19
- export const sessionChanged = () => {
20
- forgetDeviceCache();
21
- if (typeof window !== 'undefined') {
22
- window.dispatchEvent(new Event(SESSION_CHANGED_EVENT));
23
- }
24
- };
@@ -1,14 +0,0 @@
1
- import { type QueryClient } from '@tanstack/react-query';
2
- /**
3
- * Keeps what the app's queries return in localStorage for whoever is signed
4
- * in, so a reload or a return visit shows it at once and then refetches it.
5
- *
6
- * Signed-out visitors' data is shown before the first render; a signed-in
7
- * user's only once get-session confirms the same user. Each save is labelled
8
- * with who get-session last said this page is for, so any sign-in or sign-out
9
- * this page hears of (zitejs/auth on this page, another tab, a 401) clears the
10
- * device and the screen when the answer changes.
11
- */
12
- export declare function keepOnDevice(client: QueryClient, { onOwnerChange }?: {
13
- onOwnerChange?: () => void;
14
- }): void;
@@ -1,301 +0,0 @@
1
- import { dehydrate, hydrate, } from '@tanstack/react-query';
2
- import { getMode } from '../internal/browserMode.js';
3
- import { DEVICE_CACHE_KEY, DEVICE_CACHE_OWNER_KEY, SESSION_CHANGED_EVENT, } from '../internal/deviceCache.js';
4
- const SIGNED_OUT = 'anon';
5
- // Kept data seeds the screen until its refetch lands, so not much older.
6
- const MAX_AGE_MS = 3 * 24 * 60 * 60_000;
7
- // localStorage holds about 5 MB per origin; leave room for the app's own keys.
8
- const MAX_CHARS = 2_000_000;
9
- const SAVE_EVERY_MS = 10_000;
10
- const read = (key) => {
11
- try {
12
- return JSON.parse(localStorage.getItem(key) ?? 'null') ?? undefined;
13
- }
14
- catch {
15
- return undefined;
16
- }
17
- };
18
- const readOwner = () => read(DEVICE_CACHE_OWNER_KEY);
19
- const writeOwner = (owner) => {
20
- try {
21
- localStorage.setItem(DEVICE_CACHE_OWNER_KEY, JSON.stringify(owner));
22
- }
23
- catch { }
24
- };
25
- const dropKept = () => {
26
- try {
27
- localStorage.removeItem(DEVICE_CACHE_KEY);
28
- }
29
- catch { }
30
- };
31
- const isFresh = (query) => Date.now() - query.state.dataUpdatedAt < MAX_AGE_MS;
32
- const statusOf = (error) => error?.status;
33
- /**
34
- * Comes back from JSON as it went in, as an endpoint's answer does. A Date
35
- * would come back a string and a Map an empty object, and a page reading them
36
- * would break on every reload.
37
- */
38
- const isPlainJson = (value, parents = []) => {
39
- if (value === null || typeof value === 'string')
40
- return true;
41
- if (typeof value === 'boolean')
42
- return true;
43
- if (typeof value === 'number')
44
- return Number.isFinite(value);
45
- if (typeof value !== 'object' || parents.includes(value))
46
- return false;
47
- const proto = Object.getPrototypeOf(value);
48
- if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) {
49
- return false;
50
- }
51
- parents.push(value);
52
- const plain = Object.values(value).every(v => isPlainJson(v, parents));
53
- parents.pop();
54
- return plain;
55
- };
56
- // An infinite list refetches every page it holds, so keep the first.
57
- const firstPageOnly = (data) => {
58
- const list = data;
59
- return Array.isArray(list?.pages) && Array.isArray(list?.pageParams)
60
- ? { pages: list.pages.slice(0, 1), pageParams: list.pageParams.slice(0, 1) }
61
- : data;
62
- };
63
- /**
64
- * The build id when this page may keep data on the device, 'memory' when the
65
- * app or the platform says it mustn't, undefined when it can't. A preview's
66
- * endpoints run as the editor's token or a "Preview as" session and an old
67
- * sign-in's as its stored token, so get-session wouldn't say whose data it is.
68
- */
69
- const deviceCacheMode = () => {
70
- if (getMode() !== 'live')
71
- return undefined;
72
- if (window._ziteUsageToken)
73
- return undefined;
74
- try {
75
- if (localStorage.getItem('zite.auth.token'))
76
- return undefined;
77
- }
78
- catch {
79
- return undefined;
80
- }
81
- const meta = (name) => document.querySelector(`meta[name="${name}"]`)?.content;
82
- if (meta('zite-device-cache') === 'memory')
83
- return 'memory';
84
- return meta('zite-build');
85
- };
86
- /**
87
- * Keeps what the app's queries return in localStorage for whoever is signed
88
- * in, so a reload or a return visit shows it at once and then refetches it.
89
- *
90
- * Signed-out visitors' data is shown before the first render; a signed-in
91
- * user's only once get-session confirms the same user. Each save is labelled
92
- * with who get-session last said this page is for, so any sign-in or sign-out
93
- * this page hears of (zitejs/auth on this page, another tab, a 401) clears the
94
- * device and the screen when the answer changes.
95
- */
96
- export function keepOnDevice(client, { onOwnerChange } = {}) {
97
- const mode = deviceCacheMode();
98
- if (mode === 'memory')
99
- dropKept();
100
- if (mode === undefined || mode === 'memory')
101
- return;
102
- const build = mode;
103
- // Who get-session last said this page is for, and when that was asked.
104
- let confirmed;
105
- let confirmedAt = 0;
106
- let checking;
107
- let askAgain = false;
108
- let unsaved = false;
109
- // Shown from the device and not yet refetched. Kept on the next save even
110
- // once TanStack has dropped the query from memory.
111
- const restored = new Map();
112
- const restore = (kept) => {
113
- const queries = kept.queries.filter(isFresh);
114
- hydrate(client, { mutations: [], queries });
115
- for (const query of queries) {
116
- // hydrate keeps anything fresher already cached.
117
- const cached = client.getQueryCache().get(query.queryHash);
118
- if (cached?.state.dataUpdatedAt === query.state.dataUpdatedAt) {
119
- restored.set(query.queryHash, query);
120
- }
121
- }
122
- // Shown at once, then asked again on mount: it may be days old, and the
123
- // live client's staleTime would otherwise trust it for a minute.
124
- void client.invalidateQueries({
125
- predicate: query => restored.has(query.queryHash),
126
- refetchType: 'none',
127
- });
128
- };
129
- const askSession = async () => {
130
- const res = await fetch('/api/auth/get-session', {
131
- credentials: 'include',
132
- cache: 'no-store',
133
- });
134
- // An internal app's revoked access is no one.
135
- if (res.status === 401)
136
- return SIGNED_OUT;
137
- if (!res.ok)
138
- return undefined;
139
- const body = (await res.json());
140
- return body?.user?.id ?? SIGNED_OUT;
141
- };
142
- // Nothing is saved while this runs, and it asks again when the session
143
- // changes meanwhile, so the answer is never older than what it's used for.
144
- const check = () => (checking ??= (async () => {
145
- let owner;
146
- let askedAt;
147
- do {
148
- askAgain = false;
149
- askedAt = Date.now();
150
- owner = await askSession().catch(() => undefined);
151
- } while (askAgain);
152
- confirmed = owner;
153
- confirmedAt = askedAt;
154
- })().finally(() => (checking = undefined)));
155
- // What's cached was fetched for whoever was signed in before, so when that
156
- // changed, it goes from the device and the screen. `claimed`: who another
157
- // tab now says the device is for (null once someone signed out there). If
158
- // that isn't who this page finds, the session changed under it unseen.
159
- const onSessionChange = async (claimed) => {
160
- const before = confirmed;
161
- if (checking)
162
- askAgain = true;
163
- await check();
164
- if (confirmed === undefined)
165
- return;
166
- // Unknown before only while this page's first check ran: someone signed
167
- // in or out on this page then, unless it's another tab agreeing.
168
- const changedHere = before !== confirmed && (before !== undefined || claimed === undefined);
169
- const changedElsewhere = claimed !== undefined && claimed !== confirmed;
170
- if (!changedHere && !changedElsewhere)
171
- return;
172
- dropKept();
173
- writeOwner({ owner: confirmed, at: confirmedAt });
174
- restored.clear();
175
- onOwnerChange?.();
176
- void client.resetQueries();
177
- };
178
- const save = () => {
179
- if (!unsaved)
180
- return;
181
- if (confirmed === undefined || checking) {
182
- // A check that failed (offline at startup) is tried again here.
183
- if (!checking)
184
- void check();
185
- return;
186
- }
187
- // What's on screen may be a pending write's patch, not what the server has.
188
- if (client.isMutating() > 0)
189
- return;
190
- const owner = readOwner();
191
- // Someone signed out here, or in or out in another tab, after this page
192
- // last asked who it's for.
193
- if (owner && owner.owner !== confirmed && owner.at > confirmedAt)
194
- return;
195
- const inMemory = dehydrate(client, {
196
- shouldDehydrateQuery: (query) => query.state.status === 'success' &&
197
- query.meta?.persist !== false &&
198
- isFresh(query),
199
- }).queries.map(query => ({
200
- ...query,
201
- state: { ...query.state, data: firstPageOnly(query.state.data) },
202
- }));
203
- const dropped = [...restored.values()].filter(query => !client.getQueryCache().get(query.queryHash) && isFresh(query));
204
- const parts = [];
205
- let size = 0;
206
- for (const query of [...inMemory, ...dropped].sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)) {
207
- if (!isPlainJson(query.state.data))
208
- continue;
209
- let json;
210
- try {
211
- json = JSON.stringify(query);
212
- }
213
- catch {
214
- continue; // a key or meta that isn't JSON
215
- }
216
- if (size + json.length > MAX_CHARS)
217
- continue;
218
- parts.push(json);
219
- size += json.length;
220
- }
221
- try {
222
- localStorage.setItem(DEVICE_CACHE_KEY, `{"v":2,"owner":${JSON.stringify(confirmed)},"build":${JSON.stringify(build)},"queries":[${parts.join(',')}]}`);
223
- writeOwner({ owner: confirmed, at: Date.now() });
224
- unsaved = false;
225
- }
226
- catch {
227
- dropKept();
228
- }
229
- };
230
- const kept = read(DEVICE_CACHE_KEY);
231
- const usable = kept?.v === 2 && kept.build === build ? kept : undefined;
232
- if (kept && !usable)
233
- dropKept();
234
- if (usable?.owner === SIGNED_OUT)
235
- restore(usable);
236
- void check().then(() => {
237
- if (confirmed === undefined || !usable)
238
- return;
239
- if (usable.owner === confirmed) {
240
- if (confirmed !== SIGNED_OUT)
241
- restore(usable);
242
- return;
243
- }
244
- dropKept();
245
- writeOwner({ owner: confirmed, at: confirmedAt });
246
- });
247
- let saveTimer;
248
- client.getQueryCache().subscribe(event => {
249
- if (event.type === 'removed') {
250
- unsaved = true;
251
- return;
252
- }
253
- if (event.type !== 'updated')
254
- return;
255
- const { action, query } = event;
256
- if (action.type === 'success') {
257
- if (!action.manual)
258
- restored.delete(query.queryHash);
259
- unsaved = true;
260
- saveTimer ??= setTimeout(() => {
261
- saveTimer = undefined;
262
- save();
263
- }, SAVE_EVERY_MS);
264
- }
265
- else if (action.type === 'error') {
266
- const status = statusOf(action.error);
267
- // Shown from the device, then refused: leave it as a reload would.
268
- if (restored.delete(query.queryHash) &&
269
- (status === 401 || status === 403 || status === 404)) {
270
- unsaved = true;
271
- void client.resetQueries({ queryKey: query.queryKey, exact: true });
272
- }
273
- // A signed-out visitor's 401 is expected; a signed-in user's session
274
- // may have ended.
275
- if (status === 401 &&
276
- confirmed !== undefined &&
277
- confirmed !== SIGNED_OUT) {
278
- void onSessionChange();
279
- }
280
- }
281
- });
282
- document.addEventListener('visibilitychange', () => {
283
- if (document.visibilityState === 'hidden')
284
- save();
285
- });
286
- window.addEventListener('pagehide', save);
287
- // Back from the back/forward cache, where storage events don't arrive.
288
- window.addEventListener('pageshow', event => {
289
- if (event.persisted)
290
- void onSessionChange();
291
- });
292
- window.addEventListener(SESSION_CHANGED_EVENT, () => void onSessionChange());
293
- window.addEventListener('storage', event => {
294
- if (event.key !== DEVICE_CACHE_OWNER_KEY && event.key !== null)
295
- return;
296
- const claimed = readOwner()?.owner ?? null;
297
- if (confirmed !== undefined && claimed === confirmed)
298
- return;
299
- void onSessionChange(claimed);
300
- });
301
- }
@@ -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;