gemi 0.205.3 → 0.206.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.
Files changed (31) hide show
  1. package/dist/{chunk-k21eg3pn.js → chunk-j9ga7b74.js} +1 -1
  2. package/dist/{chunk-rbndzqg7.js → chunk-jr5t2hrk.js} +1 -1
  3. package/dist/{chunk-zwznp46g.js → chunk-qjk68wda.js} +2 -2
  4. package/dist/{chunk-zwznp46g.js.map → chunk-qjk68wda.js.map} +3 -3
  5. package/dist/{chunk-bdrce9s8.js → chunk-s4tq4y69.js} +1 -1
  6. package/dist/{chunk-bz84hrc3.js → chunk-xmpamj50.js} +2 -2
  7. package/dist/{chunk-bz84hrc3.js.map → chunk-xmpamj50.js.map} +1 -1
  8. package/dist/client/index.d.ts +2 -0
  9. package/dist/client/index.d.ts.map +1 -1
  10. package/dist/client/index.js +527 -148
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/queryEffects.d.ts +106 -0
  13. package/dist/client/queryEffects.d.ts.map +1 -0
  14. package/dist/client/useMultipleQuery.d.ts +83 -0
  15. package/dist/client/useMultipleQuery.d.ts.map +1 -0
  16. package/dist/client/useQuery.d.ts +11 -0
  17. package/dist/client/useQuery.d.ts.map +1 -1
  18. package/dist/facades/index.js +1 -1
  19. package/dist/http/index.js +1 -1
  20. package/dist/i18n/index.js +1 -1
  21. package/dist/kernel/index.js +1 -1
  22. package/dist/server/index.js +1 -1
  23. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts +3 -3
  24. package/dist/services/change-feed/DatabaseChangeFeedDriver.d.ts.map +1 -1
  25. package/dist/services/index.js +1 -1
  26. package/package.json +1 -1
  27. package/skills/gemi-react-best-practices/SKILL.md +3 -1
  28. package/skills/gemi-react-best-practices/rules/query-multiple-query-per-component.md +68 -0
  29. /package/dist/{chunk-k21eg3pn.js.map → chunk-j9ga7b74.js.map} +0 -0
  30. /package/dist/{chunk-rbndzqg7.js.map → chunk-jr5t2hrk.js.map} +0 -0
  31. /package/dist/{chunk-bdrce9s8.js.map → chunk-s4tq4y69.js.map} +0 -0
@@ -29,7 +29,174 @@ function isPlainObject(value) {
29
29
  return value !== null && typeof value === "object" && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
30
30
  }
31
31
  //#endregion
