zitejs 0.10.0 → 0.10.1-device.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/dist/cjs/auth/actions.js +2 -0
- package/dist/cjs/auth/client.js +5 -0
- package/dist/cjs/auth/useAuth.test.js +1 -0
- package/dist/cjs/caller/index.js +5 -16
- package/dist/cjs/internal/browserMode.d.ts +2 -0
- package/dist/cjs/internal/browserMode.js +18 -0
- package/dist/cjs/internal/deviceCache.d.ts +11 -0
- package/dist/cjs/internal/deviceCache.js +29 -0
- package/dist/cjs/query/deviceCache.d.ts +14 -0
- package/dist/cjs/query/deviceCache.js +304 -0
- package/dist/cjs/query/index.d.ts +19 -0
- package/dist/cjs/query/index.js +369 -0
- package/dist/cjs/vite/index.js +41 -0
- package/dist/cjs/vite/index.test.js +36 -0
- package/dist/esm/auth/actions.js +2 -0
- package/dist/esm/auth/client.js +5 -0
- package/dist/esm/auth/useAuth.test.js +1 -0
- package/dist/esm/caller/index.js +4 -15
- package/dist/esm/internal/browserMode.d.ts +2 -0
- package/dist/esm/internal/browserMode.js +15 -0
- package/dist/esm/internal/deviceCache.d.ts +11 -0
- package/dist/esm/internal/deviceCache.js +24 -0
- package/dist/esm/query/deviceCache.d.ts +14 -0
- package/dist/esm/query/deviceCache.js +301 -0
- package/dist/esm/query/index.d.ts +19 -0
- package/dist/esm/query/index.js +366 -0
- package/dist/esm/start/build/vite.js +4 -0
- package/dist/esm/start/classicOnly.js +3 -3
- package/dist/esm/start/version.d.ts +1 -1
- package/dist/esm/start/version.js +1 -1
- package/dist/esm/vite/index.js +41 -0
- package/dist/esm/vite/index.test.js +36 -0
- package/package.json +12 -2
|
@@ -0,0 +1,369 @@
|
|
|
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
|
+
}
|
package/dist/cjs/vite/index.js
CHANGED
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.ziteId = ziteId;
|
|
7
7
|
const parser_1 = require("@babel/parser");
|
|
8
8
|
const magic_string_1 = __importDefault(require("magic-string"));
|
|
9
|
+
const fs_1 = require("fs");
|
|
9
10
|
const path_1 = __importDefault(require("path"));
|
|
10
11
|
const estree_walker_1 = require("estree-walker");
|
|
11
12
|
const domTagNames_js_1 = require("./domTagNames.js");
|
|
@@ -69,11 +70,51 @@ function classifyElement(name) {
|
|
|
69
70
|
}
|
|
70
71
|
return null;
|
|
71
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* What zitejs/query needs to keep data on the device, in a built page: an id
|
|
75
|
+
* for this build, so data an older build saved is never shown, and the app's
|
|
76
|
+
* `deviceCache` from `zite.config.json` beside the vite config. Only `"disk"`
|
|
77
|
+
* keeps anything: an app that hasn't chosen, or whose config can't be read,
|
|
78
|
+
* keeps nothing.
|
|
79
|
+
*/
|
|
80
|
+
const deviceCacheTags = (appDir, build) => {
|
|
81
|
+
let deviceCache;
|
|
82
|
+
try {
|
|
83
|
+
deviceCache = JSON.parse((0, fs_1.readFileSync)(path_1.default.join(appDir, 'zite.config.json'), 'utf8')).deviceCache;
|
|
84
|
+
}
|
|
85
|
+
catch { }
|
|
86
|
+
return [
|
|
87
|
+
{ tag: 'meta', attrs: { name: 'zite-build', content: build } },
|
|
88
|
+
...(deviceCache === 'disk'
|
|
89
|
+
? []
|
|
90
|
+
: [
|
|
91
|
+
{
|
|
92
|
+
tag: 'meta',
|
|
93
|
+
attrs: { name: 'zite-device-cache', content: 'memory' },
|
|
94
|
+
},
|
|
95
|
+
]),
|
|
96
|
+
];
|
|
97
|
+
};
|
|
72
98
|
function ziteId() {
|
|
73
99
|
const cwd = process.cwd();
|
|
100
|
+
let appDir = cwd;
|
|
101
|
+
let building = false;
|
|
102
|
+
// One per build, shared by every page of it.
|
|
103
|
+
const build = `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
|
74
104
|
return {
|
|
75
105
|
name: 'vite-plugin-zite-id',
|
|
76
106
|
enforce: 'pre',
|
|
107
|
+
configResolved(config) {
|
|
108
|
+
// Beside the vite config, as the app's own config reads zite.config.json:
|
|
109
|
+
// the build's cwd isn't always the app's directory.
|
|
110
|
+
appDir = config.configFile
|
|
111
|
+
? path_1.default.dirname(config.configFile)
|
|
112
|
+
: config.root;
|
|
113
|
+
building = config.command === 'build';
|
|
114
|
+
},
|
|
115
|
+
transformIndexHtml() {
|
|
116
|
+
return building ? deviceCacheTags(appDir, build) : [];
|
|
117
|
+
},
|
|
77
118
|
async transform(code, id) {
|
|
78
119
|
// TanStack's route code splitting moves a route's component into its own module, `route.tsx?tsr-split=…`.
|
|
79
120
|
const file = id.split('?')[0];
|
|
@@ -3,6 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const fs_1 = require("fs");
|
|
7
|
+
const os_1 = require("os");
|
|
6
8
|
const path_1 = __importDefault(require("path"));
|
|
7
9
|
const vitest_1 = require("vitest");
|
|
8
10
|
const index_js_1 = require("./index.js");
|
|
@@ -115,3 +117,37 @@ async function transform(code, file = 'src/App.tsx') {
|
|
|
115
117
|
(0, vitest_1.expect)(await transform(source)).toBe(source);
|
|
116
118
|
});
|
|
117
119
|
});
|
|
120
|
+
(0, vitest_1.describe)("ziteId's tags for zitejs/query's device cache", () => {
|
|
121
|
+
const plugin = (command, config) => {
|
|
122
|
+
const dir = (0, fs_1.mkdtempSync)(path_1.default.join((0, os_1.tmpdir)(), 'zite-app-'));
|
|
123
|
+
if (config) {
|
|
124
|
+
(0, fs_1.writeFileSync)(path_1.default.join(dir, 'zite.config.json'), JSON.stringify(config));
|
|
125
|
+
}
|
|
126
|
+
const instance = (0, index_js_1.ziteId)();
|
|
127
|
+
instance.configResolved({
|
|
128
|
+
command,
|
|
129
|
+
configFile: path_1.default.join(dir, 'vite.config.ts'),
|
|
130
|
+
root: process.cwd(),
|
|
131
|
+
});
|
|
132
|
+
return () => Object.fromEntries(instance.transformIndexHtml().map(t => [
|
|
133
|
+
t.attrs?.name,
|
|
134
|
+
t.attrs?.content,
|
|
135
|
+
]));
|
|
136
|
+
};
|
|
137
|
+
(0, vitest_1.it)('keeps data on the device only for an app that chose disk', () => {
|
|
138
|
+
(0, vitest_1.expect)(plugin('build', { deviceCache: 'disk' })()['zite-device-cache']).toBeUndefined();
|
|
139
|
+
(0, vitest_1.expect)(plugin('build', { deviceCache: 'memory' })()['zite-device-cache']).toBe('memory');
|
|
140
|
+
(0, vitest_1.expect)(plugin('build', { id: 'app' })()['zite-device-cache']).toBe('memory');
|
|
141
|
+
(0, vitest_1.expect)(plugin('build')()['zite-device-cache']).toBe('memory');
|
|
142
|
+
});
|
|
143
|
+
(0, vitest_1.it)('gives every page of a build the same id, and each build its own', () => {
|
|
144
|
+
const pages = plugin('build', { deviceCache: 'disk' });
|
|
145
|
+
const id = pages()['zite-build'];
|
|
146
|
+
(0, vitest_1.expect)(id).toMatch(/\w{6,}/);
|
|
147
|
+
(0, vitest_1.expect)(pages()['zite-build']).toBe(id);
|
|
148
|
+
(0, vitest_1.expect)(plugin('build', { deviceCache: 'disk' })()['zite-build']).not.toBe(id);
|
|
149
|
+
});
|
|
150
|
+
(0, vitest_1.it)('tags nothing on a dev server', () => {
|
|
151
|
+
(0, vitest_1.expect)(plugin('serve', { deviceCache: 'disk' })()).toEqual({});
|
|
152
|
+
});
|
|
153
|
+
});
|
package/dist/esm/auth/actions.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { USAGE_TOKEN_QUERY_PARAM } from './constants.js';
|
|
2
2
|
import { browserPreviewClaim, PREVIEW_CLAIM_PARAM } from './previewClaim.js';
|
|
3
3
|
import { profileUpdated } from './profileUpdates.js';
|
|
4
|
+
import { forgetDeviceCache } from '../internal/deviceCache.js';
|
|
4
5
|
export function loginWithRedirect(opts) {
|
|
5
6
|
if (window.location.pathname.startsWith('/auth/'))
|
|
6
7
|
return;
|
|
@@ -42,6 +43,7 @@ export function loginWithRedirect(opts) {
|
|
|
42
43
|
window.location.href = query ? `/auth/login?${query}` : '/auth/login';
|
|
43
44
|
}
|
|
44
45
|
export function logout(opts) {
|
|
46
|
+
forgetDeviceCache();
|
|
45
47
|
void import('./client.js').then(({ signOut }) => signOut().then(() => {
|
|
46
48
|
window.location.href = opts?.returnTo || '/';
|
|
47
49
|
}));
|
package/dist/esm/auth/client.js
CHANGED
|
@@ -3,6 +3,7 @@ import { createAuthClient } from 'better-auth/react';
|
|
|
3
3
|
import { magicLinkClient, inferAdditionalFields, } from 'better-auth/client/plugins';
|
|
4
4
|
import { getAccessMode } from './config.js';
|
|
5
5
|
import { loginWithRedirect, logout } from './actions.js';
|
|
6
|
+
import { sessionChanged } from '../internal/deviceCache.js';
|
|
6
7
|
// Apart from the actions, so an app that never reads the session here (a Start
|
|
7
8
|
// app reads its user from the router) never ships better-auth's client.
|
|
8
9
|
export const authClient = createAuthClient({
|
|
@@ -18,6 +19,10 @@ export const authClient = createAuthClient({
|
|
|
18
19
|
],
|
|
19
20
|
});
|
|
20
21
|
export const useSession = authClient.useSession;
|
|
22
|
+
// better-auth flips this after any call that changes who's signed in (sign-in,
|
|
23
|
+
// sign-up, sign-out) or what's known about them. What the app kept on the
|
|
24
|
+
// device may belong to someone else now.
|
|
25
|
+
authClient.$store.atoms.$sessionSignal?.listen(sessionChanged);
|
|
21
26
|
/**
|
|
22
27
|
* An internal app has no signed-out state — SSO runs before the bundle — so an
|
|
23
28
|
* empty session means it died underneath the app. Only `internal`: elsewhere a
|
package/dist/esm/caller/index.js
CHANGED
|
@@ -1,18 +1,5 @@
|
|
|
1
1
|
import { getEnv } from '../internal/env.js';
|
|
2
|
-
|
|
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
|
-
}
|
|
2
|
+
import { getMode } from '../internal/browserMode.js';
|
|
16
3
|
const ENVIRONMENTS = {
|
|
17
4
|
production: 'https://workflows.zite.com',
|
|
18
5
|
staging: 'https://workflows.zitestaging.com',
|
|
@@ -91,7 +78,9 @@ export function createCaller(endpointOrName, nameOrFlowId, flowId) {
|
|
|
91
78
|
const res = await fetch(url, init);
|
|
92
79
|
if (!res.ok) {
|
|
93
80
|
const text = await res.text().catch(() => '');
|
|
94
|
-
throw new Error(`API call failed (${res.status}): ${text}`)
|
|
81
|
+
throw Object.assign(new Error(`API call failed (${res.status}): ${text}`), {
|
|
82
|
+
status: res.status,
|
|
83
|
+
});
|
|
95
84
|
}
|
|
96
85
|
return res.json();
|
|
97
86
|
};
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
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;
|
|
@@ -0,0 +1,24 @@
|
|
|
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
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
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;
|