@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.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 (188) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +3 -0
  4. package/dist/build/entry-template.ts +7 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +1671 -276
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/types.d.ts +6 -0
  9. package/dist/cli/index.js +1672 -286
  10. package/dist/client/client-module.d.ts +26 -0
  11. package/dist/client/define-route.d.ts +9 -0
  12. package/dist/client/document.d.ts +2 -0
  13. package/dist/client/internal/runtime-types.d.ts +2 -0
  14. package/dist/client/link.js +932 -118
  15. package/dist/client/mutation.d.ts +38 -0
  16. package/dist/client/query-store.d.ts +85 -0
  17. package/dist/client/query.d.ts +14 -0
  18. package/dist/client/route-api.d.ts +11 -0
  19. package/dist/client/router/context.d.ts +3 -2
  20. package/dist/client/router/index.d.ts +1 -1
  21. package/dist/client/router/link-utils.d.ts +8 -1
  22. package/dist/client/router/navigation.d.ts +2 -9
  23. package/dist/client/router/optimistic.d.ts +41 -0
  24. package/dist/client/router/search/index.d.ts +3 -3
  25. package/dist/client/router/search-store.d.ts +1 -0
  26. package/dist/client/router/sync-catch-up.d.ts +3 -0
  27. package/dist/client/router/types.d.ts +49 -7
  28. package/dist/client/sync.d.ts +39 -22
  29. package/dist/client.d.ts +11 -33
  30. package/dist/client.js +1219 -59
  31. package/dist/config.d.ts +7 -0
  32. package/dist/config.js +1 -0
  33. package/dist/define-route.d.ts +78 -32
  34. package/dist/env.d.ts +2 -2
  35. package/dist/furin.d.ts +1 -2
  36. package/dist/furin.js +2448 -710
  37. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  38. package/dist/plugin/index.js +349 -18
  39. package/dist/plugin/transform-client-module.d.ts +16 -0
  40. package/dist/plugin/transform-client.d.ts +2 -0
  41. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  42. package/dist/routes.d.ts +6 -0
  43. package/dist/rsc-client.js +87 -16
  44. package/dist/rsc.js +87 -16
  45. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  46. package/dist/server/auto-invalidate/types.d.ts +2 -0
  47. package/dist/server/cache/isr.d.ts +2 -4
  48. package/dist/server/cache/route-cache.d.ts +5 -0
  49. package/dist/server/dev/graph.d.ts +1 -0
  50. package/dist/server/dev-page-plugin.d.ts +5 -19
  51. package/dist/server/internal.d.ts +3 -0
  52. package/dist/server/internal.js +55 -35
  53. package/dist/server/production-server.js +54 -34
  54. package/dist/server/render/loaders.d.ts +4 -2
  55. package/dist/server/render/react-stream.d.ts +3 -0
  56. package/dist/server/render/ssr.d.ts +2 -1
  57. package/dist/server/render/template.d.ts +4 -0
  58. package/dist/server/router/defined-route.d.ts +2 -0
  59. package/dist/server/router/hmr.d.ts +1 -1
  60. package/dist/server/sync/adapter.d.ts +25 -4
  61. package/dist/server/sync/atomic.d.ts +25 -0
  62. package/dist/server/sync/drizzle/index.d.ts +45 -0
  63. package/dist/server/sync/drizzle/index.js +540 -0
  64. package/dist/server/sync/execution-error.d.ts +2 -0
  65. package/dist/server/sync/index.d.ts +2 -1
  66. package/dist/server/sync/index.js +533 -105
  67. package/dist/server/sync/mutation-handler.d.ts +4 -0
  68. package/dist/server/sync/plugin.d.ts +34 -11
  69. package/dist/server/sync/postgres/execute.d.ts +3 -0
  70. package/dist/server/sync/postgres/index.d.ts +12 -1
  71. package/dist/server/sync/postgres/index.js +34 -13
  72. package/dist/server/sync/postgres/sql.d.ts +8 -0
  73. package/dist/server/sync/prisma/index.d.ts +24 -0
  74. package/dist/server/sync/prisma/index.js +340 -0
  75. package/dist/server/sync/queries.d.ts +21 -0
  76. package/dist/server/sync/query-context.d.ts +5 -0
  77. package/dist/server/sync/redis/index.js +3 -3
  78. package/dist/server/sync/redis/scripts.d.ts +1 -1
  79. package/dist/server/sync/response.d.ts +1 -0
  80. package/dist/server/sync/sqlite/index.d.ts +3 -0
  81. package/dist/server/sync/sqlite/index.js +10 -4
  82. package/dist/server/sync/stream.d.ts +2 -5
  83. package/dist/server/sync/validation.d.ts +4 -0
  84. package/dist/shared/defer.d.ts +31 -0
  85. package/dist/shared/error.d.ts +2 -2
  86. package/dist/shared/page-key.d.ts +7 -0
  87. package/dist/shared/query-bindings.d.ts +12 -0
  88. package/dist/shared/route-frame.d.ts +1 -0
  89. package/dist/shared/sync-query.d.ts +40 -0
  90. package/package.json +29 -6
  91. package/src/adapter/package.ts +12 -2
  92. package/src/adapter/runtime-build.ts +63 -12
  93. package/src/adapter/static.ts +7 -2
  94. package/src/adapter/vercel.ts +15 -13
  95. package/src/build/client.ts +23 -5
  96. package/src/build/entry-template.ts +7 -0
  97. package/src/build/hydrate.ts +17 -3
  98. package/src/build/preload-manifest.ts +100 -0
  99. package/src/build/production-instrumentation.ts +6 -3
  100. package/src/build/types.ts +4 -0
  101. package/src/cli/index.ts +1 -0
  102. package/src/client/browser-events-runtime.ts +4 -0
  103. package/src/client/client-module.ts +57 -0
  104. package/src/client/define-route.ts +11 -1
  105. package/src/client/document.tsx +28 -18
  106. package/src/client/hmr.ts +2 -1
  107. package/src/client/internal/runtime-types.ts +2 -0
  108. package/src/client/link.tsx +8 -8
  109. package/src/client/mutation.ts +136 -0
  110. package/src/client/query-store.ts +418 -0
  111. package/src/client/query.tsx +67 -0
  112. package/src/client/route-api.tsx +75 -0
  113. package/src/client/router/boundary-tree.tsx +7 -2
  114. package/src/client/router/context.ts +57 -4
  115. package/src/client/router/index.ts +3 -0
  116. package/src/client/router/link-utils.ts +29 -1
  117. package/src/client/router/navigation.ts +3 -50
  118. package/src/client/router/optimistic.ts +233 -0
  119. package/src/client/router/provider.tsx +304 -44
  120. package/src/client/router/search/index.ts +37 -17
  121. package/src/client/router/search-store.ts +4 -0
  122. package/src/client/router/sync-catch-up.ts +7 -0
  123. package/src/client/router/types.ts +71 -9
  124. package/src/client/sync.ts +438 -65
  125. package/src/client.ts +20 -60
  126. package/src/config.ts +5 -0
  127. package/src/define-route.ts +113 -55
  128. package/src/env.d.ts +2 -2
  129. package/src/furin.ts +75 -13
  130. package/src/plugin/hmr-dependencies.ts +58 -0
  131. package/src/plugin/index.ts +38 -2
  132. package/src/plugin/routes.ts +3 -3
  133. package/src/plugin/transform-client-module.ts +123 -0
  134. package/src/plugin/transform-client.ts +293 -13
  135. package/src/plugin/transform-isomorphic.ts +11 -5
  136. package/src/routes.ts +8 -0
  137. package/src/rsc/shared.tsx +104 -18
  138. package/src/server/auto-invalidate/registry.ts +4 -0
  139. package/src/server/auto-invalidate/runtime.ts +17 -0
  140. package/src/server/auto-invalidate/types.ts +6 -0
  141. package/src/server/cache/isr.ts +6 -34
  142. package/src/server/cache/route-cache.ts +40 -4
  143. package/src/server/dev/graph.ts +16 -2
  144. package/src/server/dev-page-plugin.ts +93 -59
  145. package/src/server/internal.ts +3 -0
  146. package/src/server/render/document.tsx +10 -1
  147. package/src/server/render/element.tsx +7 -2
  148. package/src/server/render/isr.ts +61 -29
  149. package/src/server/render/loaders.ts +118 -47
  150. package/src/server/render/mixed-cache.ts +33 -4
  151. package/src/server/render/not-found.ts +4 -7
  152. package/src/server/render/ppr-document.ts +2 -1
  153. package/src/server/render/ppr-route.ts +30 -10
  154. package/src/server/render/react-stream.ts +17 -0
  155. package/src/server/render/route-frame-transport.ts +3 -0
  156. package/src/server/render/ssg.ts +51 -18
  157. package/src/server/render/ssr.ts +53 -8
  158. package/src/server/render/template.ts +23 -0
  159. package/src/server/router/defined-route.ts +3 -0
  160. package/src/server/router/hmr.ts +3 -2
  161. package/src/server/router/plugin.ts +27 -12
  162. package/src/server/sync/adapter.ts +41 -4
  163. package/src/server/sync/atomic.ts +303 -0
  164. package/src/server/sync/drizzle/index.ts +145 -0
  165. package/src/server/sync/execution-error.ts +1 -0
  166. package/src/server/sync/fingerprint.ts +2 -6
  167. package/src/server/sync/index.ts +6 -0
  168. package/src/server/sync/mutation-handler.ts +69 -0
  169. package/src/server/sync/plugin.ts +177 -60
  170. package/src/server/sync/postgres/execute.ts +20 -0
  171. package/src/server/sync/postgres/index.ts +52 -16
  172. package/src/server/sync/postgres/sql.ts +20 -0
  173. package/src/server/sync/prisma/index.ts +70 -0
  174. package/src/server/sync/queries.ts +75 -0
  175. package/src/server/sync/query-context.ts +85 -0
  176. package/src/server/sync/redis/index.ts +7 -3
  177. package/src/server/sync/redis/scripts.ts +1 -1
  178. package/src/server/sync/response.ts +21 -0
  179. package/src/server/sync/sqlite/index.ts +19 -8
  180. package/src/server/sync/stream.ts +14 -22
  181. package/src/server/sync/validation.ts +34 -0
  182. package/src/shared/defer.ts +48 -0
  183. package/src/shared/error.ts +2 -2
  184. package/src/shared/page-key.ts +36 -0
  185. package/src/shared/query-bindings.ts +138 -0
  186. package/src/shared/route-frame.ts +13 -1
  187. package/src/shared/route-map.ts +12 -2
  188. package/src/shared/sync-query.ts +138 -0