32
- //#region client/useQuery.ts
32
+ //#region client/queryEffects.ts
33
+ /**
34
+ * Where a query reads from: the resolved path (route params from the URL,
35
+ * overridden by `options.params`) and the variant key of its `search`.
36
+ */
37
+ function resolveQueryTarget(url, options, routeParams) {
38
+ const params = "params" in options ? {
39
+ ...routeParams,
40
+ ...options.params
41
+ } : routeParams;
42
+ const search = "search" in options ? options.search ?? {} : {};
43
+ return {
44
+ params,
45
+ search,
46
+ path: applyParams$1(url, params),
47
+ variantKey: toVariantKey(search)
48
+ };
49
+ }
50
+ /**
51
+ * Per-call config over the provider's `queryConfig`. Only *defined* per-call
52
+ * keys participate: a key explicitly set to `undefined` (`{ suspense: cond ?
53
+ * true : undefined }`, forwarding an optional prop) falls through to the
54
+ * provider default instead of clobbering it.
55
+ */
56
+ function mergeDefinedConfig(base, ...overrides) {
57
+ const merged = { ...base };
58
+ for (const override of overrides) {
59
+ if (!override) continue;
60
+ for (const key of Object.keys(override)) {
61
+ const value = override[key];
62
+ if (value !== void 0) merged[key] = value;
63
+ }
64
+ }
65
+ return merged;
66
+ }
67
+ /**
68
+ * A failed `suspense: false` query: schedule the background retry its retry
69
+ * policy allows. The resource owns the timer, one per variant however many
70
+ * readers render it.
71
+ */
72
+ function retryFailedQuery(resource, variantKey, snapshot, cfg) {
73
+ if (!snapshot?.error || snapshot.loading) return;
74
+ const error = snapshot.error;
75
+ const failureCount = Math.max(1, resource.failureCount(variantKey));
76
+ if (!shouldRetryQuery(failureCount, error, cfg.retry)) return;
77
+ const delay = retryDelayFor(failureCount, error, cfg.retryDelay, cfg.retryIntervalOnError);
78
+ if (cfg.debug) console.log("retrying", variantKey, "in", delay);
79
+ resource.scheduleRetry(variantKey, delay);
80
+ }
81
+ /**
82
+ * Coming back online retries a query that failed in a way another attempt
83
+ * might fix, as long as its retry policy would retry that error at all.
84
+ * Silent, and it starts a fresh run of failures. Returns the cleanup.
85
+ */
86
+ function retryWhenOnline(resource, variantKey, getConfig) {
87
+ if (typeof window === "undefined") return () => {};
88
+ const onOnline = () => {
89
+ const state = resource.peek(variantKey);
90
+ if (!state?.error) return;
91
+ if (!shouldRetryQuery(1, state.error, getConfig().retry)) return;
92
+ resource.retryNow(variantKey);
93
+ };
94
+ window.addEventListener("online", onOnline);
95
+ return () => window.removeEventListener("online", onOnline);
96
+ }
97
+ function createPollState() {
98
+ return {
99
+ timer: null,
100
+ duration: 0,
101
+ snapshot: void 0,
102
+ resource: null,
103
+ variantKey: null,
104
+ awaiting: false
105
+ };
106
+ }
107
+ /**
108
+ * One step of the `refetchUntil` poll, run after every commit so the
109
+ * predicate always sees the current render's closure. New data (or another
110
+ * resource/variant) clears the pending timer and asks the predicate again; on
111
+ * a plain re-render a pending timer is kept, so frequent renders never push
112
+ * the next refetch back. `paused` (a live channel is open) stops it.
113
+ */
114
+ function stepPoll(poll, resource, variantKey, snapshot, refetchUntil, paused) {
115
+ const clear = () => {
116
+ if (poll.timer) clearTimeout(poll.timer);
117
+ poll.timer = null;
118
+ };
119
+ if (poll.snapshot !== snapshot || poll.resource !== resource || poll.variantKey !== variantKey) {
120
+ clear();
121
+ poll.awaiting = false;
122
+ poll.snapshot = snapshot;
123
+ poll.resource = resource;
124
+ poll.variantKey = variantKey;
125
+ }
126
+ if (!refetchUntil || paused || !snapshot || snapshot.loading || !snapshot.hasData || snapshot.error) {
127
+ clear();
128
+ return;
129
+ }
130
+ if (poll.awaiting) return;
131
+ const nextDuration = refetchUntil(snapshot.data, poll.duration);
132
+ if (!(nextDuration > 0)) {
133
+ clear();
134
+ poll.duration = 0;
135
+ return;
136
+ }
137
+ if (poll.timer) return;
138
+ poll.duration = nextDuration;
139
+ poll.timer = setTimeout(() => {
140
+ poll.timer = null;
141
+ poll.awaiting = true;
142
+ resource.refetch(variantKey);
143
+ }, nextDuration);
144
+ }
145
+ /** Unmount: drop the pending poll. */
146
+ function stopPoll(poll) {
147
+ if (poll.timer) clearTimeout(poll.timer);
148
+ poll.timer = null;
149
+ poll.snapshot = void 0;
150
+ poll.awaiting = false;
151
+ }
152
+ /** The `refreshInterval` / HMR `http-reload` reload of one query. */
153
+ function reloadQuery(resource, variantKey, cfg) {
154
+ if (cfg.debug) console.log("Reloading query for", variantKey);
155
+ const data = resource.getVariant(variantKey, cfg.staleTime).data;
156
+ resource.mutate(variantKey, () => data);
157
+ }
158
+ /** Subscribe to Vite's `http-reload` event. Returns the cleanup. */
159
+ function onHttpReload(handler) {
160
+ if (typeof import.meta.hot?.on === "function") import.meta.hot.on("http-reload", handler);
161
+ return () => {
162
+ if (typeof import.meta.hot?.off === "function") import.meta.hot.off("http-reload", handler);
163
+ };
164
+ }
165
+ /**
166
+ * Revalidate when the tab comes back to the foreground, gated by `staleTime`
167
+ * and always silent. Three guards decide whether a return is owed a request:
168
+ * eligibility, the away latch (`focus` also fires for a dismissed `alert`),
169
+ * and the throttle (an embedded iframe blurs and focuses the window on every
170
+ * click). Both `focus` and `visibilitychange` are listened for because
171
+ * neither covers the other. Returns the cleanup.
172
+ */
173
+ function revalidateOnFocus(resource, variantKey, focus, getConfig) {
174
+ const markAway = () => {
175
+ focus.wasAway = true;
176
+ };
177
+ const revalidate = () => {
178
+ if (!focus.eligible) return;
179
+ if (document.visibilityState === "hidden") return;
180
+ if (!focus.wasAway) return;
181
+ const now = Date.now();
182
+ if (now - focus.last < (getConfig().focusThrottleInterval ?? 0)) return;
183
+ focus.wasAway = false;
184
+ focus.last = now;
185
+ resource.revalidate(variantKey, getConfig().staleTime);
186
+ };
187
+ const onVisibilityChange = () => {
188
+ if (document.visibilityState === "hidden") markAway();
189
+ else revalidate();
190
+ };
191
+ window.addEventListener("blur", markAway);
192
+ window.addEventListener("focus", revalidate);
193
+ document.addEventListener("visibilitychange", onVisibilityChange);
194
+ return () => {
195
+ window.removeEventListener("blur", markAway);
196
+ window.removeEventListener("focus", revalidate);
197
+ document.removeEventListener("visibilitychange", onVisibilityChange);
198
+ };
199
+ }
33
200
  /**
34
201
  * A DOM event or React's synthetic one. Never a plain object, so a cached
35
202
  * value that happens to have a `nativeEvent` key is not mistaken for one.
@@ -39,6 +206,45 @@ function isEventLike(value) {
39
206
  if (typeof Event !== "undefined" && value instanceof Event) return true;
40
207
  return "nativeEvent" in value && typeof value.preventDefault === "function";
41
208
  }
209
+ /**
210
+ * `mutate(value | updater)` for one query; a bare `mutate()` refetches.
211
+ * Returns whether it went to the wire for a refetch (the caller marks the
212
+ * query as fetched).
213
+ */
214
+ function mutateQuery(resource, variantKey, fn) {
215
+ if (isEventLike(fn)) fn = void 0;
216
+ if (!fn) {
217
+ resource.refetch(variantKey);
218
+ return "refetch";
219
+ }
220
+ resource.mutate(variantKey, (data) => {
221
+ if (data === void 0) {
222
+ console.warn("Mutate function called before the query.");
223
+ return data;
224
+ }
225
+ const updatedData = typeof fn === "function" ? fn(data) : fn;
226
+ if (isPlainObject(data)) {
227
+ if (isPlainObject(updatedData)) return updatedData;
228
+ throw new Error("Mutate function must return an object when the current data is an object.");
229
+ }
230
+ if (Array.isArray(data)) {
231
+ if (Array.isArray(updatedData)) return updatedData;
232
+ throw new Error("Mutate function must return an array when the current data is an array.");
233
+ }
234
+ if (typeof data !== typeof updatedData) throw new Error("Mutate function must return the same type as the current data.");
235
+ return updatedData;
236
+ });
237
+ return "update";
238
+ }
239
+ /**
240
+ * The dev warning for a suspense query a server render had no data for.
241
+ */
242
+ function warnUnprefetched(url, variantKey, hook = "useQuery") {
243
+ const searchHint = variantKey ? `, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams(variantKey)))} }` : "";
244
+ console.warn(`[gemi] ${hook}("${url}") rendered on the server without data. The server never fetches, so this page ships without it and the client suspends after hydration. Add \`Query.prefetch("${url}"${searchHint})\` to the route's view handler.`);
245
+ }
246
+ //#endregion
247
+ //#region client/useQuery.ts
42
248
  var defaultConfig = {
43
249
  fallbackData: null,
44
250
  keepPreviousData: true,
@@ -58,11 +264,7 @@ var defaultOptions$1 = {
58
264
  function useQuery(url, ...args) {
59
265
  const [options, config] = args;
60
266
  const { user: _user, ...queryConfig } = useContext(QueryConfigContext) ?? {};
61
- const merged = { ...queryConfig };
62
- if (config) {
63
- for (const key of Object.keys(config)) if (config[key] !== void 0) merged[key] = config[key];
64
- }
65
- return useFrameworkQuery(url, options, merged);
267
+ return useFrameworkQuery(url, options, mergeDefinedConfig(queryConfig, config));
66
268
  }
67
269
  /**
68
270
  * `useQuery` minus the app's provider-level `queryConfig`: per-call config
@@ -83,15 +285,9 @@ function useFrameworkQuery(url, ...args) {
83
285
  ..._config
84
286
  };
85
287
  const suspense = config.suspense !== false && !config.lazy;
86
- const params = "params" in options ? {
87
- ..._params,
88
- ...options.params
89
- } : _params;
90
- const search = "search" in options ? options.search ?? {} : {};
288
+ const { params, search, path: currentPath, variantKey: currentVariantKey } = resolveQueryTarget(url, options, _params);
91
289
  const { getResource } = useContext(QueryManagerContext);
92
290
  const serverQueries = useContext(ServerQueryContext);
93
- const currentPath = applyParams$1(url, params);
94
- const currentVariantKey = toVariantKey(search);
95
291
  const deferredPath = useDeferredValue(currentPath);
96
292
  const deferredVariantKey = useDeferredValue(currentVariantKey);
97
293
  const deferVariant = suspense && config.keepPreviousData;
@@ -114,18 +310,14 @@ function useFrameworkQuery(url, ...args) {
114
310
  }, [realtime, liveKey]);
115
311
  const refreshIntervalRef = useRef(null);
116
312
  const fetchedRef = useRef(!lazy);
117
- const pollRef = useRef({
118
- timer: null,
119
- duration: 0,
120
- snapshot: void 0,
121
- resource: null,
122
- variantKey: null,
123
- awaiting: false
124
- });
313
+ const pollRef = useRef(null);
314
+ pollRef.current ??= createPollState();
125
315
  const prefetchedRef = useRef(false);
126
- const focusEligibleRef = useRef(!lazy);
127
- const wasAwayRef = useRef(false);
128
- const lastFocusRevalidationRef = useRef(0);
316
+ const focusRef = useRef({
317
+ eligible: !lazy,
318
+ wasAway: false,
319
+ last: 0
320
+ });
129
321
  const subscribe = useCallback((onStoreChange) => {
130
322
  const release = resource.retain(variantKey);
131
323
  const unsubscribe = resource.store.subscribe(onStoreChange);
@@ -164,10 +356,7 @@ function useFrameworkQuery(url, ...args) {
164
356
  else if (entry.status === "rejected") serverError = entry.error;
165
357
  else readPromise = entry.promise;
166
358
  } else readPromise = resource.read(variantKey, config.staleTime).promise;
167
- if (suspense && typeof window === "undefined" && unserved && !state?.hasData && process.env.NODE_ENV !== "production") {
168
- const searchHint = variantKey ? `, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams(variantKey)))} }` : "";
169
- console.warn(`[gemi] useQuery("${url}") rendered on the server without data. The server never fetches, so this page ships without it and the client suspends after hydration. Add \`Query.prefetch("${url}"${searchHint})\` to the route's view handler.`);
170
- }
359
+ if (suspense && typeof window === "undefined" && unserved && !state?.hasData && process.env.NODE_ENV !== "production") warnUnprefetched(url, variantKey);
171
360
  useEffect(() => {
172
361
  if (!isDeferred) return;
173
362
  const targetSeed = configRef.current.fallbackData != null ? { [currentVariantKey]: configRef.current.fallbackData } : prefetchedData?.[currentPath];
@@ -183,76 +372,20 @@ function useFrameworkQuery(url, ...args) {
183
372
  if (fetchedRef.current) resource.getVariant(variantKey, configRef.current.staleTime);
184
373
  }, [variantKey, resource]);
185
374
  useEffect(() => {
186
- if (suspense || !snapshot?.error || snapshot.loading) return;
187
- const cfg = configRef.current;
188
- const error = snapshot.error;
189
- const failureCount = Math.max(1, resource.failureCount(variantKey));
190
- if (!shouldRetryQuery(failureCount, error, cfg.retry)) return;
191
- const delay = retryDelayFor(failureCount, error, cfg.retryDelay, cfg.retryIntervalOnError);
192
- if (cfg.debug) console.log("retrying", variantKey, "in", delay);
193
- resource.scheduleRetry(variantKey, delay);
375
+ if (suspense) return;
376
+ retryFailedQuery(resource, variantKey, snapshot, configRef.current);
194
377
  }, [
195
378
  snapshot,
196
379
  suspense,
197
380
  resource,
198
381
  variantKey
199
382
  ]);
383
+ useEffect(() => retryWhenOnline(resource, variantKey, () => configRef.current), [resource, variantKey]);
200
384
  useEffect(() => {
201
- if (typeof window === "undefined") return;
202
- const onOnline = () => {
203
- const state = resource.peek(variantKey);
204
- if (!state?.error) return;
205
- if (!shouldRetryQuery(1, state.error, configRef.current.retry)) return;
206
- resource.retryNow(variantKey);
207
- };
208
- window.addEventListener("online", onOnline);
209
- return () => window.removeEventListener("online", onOnline);
210
- }, [resource, variantKey]);
211
- useEffect(() => {
212
- const poll = pollRef.current;
213
- const clear = () => {
214
- if (poll.timer) clearTimeout(poll.timer);
215
- poll.timer = null;
216
- };
217
- if (poll.snapshot !== snapshot || poll.resource !== resource || poll.variantKey !== variantKey) {
218
- clear();
219
- poll.awaiting = false;
220
- poll.snapshot = snapshot;
221
- poll.resource = resource;
222
- poll.variantKey = variantKey;
223
- }
224
- const refetchUntil = configRef.current.refetchUntil;
225
- if (!refetchUntil || liveOpen || !snapshot || snapshot.loading || !snapshot.hasData || snapshot.error) {
226
- clear();
227
- return;
228
- }
229
- if (poll.awaiting) return;
230
- const nextDuration = refetchUntil(snapshot.data, poll.duration);
231
- if (!(nextDuration > 0)) {
232
- clear();
233
- poll.duration = 0;
234
- return;
235
- }
236
- if (poll.timer) return;
237
- poll.duration = nextDuration;
238
- poll.timer = setTimeout(() => {
239
- poll.timer = null;
240
- poll.awaiting = true;
241
- resource.refetch(variantKey);
242
- }, nextDuration);
385
+ stepPoll(pollRef.current, resource, variantKey, snapshot, configRef.current.refetchUntil, liveOpen);
243
386
  });
244
- useEffect(() => () => {
245
- const poll = pollRef.current;
246
- if (poll.timer) clearTimeout(poll.timer);
247
- poll.timer = null;
248
- poll.snapshot = void 0;
249
- poll.awaiting = false;
250
- }, []);
251
- const handleReload = useCallback(() => {
252
- if (configRef.current.debug) console.log("Reloading query for", variantKey);
253
- const data = resource.getVariant(variantKey, configRef.current.staleTime).data;
254
- resource.mutate(variantKey, () => data);
255
- }, [variantKey, resource]);
387
+ useEffect(() => () => stopPoll(pollRef.current), []);
388
+ const handleReload = useCallback(() => reloadQuery(resource, variantKey, configRef.current), [variantKey, resource]);
256
389
  useEffect(() => {
257
390
  if (!fetchedRef.current || liveOpen) return;
258
391
  refreshIntervalRef.current = setInterval(() => {
@@ -268,45 +401,16 @@ function useFrameworkQuery(url, ...args) {
268
401
  ]);
269
402
  useEffect(() => {
270
403
  if (!config.revalidateOnFocus) return;
271
- const markAway = () => {
272
- wasAwayRef.current = true;
273
- };
274
- const revalidate = () => {
275
- if (!focusEligibleRef.current) return;
276
- if (document.visibilityState === "hidden") return;
277
- if (!wasAwayRef.current) return;
278
- const now = Date.now();
279
- if (now - lastFocusRevalidationRef.current < configRef.current.focusThrottleInterval) return;
280
- wasAwayRef.current = false;
281
- lastFocusRevalidationRef.current = now;
282
- resource.revalidate(variantKey, configRef.current.staleTime);
283
- };
284
- const onVisibilityChange = () => {
285
- if (document.visibilityState === "hidden") markAway();
286
- else revalidate();
287
- };
288
- window.addEventListener("blur", markAway);
289
- window.addEventListener("focus", revalidate);
290
- document.addEventListener("visibilitychange", onVisibilityChange);
291
- return () => {
292
- window.removeEventListener("blur", markAway);
293
- window.removeEventListener("focus", revalidate);
294
- document.removeEventListener("visibilitychange", onVisibilityChange);
295
- };
404
+ return revalidateOnFocus(resource, variantKey, focusRef.current, () => configRef.current);
296
405
  }, [
297
406
  config.revalidateOnFocus,
298
407
  resource,
299
408
  variantKey
300
409
  ]);
301
- useEffect(() => {
302
- if (typeof import.meta.hot?.on === "function") import.meta.hot.on("http-reload", handleReload);
303
- return () => {
304
- if (typeof import.meta.hot?.off === "function") import.meta.hot.off("http-reload", handleReload);
305
- };
306
- }, [handleReload]);
410
+ useEffect(() => onHttpReload(handleReload), [handleReload]);
307
411
  const trigger = useCallback(() => {
308
412
  fetchedRef.current = true;
309
- focusEligibleRef.current = true;
413
+ focusRef.current.eligible = true;
310
414
  const variant = resource.store.getValue().get(variantKey);
311
415
  if (!variant || !variant.loading && !variant.hasData) resource.refetch(variantKey);
312
416
  }, [resource, variantKey]);
@@ -318,34 +422,12 @@ function useFrameworkQuery(url, ...args) {
318
422
  }, [resource, variantKey]);
319
423
  const refetch = useCallback(() => {
320
424
  fetchedRef.current = true;
321
- focusEligibleRef.current = true;
425
+ focusRef.current.eligible = true;
322
426
  resource.refetch(variantKey);
323
427
  }, [resource, variantKey]);
324
428
  function mutate(fn) {
325
- if (isEventLike(fn)) fn = void 0;
326
- focusEligibleRef.current = true;
327
- if (!fn) {
328
- fetchedRef.current = true;
329
- resource.refetch(variantKey);
330
- return;
331
- }
332
- return resource.mutate(variantKey, (data) => {
333
- if (data === void 0) {
334
- console.warn("Mutate function called before the query.");
335
- return data;
336
- }
337
- const updatedData = typeof fn === "function" ? fn(data) : fn;
338
- if (isPlainObject(data)) {
339
- if (isPlainObject(updatedData)) return updatedData;
340
- throw new Error("Mutate function must return an object when the current data is an object.");
341
- }
342
- if (Array.isArray(data)) {
343
- if (Array.isArray(updatedData)) return updatedData;
344
- throw new Error("Mutate function must return an array when the current data is an array.");
345
- }
346
- if (typeof data !== typeof updatedData) throw new Error("Mutate function must return the same type as the current data.");
347
- return updatedData;
348
- });
429
+ focusRef.current.eligible = true;
430
+ if (mutateQuery(resource, variantKey, fn) === "refetch") fetchedRef.current = true;
349
431
  }
350
432
  if (suspense) {
351
433
  if (serverError) throw serverError;
@@ -364,6 +446,303 @@ function useFrameworkQuery(url, ...args) {
364
446
  };
365
447
  }
366
448
  //#endregion
449
+ //#region client/useMultipleQuery.ts
450
+ /** A key whose first answer is still on the wire: nothing to show for it yet. */
451
+ function awaitingFirstAnswer(target) {
452
+ const state = target.resource.peek(target.variantKey);
453
+ return !!state && state.loading && !state.hasData;
454
+ }
455
+ function useMultipleQuery(queries, sharedConfig) {
456
+ const { user: _user, ...appConfig } = useContext(QueryConfigContext) ?? {};
457
+ const routeParams = useParams();
458
+ const { getResource } = useContext(QueryManagerContext);
459
+ const serverQueries = useContext(ServerQueryContext);
460
+ const realtime = useContext(RealtimeContext);
461
+ const { prefetchedData } = useRouteData();
462
+ const current = Object.keys(queries).map((key) => {
463
+ const [url, options, callConfig] = queries[key];
464
+ const config = {
465
+ ...defaultConfig,
466
+ ...mergeDefinedConfig(appConfig, sharedConfig, callConfig),
467
+ lazy: false
468
+ };
469
+ const target = resolveQueryTarget(url, {
470
+ ...defaultOptions$1,
471
+ ...options
472
+ }, routeParams);
473
+ return {
474
+ key,
475
+ url,
476
+ config,
477
+ suspense: config.suspense !== false,
478
+ ...target
479
+ };
480
+ });
481
+ const signature = JSON.stringify(current.filter((e) => e.suspense && e.config.keepPreviousData).map((e) => [
482
+ e.key,
483
+ e.url,
484
+ e.path,
485
+ e.variantKey,
486
+ e.params,
487
+ e.search
488
+ ]));
489
+ const deferredSignature = useDeferredValue(signature);
490
+ const deferred = useMemo(() => {
491
+ const map = /* @__PURE__ */ new Map();
492
+ if (deferredSignature === signature) return map;
493
+ for (const [key, url, path, variantKey, params, search] of JSON.parse(deferredSignature)) map.set(key, {
494
+ url,
495
+ path,
496
+ variantKey,
497
+ params,
498
+ search
499
+ });
500
+ return map;
501
+ }, [deferredSignature, signature]);
502
+ const entries = current.map((e) => {
503
+ const visible = (e.suspense && e.config.keepPreviousData ? deferred.get(e.key) : void 0) ?? e;
504
+ const isDeferred = visible.path !== e.path || visible.variantKey !== e.variantKey;
505
+ const seed = e.config.fallbackData != null ? { [visible.variantKey]: e.config.fallbackData } : prefetchedData?.[visible.path];
506
+ return {
507
+ ...e,
508
+ url: visible.url,
509
+ path: visible.path,
510
+ variantKey: visible.variantKey,
511
+ params: visible.params,
512
+ search: visible.search,
513
+ currentPath: e.path,
514
+ currentVariantKey: e.variantKey,
515
+ isDeferred,
516
+ resource: getResource(visible.path, seed ?? void 0)
517
+ };
518
+ });
519
+ const entriesRef = useRef(entries);
520
+ entriesRef.current = entries;
521
+ const targets = useMemo(() => entriesRef.current.map(({ key, path, variantKey, resource }) => ({
522
+ key,
523
+ path,
524
+ variantKey,
525
+ resource
526
+ })), [entries.map((e) => `${e.key}\u0000${e.path}\u0000${e.variantKey}`).join("\n"), getResource]);
527
+ const subscribe = useCallback((onStoreChange) => {
528
+ const releases = targets.map((t) => t.resource.retain(t.variantKey));
529
+ let notified = targets.map((t) => t.resource.peek(t.variantKey));
530
+ let active = true;
531
+ let scheduled = false;
532
+ const flush = () => {
533
+ scheduled = false;
534
+ if (!active) return;
535
+ const states = targets.map((t) => t.resource.peek(t.variantKey));
536
+ if (!states.some((state, i) => state !== notified[i] && notified[i]?.hasData) && targets.some(awaitingFirstAnswer)) return;
537
+ notified = states;
538
+ onStoreChange();
539
+ };
540
+ const onChange = () => {
541
+ if (scheduled) return;
542
+ scheduled = true;
543
+ queueMicrotask(flush);
544
+ };
545
+ const unsubscribes = [...new Set(targets.map((t) => t.resource))].map((resource) => resource.store.subscribe(onChange));
546
+ return () => {
547
+ active = false;
548
+ for (const unsubscribe of unsubscribes) unsubscribe();
549
+ for (const release of releases) release();
550
+ };
551
+ }, [targets]);
552
+ const cacheRef = useRef(null);
553
+ const getSnapshot = useCallback(() => {
554
+ const states = targets.map((t) => t.resource.peek(t.variantKey));
555
+ const cached = cacheRef.current;
556
+ if (cached && cached.targets === targets && states.every((state, i) => state === cached.states[i])) return cached.states;
557
+ cacheRef.current = {
558
+ targets,
559
+ states
560
+ };
561
+ return states;
562
+ }, [targets]);
563
+ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
564
+ const lastDataRef = useRef(/* @__PURE__ */ new Map());
565
+ useEffect(() => {
566
+ snapshot.forEach((state, i) => {
567
+ if (state?.hasData) lastDataRef.current.set(targets[i].key, state);
568
+ });
569
+ }, [snapshot, targets]);
570
+ const states = entries.map((e, i) => {
571
+ const state = snapshot[i];
572
+ const last = lastDataRef.current.get(e.key);
573
+ if (e.config.keepPreviousData && !state?.hasData && (state ? state.loading : true) && last) return {
574
+ ...last,
575
+ loading: true
576
+ };
577
+ return state;
578
+ });
579
+ const promises = [];
580
+ let thrown = null;
581
+ entries.forEach((e, i) => {
582
+ const state = states[i];
583
+ if (!e.suspense || state?.hasData || state?.error) return;
584
+ if (typeof window === "undefined") {
585
+ const entry = serverQueries?.ensure(e.url, {
586
+ params: e.params,
587
+ search: e.search
588
+ }) ?? null;
589
+ if (entry?.status === "resolved") {
590
+ states[i] = {
591
+ loading: false,
592
+ data: entry.data,
593
+ hasData: true,
594
+ error: null,
595
+ version: 0
596
+ };
597
+ return;
598
+ }
599
+ if (entry?.status === "rejected") thrown ??= { error: entry.error };
600
+ else if (entry) promises.push(entry.promise);
601
+ if (!entry && process.env.NODE_ENV !== "production") warnUnprefetched(e.url, e.variantKey, "useMultipleQuery");
602
+ return;
603
+ }
604
+ const { promise } = e.resource.read(e.variantKey, e.config.staleTime);
605
+ if (promise) promises.push(promise);
606
+ });
607
+ const [liveOpen, setLiveOpen] = useState({});
608
+ const liveKey = JSON.stringify(entries.filter((e) => e.config.live).map((e) => [e.key, e.config.live]));
609
+ useEffect(() => {
610
+ const stops = JSON.parse(liveKey).map(([key, live]) => {
611
+ const initial = entriesRef.current.find((e) => e.key === key).resource;
612
+ return followLive(realtime, live, () => entriesRef.current.find((e) => e.key === key)?.resource ?? initial, (open) => setLiveOpen((prev) => prev[key] === open ? prev : {
613
+ ...prev,
614
+ [key]: open
615
+ }));
616
+ });
617
+ return () => {
618
+ for (const stop of stops) stop();
619
+ };
620
+ }, [realtime, liveKey]);
621
+ const pendingKey = JSON.stringify(entries.filter((e) => e.isDeferred).map((e) => [
622
+ e.key,
623
+ e.currentPath,
624
+ e.currentVariantKey
625
+ ]));
626
+ useEffect(() => {
627
+ const releases = JSON.parse(pendingKey).map(([key, path, variantKey]) => {
628
+ const config = entriesRef.current.find((e) => e.key === key)?.config;
629
+ const seed = config?.fallbackData != null ? { [variantKey]: config.fallbackData } : prefetchedData?.[path];
630
+ return getResource(path, seed ?? void 0).retain(variantKey);
631
+ });
632
+ return () => {
633
+ for (const release of releases) release();
634
+ };
635
+ }, [
636
+ pendingKey,
637
+ getResource,
638
+ prefetchedData
639
+ ]);
640
+ useEffect(() => {
641
+ for (const t of targets) {
642
+ const config = entriesRef.current.find((e) => e.key === t.key)?.config;
643
+ t.resource.getVariant(t.variantKey, config?.staleTime);
644
+ }
645
+ }, [targets]);
646
+ const configOf = (key) => entriesRef.current.find((e) => e.key === key)?.config ?? defaultConfig;
647
+ const retriedRef = useRef(/* @__PURE__ */ new Map());
648
+ useEffect(() => {
649
+ targets.forEach((t, i) => {
650
+ const state = snapshot[i];
651
+ if (retriedRef.current.get(t.key) === state) return;
652
+ retriedRef.current.set(t.key, state);
653
+ const config = configOf(t.key);
654
+ if (config.suspense !== false) return;
655
+ retryFailedQuery(t.resource, t.variantKey, state, config);
656
+ });
657
+ });
658
+ useEffect(() => {
659
+ const cleanups = targets.map((t) => retryWhenOnline(t.resource, t.variantKey, () => configOf(t.key)));
660
+ return () => {
661
+ for (const cleanup of cleanups) cleanup();
662
+ };
663
+ }, [targets]);
664
+ const pollsRef = useRef(/* @__PURE__ */ new Map());
665
+ useEffect(() => {
666
+ const polls = pollsRef.current;
667
+ const keys = new Set(targets.map((t) => t.key));
668
+ for (const [key, poll] of polls) if (!keys.has(key)) {
669
+ stopPoll(poll);
670
+ polls.delete(key);
671
+ }
672
+ targets.forEach((t, i) => {
673
+ let poll = polls.get(t.key);
674
+ if (!poll) {
675
+ poll = createPollState();
676
+ polls.set(t.key, poll);
677
+ }
678
+ stepPoll(poll, t.resource, t.variantKey, snapshot[i], configOf(t.key).refetchUntil, !!liveOpen[t.key]);
679
+ });
680
+ });
681
+ useEffect(() => () => {
682
+ for (const poll of pollsRef.current.values()) stopPoll(poll);
683
+ }, []);
684
+ const intervalsKey = JSON.stringify(entries.map((e) => liveOpen[e.key] ? null : e.config.refreshInterval));
685
+ useEffect(() => {
686
+ const intervals = JSON.parse(intervalsKey);
687
+ const timers = targets.map((t, i) => intervals[i] == null ? null : setInterval(() => reloadQuery(t.resource, t.variantKey, configOf(t.key)), intervals[i]));
688
+ return () => {
689
+ for (const timer of timers) if (timer) clearInterval(timer);
690
+ };
691
+ }, [targets, intervalsKey]);
692
+ const focusRef = useRef(/* @__PURE__ */ new Map());
693
+ const focusKey = entries.map((e) => e.config.revalidateOnFocus ? 1 : 0).join();
694
+ useEffect(() => {
695
+ const flags = focusKey.split(",");
696
+ const cleanups = targets.map((t, i) => {
697
+ if (flags[i] !== "1") return null;
698
+ let focus = focusRef.current.get(t.key);
699
+ if (!focus) {
700
+ focus = {
701
+ eligible: true,
702
+ wasAway: false,
703
+ last: 0
704
+ };
705
+ focusRef.current.set(t.key, focus);
706
+ }
707
+ return revalidateOnFocus(t.resource, t.variantKey, focus, () => configOf(t.key));
708
+ });
709
+ return () => {
710
+ for (const cleanup of cleanups) cleanup?.();
711
+ };
712
+ }, [targets, focusKey]);
713
+ useEffect(() => onHttpReload(() => {
714
+ for (const t of targets) reloadQuery(t.resource, t.variantKey, configOf(t.key));
715
+ }), [targets]);
716
+ if (thrown) throw thrown.error;
717
+ entries.forEach((e, i) => {
718
+ const state = states[i];
719
+ if (e.suspense && state?.error && !state?.hasData) throw state.error;
720
+ });
721
+ if (promises.length > 0) throw promises.length === 1 ? promises[0] : Promise.all(promises);
722
+ const data = {};
723
+ const error = {};
724
+ const mutate = {};
725
+ const refetch = {};
726
+ let loading = false;
727
+ entries.forEach((e, i) => {
728
+ const state = states[i];
729
+ data[e.key] = state?.data;
730
+ error[e.key] = state?.error ?? null;
731
+ if (e.isDeferred || (state?.loading ?? true)) loading = true;
732
+ mutate[e.key] = (fn) => {
733
+ mutateQuery(e.resource, e.variantKey, fn);
734
+ };
735
+ refetch[e.key] = () => e.resource.refetch(e.variantKey);
736
+ });
737
+ return {
738
+ data,
739
+ loading,
740
+ error,
741
+ mutate,
742
+ refetch
743
+ };
744
+ }
745
+ //#endregion
367
746
  //#region client/useInfiniteQuery.ts
368
747
  /**
369
748
  * Follows the cursor chain through the cache: the first page, then
@@ -3281,6 +3660,6 @@ function onStaticNavigate(callback) {
3281
3660
  return () => document.removeEventListener("gemi:page-load", listener);
3282
3661
  }
3283
3662
  //#endregion
3284
- export { CHUNK_RELOAD_MARKER, Form, FormError, FormFieldContainer, Head, Image, Link, OpenGraphImage, QueryError, QueryManagerProvider, Redirect, ValidationErrors, configureRealtime, create, createRoot, defineDictionary, fetchBlob, fetchText, init, isAuthenticationError, isChunkLoadError, isCsrfError, isFormError, isHttpError, isNetworkError, isNotFoundError, isPermissionError, isRateLimitError, isRetryableQueryError, isServerError, isValidationError, island, mutationErrorField, mutationErrorKind, mutationErrorList, onStaticNavigate, recoverFromChunkLoadError, textDirection, useAppIdMissmatch, useBreadcrumbs, useChannel, useChannelInvalidate, useCspNonce, useDelete, useDictionary, useDomain, useEmailCode, useFeature, useFeatures, useForgotPassword, useFormData, useFormStatus, useFormatter, useInfiniteQuery, useIntendedUrl, useIsNavigationPending, useLocale, useLocation, useMutate, useMutation, useMutationStatus, useNavigate, useNavigationProgress, useParams, usePatch, usePost, usePrefetch, usePut, useQuery, useResetPassword, useRoute, useRouteTransition, useSearchParams, useSetQueryData, useSignIn, useSignOut, useSignUp, useSubscription, useTheme, useTranslator, useUpload, useUser };
3663
+ export { CHUNK_RELOAD_MARKER, Form, FormError, FormFieldContainer, Head, Image, Link, OpenGraphImage, QueryError, QueryManagerProvider, Redirect, ValidationErrors, configureRealtime, create, createRoot, defineDictionary, fetchBlob, fetchText, init, isAuthenticationError, isChunkLoadError, isCsrfError, isFormError, isHttpError, isNetworkError, isNotFoundError, isPermissionError, isRateLimitError, isRetryableQueryError, isServerError, isValidationError, island, mutationErrorField, mutationErrorKind, mutationErrorList, onStaticNavigate, recoverFromChunkLoadError, textDirection, useAppIdMissmatch, useBreadcrumbs, useChannel, useChannelInvalidate, useCspNonce, useDelete, useDictionary, useDomain, useEmailCode, useFeature, useFeatures, useForgotPassword, useFormData, useFormStatus, useFormatter, useInfiniteQuery, useIntendedUrl, useIsNavigationPending, useLocale, useLocation, useMultipleQuery, useMutate, useMutation, useMutationStatus, useNavigate, useNavigationProgress, useParams, usePatch, usePost, usePrefetch, usePut, useQuery, useResetPassword, useRoute, useRouteTransition, useSearchParams, useSetQueryData, useSignIn, useSignOut, useSignUp, useSubscription, useTheme, useTranslator, useUpload, useUser };
3285
3664
 
3286
3665
  //# sourceMappingURL=index.js.map