@@ -1,11 +1,24 @@
1
1
  import { log } from "evlog";
2
2
  import type React from "react";
3
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import {
4
+ createElement,
5
+ useCallback,
6
+ useEffect,
7
+ useLayoutEffect,
8
+ useMemo,
9
+ useRef,
10
+ useState,
11
+ useSyncExternalStore,
12
+ } from "react";
4
13
  import type { HeadOptions } from "../../client.ts";
5
14
  import { parseDeferredNdjson } from "../../shared/deferred-ndjson.ts";
15
+ import { type DeferredQueryValue, projectDeferredQueryData } from "../../shared/query-bindings.ts";
6
16
  import type { SearchParamsInput } from "../../shared/search-params.ts";
17
+ import { type QuerySeed, queryTag } from "../../shared/sync-query.ts";
7
18
  import { subscribeBrowserEvent } from "../browser-events.ts";
8
19
  import { DocumentProvider, useDocumentState } from "../document.tsx";
20
+ import { QueryStoreContext } from "../query.tsx";
21
+ import { QueryStore } from "../query-store.ts";
9
22
  import { isAbortError } from "./abort.ts";
10
23
  import { buildPageElement, buildRouterTree } from "./boundary-tree.tsx";
11
24
  import {
@@ -27,6 +40,7 @@ import {
27
40
  stripHashFromHref,
28
41
  toLogical,
29
42
  } from "./link-utils.ts";
43
+ import { createOptimisticRuntime, registerOptimisticRuntime, SYNC_REQUEST } from "./optimistic.ts";
30
44
  import { createSearchStore, SearchStoreContext } from "./search-store.ts";
31
45
  import {
32
46
  buildDataEndpoint,
@@ -123,10 +137,24 @@ export function RouterProvider({
123
137
  syncPath,
124
138
  }: RouterProviderProps): React.ReactElement {
125
139
  const initialDocumentState = useDocumentState();
140
+ const [queries] = useState(() => {
141
+ const store = new QueryStore(
142
+ typeof window === "undefined" ? undefined : window.location.origin
143
+ );
144
+ store.hydrate(
145
+ (initialData.__furinQueries as QuerySeed[] | undefined) ?? [],
146
+ typeof window === "undefined" ? undefined : window.location.origin
147
+ );
148
+ return store;
149
+ });
126
150
  // Initial state. When `initialMatch` is `null`, `initialNotFound` MUST be set —
127
151
  // the provider boots into the inline not-found UI.
128
152
  const [state, setState] = useState<RouterState>(() => ({
129
- data: initialData,
153
+ data: Object.fromEntries(
154
+ Object.entries(initialData).filter(([key]) => key !== "__furinQueries")
155
+ ),
156
+ querySeeds: initialData.__furinQueries as QuerySeed[] | undefined,
157
+ hydrateQueries: queries.captureHydration(),
130
158
  error: initialError
131
159
  ? {
132
160
  ...initialError,
@@ -138,6 +166,46 @@ export function RouterProvider({
138
166
  notFound: initialNotFound,
139
167
  }));
140
168
  const [boundaryResetVersion, setBoundaryResetVersion] = useState(0);
169
+ const currentState = useRef(state);
170
+ useLayoutEffect(() => {
171
+ currentState.current = state;
172
+ }, [state]);
173
+ useLayoutEffect(() => {
174
+ state.hydrateQueries?.(
175
+ state.querySeeds ?? [],
176
+ typeof window === "undefined" ? undefined : window.location.origin
177
+ );
178
+ }, [state.hydrateQueries, state.querySeeds]);
179
+ const resolvedQueries = useRef(new WeakMap<Promise<unknown>, DeferredQueryValue>());
180
+ const [deferredRevision, setDeferredRevision] = useState(0);
181
+ useEffect(() => {
182
+ const snapshot = currentState.current;
183
+ const hydrated = new Set(snapshot.querySeeds?.map((seed) => seed.url));
184
+ let disposed = false;
185
+ for (const promise of Object.values(state.data)) {
186
+ if (!(promise instanceof Promise)) {
187
+ continue;
188
+ }
189
+ promise.then(
190
+ (value: unknown) => {
191
+ if (disposed) {
192
+ return;
193
+ }
194
+ resolvedQueries.current.set(promise, { value });
195
+ const seeds = (snapshot.querySeeds ?? []).filter((seed) => !hydrated.has(seed.url));
196
+ snapshot.hydrateQueries?.(seeds, window.location.origin);
197
+ for (const seed of seeds) {
198
+ hydrated.add(seed.url);
199
+ }
200
+ setDeferredRevision((revision) => revision + 1);
201
+ },
202
+ () => undefined
203
+ );
204
+ }
205
+ return () => {
206
+ disposed = true;
207
+ };
208
+ }, [queries, state.data]);
141
209
  const [isNavigating, setIsNavigating] = useState(false);
142
210
  // currentHref stores the LOGICAL path (basePath stripped) so Link active-state
143
211
  // detection works with route patterns that never include the basePath prefix.
@@ -147,6 +215,33 @@ export function RouterProvider({
147
215
  }
148
216
  return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
149
217
  });
218
+ const optimisticSnapshot = useRef({
219
+ href: currentHref,
220
+ loaded: state.match !== null,
221
+ pattern: state.match?.pattern,
222
+ });
223
+ useLayoutEffect(() => {
224
+ optimisticSnapshot.current = {
225
+ href: currentHref,
226
+ loaded: state.match !== null && !(state.error || state.notFound),
227
+ pattern: state.match?.pattern,
228
+ };
229
+ }, [currentHref, state.match, state.error, state.notFound]);
230
+ const syncResponse = useRef<
231
+ ((response: Response | undefined, optimistic: boolean) => void) | undefined
232
+ >(undefined);
233
+ const [optimisticRuntime] = useState(() =>
234
+ createOptimisticRuntime({
235
+ basePath,
236
+ queries,
237
+ snapshot: () => optimisticSnapshot.current,
238
+ onResponse: (response, optimistic) => syncResponse.current?.(response, optimistic),
239
+ })
240
+ );
241
+ useSyncExternalStore(optimisticRuntime.subscribe, optimisticRuntime.revision, () => 0);
242
+ const queryRevision = useSyncExternalStore(queries.subscribeAll, queries.revision, () => 0);
243
+ useEffect(() => registerOptimisticRuntime(optimisticRuntime), [optimisticRuntime]);
244
+ const snapshotVersions = useRef(new WeakMap<RouterState, number>());
150
245
  const prefetchCache = useRef(new Map<string, CacheEntry>());
151
246
  /** Monotonic counter to discard stale navigations (race condition guard). */
152
247
  const navVersion = useRef(0);
@@ -169,6 +264,7 @@ export function RouterProvider({
169
264
  const pendingScrollRef = useRef<
170
265
  { type: "restore"; key: string } | { type: "reset"; href: string } | null
171
266
  >(null);
267
+ const renderedHistoryKey = useRef<string | undefined>(undefined);
172
268
  /**
173
269
  * Tracks the last successfully rendered match for use in the no-route 404 path.
174
270
  * `null` on the initial render when the URL didn't match any route and the
@@ -236,6 +332,7 @@ export function RouterProvider({
236
332
  hmrRefresh: boolean
237
333
  // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SPA navigation orchestrator — response shapes (redirect, stale-deploy, deferred) + abort-signal wiring require this depth
238
334
  ): Promise<RouterState | null> => {
335
+ const hydrateQueries = queries.captureHydration();
239
336
  // Normalize trailing slashes so "/docs/routing/" matches the route
240
337
  // pattern "/docs/routing" — static hosts (GitHub Pages, Netlify) often
241
338
  // redirect to or serve URLs with a trailing slash.
@@ -311,6 +408,7 @@ export function RouterProvider({
311
408
  __furinRedirect,
312
409
  __furinError,
313
410
  __furinTitle,
411
+ __furinQueries,
314
412
  ...cleanSyncData
315
413
  } = syncData as {
316
414
  __furinStatus?: number;
@@ -319,6 +417,7 @@ export function RouterProvider({
319
417
  __furinError?: { digest: string; message: string; status: number };
320
418
  __furinHead?: HeadOptions;
321
419
  __furinTitle?: string;
420
+ __furinQueries?: QuerySeed[];
322
421
  [key: string]: unknown;
323
422
  };
324
423
 
@@ -395,7 +494,14 @@ export function RouterProvider({
395
494
  };
396
495
  }
397
496
 
398
- return { data, head: __furinHead, match: loadedMatch, title };
497
+ return {
498
+ data,
499
+ head: __furinHead,
500
+ match: loadedMatch,
501
+ querySeeds: __furinQueries,
502
+ hydrateQueries,
503
+ title,
504
+ };
399
505
  } catch (err: unknown) {
400
506
  if (!isAbortError(err)) {
401
507
  log.error({
@@ -407,29 +513,42 @@ export function RouterProvider({
407
513
  return null;
408
514
  }
409
515
  },
410
- [routes, basePath, resolveNoMatchState]
516
+ [routes, basePath, resolveNoMatchState, queries]
411
517
  );
412
518
 
413
- const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
414
- const normalizedPath = stripHashFromHref(path);
415
-
416
- if (type === "page") {
417
- for (const key of [...prefetchCache.current.keys()]) {
418
- if (stripHashFromHref(key) === normalizedPath) {
419
- prefetchCache.current.delete(key);
519
+ const fetchConfirmedPageState = useCallback(
520
+ async (href: string, signal: AbortSignal | undefined, hmrRefresh: boolean) => {
521
+ for (;;) {
522
+ try {
523
+ // biome-ignore lint/performance/noAwaitInLoops: a snapshot must be read after local writes settle.
524
+ await optimisticRuntime.wait(href, signal);
525
+ } catch (error) {
526
+ if (signal?.aborted) {
527
+ return null;
528
+ }
529
+ throw error;
530
+ }
531
+ const version = optimisticRuntime.revision(href);
532
+ const snapshot = await fetchPageState(href, signal, hmrRefresh);
533
+ if (optimisticRuntime.publishable(href, version)) {
534
+ if (snapshot) {
535
+ snapshotVersions.current.set(snapshot, version);
536
+ }
537
+ return snapshot;
420
538
  }
421
539
  }
422
- return;
423
- }
540
+ },
541
+ [fetchPageState, optimisticRuntime]
542
+ );
424
543
 
425
- // layout: prefix match — evict the path itself and all nested children
426
- const prefix =
427
- normalizedPath === "/" || normalizedPath.endsWith("/")
428
- ? normalizedPath
429
- : `${normalizedPath}/`;
544
+ const invalidatePrefetch = useCallback((path: string, type: "page" | "layout") => {
545
+ const normalizedPath = normalizeHref(new URL(path, "http://furin.local").pathname);
430
546
  for (const key of [...prefetchCache.current.keys()]) {
431
- const normalizedKey = stripHashFromHref(key);
432
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
547
+ if (
548
+ shouldAutoRefreshPath(normalizeHref(stripHashFromHref(key)), [
549
+ { path: normalizedPath, type },
550
+ ])
551
+ ) {
433
552
  prefetchCache.current.delete(key);
434
553
  }
435
554
  }
@@ -463,16 +582,26 @@ export function RouterProvider({
463
582
  signal: AbortSignal | undefined
464
583
  ): Promise<RouterState | null> {
465
584
  const cached = prefetchCache.current.get(redirectLogical);
466
- const useCached = cached !== undefined && !shouldRefetch(cached);
585
+ const useCached =
586
+ cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(redirectLogical);
467
587
  let redirectState =
468
588
  useCached && cached
469
589
  ? await cached.promise
470
- : await fetchPageState(redirectLogical, signal, false);
590
+ : await fetchConfirmedPageState(redirectLogical, signal, false);
471
591
  if (navVersion.current !== myVersion) {
472
592
  return null;
473
593
  }
474
- if (useCached && isRedirectState(redirectState)) {
475
- redirectState = await fetchPageState(redirectLogical, signal, false);
594
+ if (
595
+ useCached &&
596
+ (isRedirectState(redirectState) ||
597
+ (redirectState &&
598
+ !optimisticRuntime.publishable(
599
+ redirectLogical,
600
+ snapshotVersions.current.get(redirectState) ??
601
+ optimisticRuntime.revision(redirectLogical)
602
+ )))
603
+ ) {
604
+ redirectState = await fetchConfirmedPageState(redirectLogical, signal, false);
476
605
  }
477
606
  return navVersion.current === myVersion ? redirectState : null;
478
607
  }
@@ -517,6 +646,7 @@ export function RouterProvider({
517
646
  | undefined
518
647
  ) {
519
648
  const logicalHref = normalizeHref(rawLogicalHref);
649
+ const beforeCommit = opts?.beforeCommit;
520
650
  const finishUserNavigation =
521
651
  opts?.hmrRefresh === true ? undefined : beginUserNavigation(pendingUserNavigation);
522
652
  navVersion.current += 1;
@@ -528,14 +658,26 @@ export function RouterProvider({
528
658
  setIsNavigating(true);
529
659
  try {
530
660
  const cached = prefetchCache.current.get(logicalHref);
531
- const useCached = cached !== undefined && !shouldRefetch(cached);
661
+ const useCached =
662
+ cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref);
532
663
  let newState =
533
664
  useCached && cached
534
665
  ? await cached.promise
535
- : await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
536
- const cachedRedirect = useCached && isRedirectState(newState);
666
+ : await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
667
+ const cachedRedirect =
668
+ useCached &&
669
+ (isRedirectState(newState) ||
670
+ (newState &&
671
+ !optimisticRuntime.publishable(
672
+ logicalHref,
673
+ snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)
674
+ )));
537
675
  if (cachedRedirect) {
538
- newState = await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
676
+ newState = await fetchConfirmedPageState(
677
+ logicalHref,
678
+ navSignal,
679
+ opts?.hmrRefresh === true
680
+ );
539
681
  }
540
682
  if (navVersion.current !== myVersion || opts?.shouldCommit?.() === false) {
541
683
  return;
@@ -577,7 +719,19 @@ export function RouterProvider({
577
719
  if (opts?.shouldCommit?.() === false) {
578
720
  return;
579
721
  }
580
- opts?.beforeCommit?.();
722
+ const publicationHref = newState.finalHref ?? resolved.href;
723
+ if (
724
+ !optimisticRuntime.publishable(
725
+ publicationHref,
726
+ snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref)
727
+ )
728
+ ) {
729
+ return;
730
+ }
731
+ if (!(newState.error || newState.notFound)) {
732
+ optimisticRuntime.commit(publicationHref);
733
+ }
734
+ beforeCommit?.();
581
735
  const effectiveLogical = newState.finalHref ?? resolved.href;
582
736
  const physicalEffective = basePath + effectiveLogical;
583
737
  if (opts?.resetScroll ?? true) {
@@ -601,12 +755,13 @@ export function RouterProvider({
601
755
  physicalEffective
602
756
  );
603
757
  } else {
604
- const currentKey = getHistoryKey(history.state);
758
+ const currentKey = renderedHistoryKey.current;
605
759
  if (currentKey) {
606
760
  saveScrollPosition(currentKey);
607
761
  }
608
762
  window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
609
763
  }
764
+ renderedHistoryKey.current = getHistoryKey(history.state);
610
765
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
611
766
  const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
612
767
  setCurrentHref(logicalPath + effectiveUrl.search);
@@ -617,12 +772,19 @@ export function RouterProvider({
617
772
  }
618
773
  }
619
774
  },
620
- [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]
775
+ [
776
+ basePath,
777
+ fetchConfirmedPageState,
778
+ defaultPreloadStaleTime,
779
+ prefetchCacheSize,
780
+ optimisticRuntime,
781
+ ]
621
782
  );
622
783
 
623
784
  const [searchStore] = useState(() =>
624
785
  createSearchStore({
625
786
  currentHref,
787
+ currentPattern: state.match?.pattern,
626
788
  navigate,
627
789
  search: resolvedSearch,
628
790
  searchRoutes: routes,
@@ -631,11 +793,12 @@ export function RouterProvider({
631
793
  const searchSnapshot = useMemo(
632
794
  () => ({
633
795
  currentHref,
796
+ currentPattern: state.match?.pattern,
634
797
  navigate,
635
798
  search: resolvedSearch,
636
799
  searchRoutes: routes,
637
800
  }),
638
- [currentHref, navigate, resolvedSearch, routes]
801
+ [currentHref, state.match?.pattern, navigate, resolvedSearch, routes]
639
802
  );
640
803
 
641
804
  useLayoutEffect(() => {
@@ -673,11 +836,39 @@ export function RouterProvider({
673
836
  onError: (error) => {
674
837
  log.warn({ action: "sync_refresh_failed", error: String(error) });
675
838
  },
676
- refresh: () => refresh(undefined),
839
+ refresh: async () => {
840
+ await waitForUserNavigation(pendingUserNavigation);
841
+ await refresh(undefined);
842
+ },
677
843
  }),
678
844
  [refresh]
679
845
  );
680
846
 
847
+ useLayoutEffect(() => {
848
+ syncResponse.current = (response, optimistic) => {
849
+ const invalidated: Array<{ path: string; type: "page" | "layout" }> = [];
850
+ if (
851
+ response &&
852
+ (response.url === "" || new URL(response.url).origin === window.location.origin)
853
+ ) {
854
+ applyRevalidateHeader(response.headers, (path, type) => {
855
+ const resolvedType = type ?? "page";
856
+ invalidatePrefetch(path, resolvedType);
857
+ invalidated.push({ path, type: resolvedType });
858
+ });
859
+ }
860
+ if (
861
+ optimistic ||
862
+ (autoRefresh && shouldAutoRefreshPath(optimisticSnapshot.current.href, invalidated))
863
+ ) {
864
+ invalidationRefresh.run();
865
+ }
866
+ };
867
+ return () => {
868
+ syncResponse.current = undefined;
869
+ };
870
+ }, [autoRefresh, invalidatePrefetch, invalidationRefresh]);
871
+
681
872
  // Expose a transactional refresh to the HMR handler in _hydrate.tsx. The
682
873
  // callback swaps the hot component only after fresh data is ready and just
683
874
  // before setState publishes the complete router snapshot.
@@ -723,6 +914,9 @@ export function RouterProvider({
723
914
 
724
915
  const handlePopState = useCallback(() => {
725
916
  const finishUserNavigation = beginUserNavigation(pendingUserNavigation);
917
+ if (renderedHistoryKey.current) {
918
+ saveScrollPosition(renderedHistoryKey.current);
919
+ }
726
920
  const destKey = getHistoryKey(history.state);
727
921
  const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
728
922
  const logicalHref = logicalPath + window.location.search;
@@ -739,13 +933,20 @@ export function RouterProvider({
739
933
  try {
740
934
  const cached = prefetchCache.current.get(logicalHref);
741
935
  let newState: RouterState | null;
742
- if (cached && !shouldRefetch(cached)) {
936
+ if (cached && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref)) {
743
937
  newState = await cached.promise;
744
- if (isRedirectState(newState)) {
745
- newState = await fetchPageState(logicalHref, navSignal, false);
938
+ if (
939
+ isRedirectState(newState) ||
940
+ (newState &&
941
+ !optimisticRuntime.publishable(
942
+ logicalHref,
943
+ snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)
944
+ ))
945
+ ) {
946
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
746
947
  }
747
948
  } else {
748
- newState = await fetchPageState(logicalHref, navSignal, false);
949
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
749
950
  }
750
951
  if (navVersion.current !== myVersion) {
751
952
  return;
@@ -771,6 +972,18 @@ export function RouterProvider({
771
972
  return;
772
973
  }
773
974
  newState = resolved.state;
975
+ const publicationHref = newState.finalHref ?? resolved.href;
976
+ if (
977
+ !optimisticRuntime.publishable(
978
+ publicationHref,
979
+ snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref)
980
+ )
981
+ ) {
982
+ return;
983
+ }
984
+ if (!(newState.error || newState.notFound)) {
985
+ optimisticRuntime.commit(publicationHref);
986
+ }
774
987
 
775
988
  currentMatchRef.current = newState.match;
776
989
  if (!newState.error) {
@@ -784,6 +997,7 @@ export function RouterProvider({
784
997
  if (effectiveLogical !== logicalHref) {
785
998
  window.history.replaceState(history.state, "", basePath + effectiveLogical);
786
999
  }
1000
+ renderedHistoryKey.current = destKey;
787
1001
  setCurrentHref(normalizeHref(effectiveLogical));
788
1002
  if (destKey) {
789
1003
  pendingScrollRef.current = { key: destKey, type: "restore" };
@@ -797,7 +1011,7 @@ export function RouterProvider({
797
1011
  }
798
1012
  }
799
1013
  })();
800
- }, [fetchPageState, basePath]);
1014
+ }, [fetchConfirmedPageState, basePath, optimisticRuntime]);
801
1015
 
802
1016
  // Disable native scroll restoration and assign a key to the initial history entry.
803
1017
  useEffect(() => {
@@ -805,6 +1019,7 @@ export function RouterProvider({
805
1019
  if (!getHistoryKey(history.state)) {
806
1020
  history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
807
1021
  }
1022
+ renderedHistoryKey.current = getHistoryKey(history.state);
808
1023
  }, []);
809
1024
 
810
1025
  // Render-synchronous scroll restoration.
@@ -886,7 +1101,7 @@ export function RouterProvider({
886
1101
  return;
887
1102
  }
888
1103
  e.preventDefault();
889
- navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
1104
+ navigate(logicalHref, undefined);
890
1105
  };
891
1106
  document.addEventListener("click", handler);
892
1107
  return () => document.removeEventListener("click", handler);
@@ -900,6 +1115,9 @@ export function RouterProvider({
900
1115
  const originalFetch = window.fetch;
901
1116
  const wrapped = async (...args: Parameters<typeof fetch>): Promise<Response> => {
902
1117
  const response = await originalFetch.apply(window, args);
1118
+ if (args[1] && SYNC_REQUEST in args[1]) {
1119
+ return response;
1120
+ }
903
1121
  if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
904
1122
  return response;
905
1123
  }
@@ -972,6 +1190,25 @@ export function RouterProvider({
972
1190
  return (await response.json()) as SyncChangePagePayload;
973
1191
  },
974
1192
  onInvalidations: applyInvalidations,
1193
+ onReset: () => queries.invalidateAll(),
1194
+ onQueries: (identities) => {
1195
+ queries.invalidate(identities);
1196
+ const tags = new Set(identities.map(queryTag));
1197
+ const affected = (snapshot: RouterState) =>
1198
+ snapshot.querySeeds?.some((seed) => tags.has(queryTag(seed.identity)));
1199
+ for (const [href, entry] of prefetchCache.current) {
1200
+ entry.promise
1201
+ .then((snapshot) => {
1202
+ if (snapshot && affected(snapshot) && prefetchCache.current.get(href) === entry) {
1203
+ prefetchCache.current.delete(href);
1204
+ }
1205
+ })
1206
+ .catch(() => undefined);
1207
+ }
1208
+ if (autoRefresh && affected(currentState.current)) {
1209
+ invalidationRefresh.run();
1210
+ }
1211
+ },
975
1212
  });
976
1213
  const recover = () => {
977
1214
  if (disposed) {
@@ -1006,19 +1243,41 @@ export function RouterProvider({
1006
1243
  disposed = true;
1007
1244
  unsubscribe?.();
1008
1245
  };
1009
- }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh]);
1246
+ }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh, queries]);
1010
1247
 
1248
+ const queryData = useMemo(
1249
+ () =>
1250
+ projectDeferredQueryData(
1251
+ state.data,
1252
+ state.querySeeds ?? [],
1253
+ (seed) => {
1254
+ if (seed.local && typeof window !== "undefined") {
1255
+ const original = new URL(seed.url);
1256
+ return queries.snapshot(
1257
+ new URL(original.pathname + original.search, window.location.origin).href
1258
+ ).data;
1259
+ }
1260
+ return queries.snapshot(seed.url).data;
1261
+ },
1262
+ resolvedQueries.current
1263
+ ),
1264
+ [queries, state.data, state.querySeeds, queryRevision, deferredRevision]
1265
+ );
1266
+ const renderedData = optimisticRuntime.project(queryData, currentHref);
1011
1267
  let pageElement: React.ReactNode;
1012
1268
  if (state.notFound || !state.match) {
1013
- pageElement = buildNotFoundPageElement(
1269
+ const notFoundElement = buildNotFoundPageElement(
1014
1270
  state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries,
1015
1271
  state.notFound ?? {}
1016
1272
  );
1273
+ pageElement = root?.layout
1274
+ ? createElement(root.layout as React.ElementType, renderedData, notFoundElement)
1275
+ : notFoundElement;
1017
1276
  } else {
1018
1277
  pageElement = buildPageElement(
1019
1278
  state.match,
1020
1279
  root,
1021
- state.data,
1280
+ renderedData,
1022
1281
  {
1023
1282
  onReset: () => {
1024
1283
  refresh(undefined).catch((err: unknown) => {
@@ -1037,6 +1296,7 @@ export function RouterProvider({
1037
1296
  {
1038
1297
  basePath,
1039
1298
  currentHref,
1299
+ currentPattern: state.match?.pattern,
1040
1300
  defaultPreload,
1041
1301
  defaultPreloadDelay,
1042
1302
  defaultPreloadStaleTime,
@@ -1063,7 +1323,7 @@ export function RouterProvider({
1063
1323
  </SearchStoreContext.Provider>
1064
1324
  );
1065
1325
  if (initialDocumentState === null) {
1066
- return routerTree;
1326
+ return <QueryStoreContext.Provider value={queries}>{routerTree}</QueryStoreContext.Provider>;
1067
1327
  }
1068
1328
  return (
1069
1329
  <DocumentProvider
@@ -1072,7 +1332,7 @@ export function RouterProvider({
1072
1332
  head: state.head,
1073
1333
  }}
1074
1334
  >
1075
- {routerTree}
1335
+ <QueryStoreContext.Provider value={queries}>{routerTree}</QueryStoreContext.Provider>
1076
1336
  </DocumentProvider>
1077
1337
  );
1078
1338
  }