@teyik0/furin 0.6.0-alpha.1 → 0.7.0-alpha.2

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 (197) 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/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
@@ -1,6 +1,6 @@
1
1
  // @bun
2
2
  // src/client/link.tsx
3
- import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef as useRef2 } from "react";
3
+ import { createElement as createElement7, useCallback as useCallback4, useEffect as useEffect3, useRef as useRef2 } from "react";
4
4
 
5
5
  // src/shared/search-params.ts
6
6
  function routeSegmentSpecificity(segment) {
@@ -127,7 +127,7 @@ function findSearchDefaultsForRouteTarget(to, routes) {
127
127
  }
128
128
 
129
129
  // src/client/router/context.ts
130
- import { createContext, useContext } from "react";
130
+ import { createContext, useCallback, useContext, useMemo } from "react";
131
131
 
132
132
  // src/client/router/link-utils.ts
133
133
  var HASH_FRAGMENT_RE = /#.*$/;
@@ -190,6 +190,10 @@ function applyLinkParams(to, params) {
190
190
  }
191
191
  return url;
192
192
  }
193
+ function resolveRouteTarget(target, routes) {
194
+ const path = applyLinkParams(target.to, target.params);
195
+ return buildHref(path, target.search, target.hash, findSearchDefaultsForRouteTarget(path, routes));
196
+ }
193
197
  function buildHref(to, search, hash, searchDefaults) {
194
198
  let url = to;
195
199
  if (search && Object.keys(search).length > 0) {
@@ -320,13 +324,66 @@ var CLIENT_FALLBACK_ROUTER = {
320
324
  search: {},
321
325
  searchRoutes: []
322
326
  };
323
- function useRouter() {
327
+ function useRouterContext() {
324
328
  const ctx = useContext(RouterContext);
325
329
  return ctx ?? CLIENT_FALLBACK_ROUTER;
326
330
  }
331
+ function useRouter() {
332
+ const context = useRouterContext();
333
+ const navigate = useCallback((next, opts) => {
334
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
335
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
336
+ if (policy === "blocked") {
337
+ return Promise.reject(new Error("[furin] Unsafe navigation URL."));
338
+ }
339
+ if (policy === "external" && typeof window !== "undefined") {
340
+ window.location.assign(href);
341
+ return Promise.resolve();
342
+ }
343
+ if (typeof next === "string") {
344
+ return context.navigate(href, opts);
345
+ }
346
+ const options = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
347
+ return context.navigate(href, options);
348
+ }, [context.navigate, context.searchRoutes]);
349
+ const prefetch = useCallback((next, opts) => {
350
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
351
+ const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
352
+ if (policy !== "internal") {
353
+ return;
354
+ }
355
+ context.prefetch(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
356
+ }, [context.prefetch, context.searchRoutes]);
357
+ return useMemo(() => ({ ...context, navigate, prefetch }), [context, navigate, prefetch]);
358
+ }
327
359
 
328
360
  // src/client/router/boundary-tree.tsx
329
- import { createElement as createElement2 } from "react";
361
+ import { createElement as createElement3 } from "react";
362
+
363
+ // src/shared/page-key.ts
364
+ function identityValue(value) {
365
+ return Object.is(value, -0) ? "-0" : String(value);
366
+ }
367
+ function pageKey(pattern, data, remountDeps) {
368
+ const { params, query } = data;
369
+ if (remountDeps) {
370
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
371
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
372
+ }
373
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
374
+ if (left < right) {
375
+ return -1;
376
+ }
377
+ return left > right ? 1 : 0;
378
+ });
379
+ return JSON.stringify([
380
+ pattern,
381
+ entries.map(([name, value]) => [
382
+ name,
383
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
384
+ ])
385
+ ]);
386
+ }
330
387
 
331
388
  // src/client/boundaries.tsx
332
389
  import { Component, Fragment as Fragment2 } from "react";
@@ -667,6 +724,7 @@ var DefaultNotFoundFallback = ({ error }) => /* @__PURE__ */ jsxDEV(DefaultNotFo
667
724
 
668
725
  // src/client/document.tsx
669
726
  import { createContext as createContext2, createElement, useContext as useContext2 } from "react";
727
+ import { preloadModule } from "react-dom";
670
728
  import { jsxDEV as jsxDEV2, Fragment } from "react/jsx-dev-runtime";
671
729
  var DocumentContext = createContext2(null);
672
730
  function serializeJson(value) {
@@ -684,29 +742,39 @@ function DocumentProvider({
684
742
  function useDocumentState() {
685
743
  return useContext2(DocumentContext);
686
744
  }
687
- function renderMeta(meta, index) {
745
+ function renderMeta(meta, key) {
688
746
  if ("title" in meta) {
689
747
  return /* @__PURE__ */ jsxDEV2("title", {
690
748
  children: meta.title
691
- }, `title:${index}`, false, undefined, this);
749
+ }, key, false, undefined, this);
692
750
  }
693
751
  if ("script:ld+json" in meta) {
694
752
  return /* @__PURE__ */ jsxDEV2("script", {
695
753
  dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
696
754
  type: "application/ld+json"
697
- }, `json-ld:${index}`, false, undefined, this);
755
+ }, key, false, undefined, this);
698
756
  }
699
757
  if ("tagName" in meta) {
700
758
  const { tagName, ...attributes } = meta;
701
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
759
+ return createElement(tagName, { ...attributes, key });
702
760
  }
703
- return createElement("meta", { ...meta, key: `meta:${index}` });
761
+ return createElement("meta", { ...meta, key });
704
762
  }
705
763
  function HeadContent() {
706
764
  const state = useContext2(DocumentContext);
707
765
  if (state === null) {
708
766
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
709
767
  }
768
+ for (const href of state.assets.modulePreloads ?? []) {
769
+ preloadModule(href, { as: "script", nonce: state.nonce });
770
+ }
771
+ const occurrences = new Map;
772
+ const descriptorKey = (descriptor) => {
773
+ const identity = JSON.stringify(descriptor);
774
+ const occurrence = occurrences.get(identity) ?? 0;
775
+ occurrences.set(identity, occurrence + 1);
776
+ return `${identity}:${occurrence}`;
777
+ };
710
778
  return /* @__PURE__ */ jsxDEV2(Fragment, {
711
779
  children: [
712
780
  state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV2("script", {
@@ -739,20 +807,20 @@ function HeadContent() {
739
807
  href,
740
808
  rel: "stylesheet"
741
809
  }, href, false, undefined, this)),
742
- state.head?.meta?.map(renderMeta),
743
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV2("link", {
810
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
811
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV2("link", {
744
812
  ...link
745
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
746
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV2("script", {
813
+ }, descriptorKey(link), false, undefined, this)),
814
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV2("script", {
747
815
  ...attributes,
748
- dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children },
749
- nonce: state.nonce ?? attributes.nonce
750
- }, `script:${index}`, false, undefined, this)),
751
- state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV2("style", {
816
+ nonce: state.nonce ?? attributes.nonce,
817
+ children
818
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
819
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV2("style", {
752
820
  dangerouslySetInnerHTML: { __html: children },
753
821
  nonce: state.nonce,
754
822
  type
755
- }, `style:${index}`, false, undefined, this))
823
+ }, descriptorKey({ children, type }), false, undefined, this))
756
824
  ]
757
825
  }, undefined, true, undefined, this);
758
826
  }
@@ -961,6 +1029,31 @@ function wrapSegmentBoundaries(inner, segment, options) {
961
1029
  return wrapped;
962
1030
  }
963
1031
 
1032
+ // src/client/route-api.tsx
1033
+ import { createContext as createContext3, createElement as createElement2, useContext as useContext3 } from "react";
1034
+ var RESERVED_RENDER_KEYS = new Set([
1035
+ "catch",
1036
+ "children",
1037
+ "finally",
1038
+ "key",
1039
+ "ref",
1040
+ "then",
1041
+ "toJSON"
1042
+ ]);
1043
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
1044
+ var contextGlobal = globalThis;
1045
+ var RouteContext = contextGlobal[ROUTE_CONTEXT] ??= createContext3(null);
1046
+ function withRouteSnapshot(element, pattern, props) {
1047
+ const {
1048
+ params,
1049
+ path: _path,
1050
+ query: _query,
1051
+ ...data
1052
+ } = props;
1053
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
1054
+ return createElement2(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
1055
+ }
1056
+
964
1057
  // src/client/router/boundary-tree.tsx
965
1058
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
966
1059
  function buildRouterTree(context, pageElement, options) {
@@ -978,7 +1071,10 @@ function RouteErrorThrower({
978
1071
  throw new FurinServerError(error);
979
1072
  }
980
1073
  function buildPageElement(match, root, data, options, error) {
981
- let element = error ? createElement2(RouteErrorThrower, { error }) : createElement2(match.component, data);
1074
+ let element = error ? createElement3(RouteErrorThrower, { error }) : createElement3(match.component, {
1075
+ ...data,
1076
+ key: pageKey(match.pattern, data, match.pageRoute.remountDeps)
1077
+ });
982
1078
  const chain = [];
983
1079
  let current = match.pageRoute;
984
1080
  while (current) {
@@ -987,23 +1083,29 @@ function buildPageElement(match, root, data, options, error) {
987
1083
  }
988
1084
  const byDepth = new Map;
989
1085
  for (const segment of match.segmentBoundaries ?? []) {
990
- byDepth.set(segment.depth, segment);
1086
+ const boundaries = byDepth.get(segment.depth) ?? [];
1087
+ boundaries.unshift(segment);
1088
+ byDepth.set(segment.depth, boundaries);
991
1089
  }
992
1090
  const rootOffset = root ? 1 : 0;
993
1091
  for (let i = chain.length - 1;i >= rootOffset; i -= 1) {
994
- element = wrapSegmentBoundaries(element, byDepth.get(i), options);
1092
+ for (const segment of byDepth.get(i) ?? []) {
1093
+ element = wrapSegmentBoundaries(element, segment, options);
1094
+ }
995
1095
  const Layout = chain[i]?.layout;
996
1096
  if (Layout) {
997
- element = createElement2(Layout, data, element);
1097
+ element = createElement3(Layout, data, element);
998
1098
  }
999
1099
  }
1000
1100
  if (root) {
1001
- element = wrapSegmentBoundaries(element, byDepth.get(0), options);
1101
+ for (const segment of byDepth.get(0) ?? []) {
1102
+ element = wrapSegmentBoundaries(element, segment, options);
1103
+ }
1002
1104
  if (root.layout) {
1003
- element = createElement2(root.layout, data, element);
1105
+ element = createElement3(root.layout, data, element);
1004
1106
  }
1005
1107
  }
1006
- return element;
1108
+ return error ? element : withRouteSnapshot(element, match.pattern, data);
1007
1109
  }
1008
1110
  // src/client/router/history.ts
1009
1111
  var SCROLL_STORAGE_KEY = "__furin_scroll__";
@@ -1035,25 +1137,10 @@ function isStaleDeployResponse(res) {
1035
1137
  return Boolean(clientBuildId && serverBuildId !== clientBuildId);
1036
1138
  }
1037
1139
  // src/client/router/navigation.ts
1038
- import { useCallback } from "react";
1039
1140
  function useNavigate() {
1040
- const router = useRouter();
1041
- return useCallback((next) => {
1042
- const searchDefaults = findSearchDefaultsForRouteTarget(next.to, router.searchRoutes);
1043
- const href = buildHref(next.to, next.search, next.hash, searchDefaults);
1044
- const policy = navigationHrefPolicy(href, typeof window === "undefined" ? undefined : window.location.origin);
1045
- if (policy === "blocked") {
1046
- return Promise.reject(new Error("[furin] Unsafe navigation URL."));
1047
- }
1048
- if (policy === "external" && typeof window !== "undefined") {
1049
- window.location.assign(href);
1050
- return Promise.resolve();
1051
- }
1052
- const opts = next.replace === undefined && next.resetScroll === undefined ? undefined : { replace: next.replace, resetScroll: next.resetScroll };
1053
- return router.navigate(href, opts);
1054
- }, [router]);
1141
+ return useRouter().navigate;
1055
1142
  }
1056
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
1143
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
1057
1144
  function formatDuration(ms) {
1058
1145
  if (ms < 1000)
1059
1146
  return `${Math.round(ms)}ms`;
@@ -1180,7 +1267,7 @@ function isoNow() {
1180
1267
  return `${_isoCachedPrefix}.${String(now % 1000).padStart(3, "0")}Z`;
1181
1268
  }
1182
1269
 
1183
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
1270
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
1184
1271
  var DEFAULT_REPLACEMENT = "[REDACTED]";
1185
1272
  function normalizeRedactPathPattern(pattern) {
1186
1273
  if (!pattern.includes("*") && !pattern.includes("."))
@@ -1483,7 +1570,7 @@ function applyMaskers(value, maskers) {
1483
1570
  return result;
1484
1571
  }
1485
1572
 
1486
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
1573
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
1487
1574
  function logPluginError(name, hook, err) {
1488
1575
  console.error(`[evlog/${name}] ${hook} failed:`, err);
1489
1576
  }
@@ -1641,7 +1728,7 @@ function getRegistry() {
1641
1728
  }
1642
1729
  var globalConfig = getRegistry().config;
1643
1730
 
1644
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
1731
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
1645
1732
  var snippetReader = null;
1646
1733
  var PRETTY_ERROR_TREE_SPACER = "__EVLOG_TREE_SPACER__";
1647
1734
  function pushTreeSpacer(children) {
@@ -1942,7 +2029,7 @@ function buildErrorEntries(error, options = {}) {
1942
2029
  }];
1943
2030
  }
1944
2031
 
1945
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
2032
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
1946
2033
  var DEV_PRESETS = {
1947
2034
  evlog: {
1948
2035
  frameworkOverlay: false,
@@ -1991,7 +2078,7 @@ function resolveDevTerminal(input = {}) {
1991
2078
  };
1992
2079
  }
1993
2080
 
1994
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
2081
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
1995
2082
  var publisher = null;
1996
2083
  function publishWideEvent(event) {
1997
2084
  if (!publisher)
@@ -2003,13 +2090,13 @@ function publishWideEvent(event) {
2003
2090
  }
2004
2091
  }
2005
2092
 
2006
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
2093
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
2007
2094
  var evlogErrorBrand = Symbol.for("evlog.error.brand");
2008
2095
  function isEvlogError(error) {
2009
2096
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
2010
2097
  }
2011
2098
 
2012
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
2099
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
2013
2100
  var evlogErrorInternalKey = Symbol.for("evlog.error.internal");
2014
2101
  var evlogErrorDataKey = Symbol.for("evlog.error.data");
2015
2102
  var EvlogError = class EvlogError extends Error {
@@ -2113,7 +2200,7 @@ Object.defineProperty(EvlogError.prototype, evlogErrorBrand, {
2113
2200
  enumerable: false
2114
2201
  });
2115
2202
 
2116
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
2203
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
2117
2204
  var nativeStdoutWrite = typeof process !== "undefined" && typeof process.stdout?.write === "function" ? process.stdout.write.bind(process.stdout) : undefined;
2118
2205
  function writePrettyStdout(text) {
2119
2206
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
@@ -2787,7 +2874,16 @@ function finalizeAudit(event) {
2787
2874
  _testCollector?.(decorated, event);
2788
2875
  }
2789
2876
  // src/client/router/provider.tsx
2790
- import { useCallback as useCallback2, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2877
+ import {
2878
+ createElement as createElement6,
2879
+ useCallback as useCallback3,
2880
+ useEffect as useEffect2,
2881
+ useLayoutEffect,
2882
+ useMemo as useMemo2,
2883
+ useRef,
2884
+ useState,
2885
+ useSyncExternalStore as useSyncExternalStore2
2886
+ } from "react";
2791
2887
 
2792
2888
  // ../../node_modules/.bun/seroval@1.6.7/node_modules/seroval/dist/dev/index.js
2793
2889
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
@@ -3843,7 +3939,7 @@ function parseCompactJsonLine(value) {
3843
3939
  import {
3844
3940
  Children,
3845
3941
  cloneElement,
3846
- createElement as createElement3,
3942
+ createElement as createElement4,
3847
3943
  isValidElement,
3848
3944
  use
3849
3945
  } from "react";
@@ -3876,7 +3972,7 @@ function decodeFlightBytes(bytes) {
3876
3972
  }));
3877
3973
  }
3878
3974
  function createRenderableSource(state) {
3879
- const element = createElement3(RscNode, { state });
3975
+ const element = createElement4(RscNode, { state });
3880
3976
  return new Proxy(element, {
3881
3977
  get(target, property, receiver) {
3882
3978
  if (property === RSC_SOURCE) {
@@ -3894,6 +3990,50 @@ function restoreRscSource(kind, bytes) {
3894
3990
  return kind === "renderable" ? createRenderableSource(state) : { [RSC_SOURCE]: state };
3895
3991
  }
3896
3992
 
3993
+ // src/shared/sync-query.ts
3994
+ function mergeQuerySeeds(target, incoming) {
3995
+ for (const seed of incoming) {
3996
+ const index = target.findIndex((existing) => existing.url === seed.url);
3997
+ const previous = target[index];
3998
+ const bindings = [...seed.bindings ?? []];
3999
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
4000
+ for (const binding of previous.bindings ?? []) {
4001
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
4002
+ bindings.push(binding);
4003
+ }
4004
+ }
4005
+ }
4006
+ const merged = { ...seed, bindings };
4007
+ if (index < 0) {
4008
+ target.push(merged);
4009
+ } else {
4010
+ target[index] = merged;
4011
+ }
4012
+ }
4013
+ }
4014
+ var PREFIX = "__furin.query:";
4015
+ function queryTag(identity) {
4016
+ for (const [key, value] of Object.entries(identity.scope)) {
4017
+ if (value === undefined) {
4018
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
4019
+ }
4020
+ }
4021
+ return PREFIX + JSON.stringify([
4022
+ identity.id,
4023
+ Object.entries(identity.scope).sort(([a], [b]) => {
4024
+ if (a === b) {
4025
+ return 0;
4026
+ }
4027
+ return a < b ? -1 : 1;
4028
+ })
4029
+ ]);
4030
+ }
4031
+ function queryUrl(url, origin) {
4032
+ const parsed = new URL(url, origin);
4033
+ parsed.searchParams.sort();
4034
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
4035
+ }
4036
+
3897
4037
  // src/shared/route-frame.ts
3898
4038
  var FRAME_VERSION = 3;
3899
4039
  var MAX_FRAME_BYTES = 1024 * 1024;
@@ -4004,6 +4144,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
4004
4144
  const { frame } = envelope;
4005
4145
  if (frame.type === "data") {
4006
4146
  dataValue = fromCrossJSON(frame.value, {});
4147
+ if (frame.deferredKeys.length > 0 && dataValue && typeof dataValue === "object") {
4148
+ const data = dataValue;
4149
+ data.__furinQueries ??= [];
4150
+ }
4007
4151
  for (const key of frame.deferredKeys) {
4008
4152
  deferredPromises[key] = new Promise((resolve, reject) => {
4009
4153
  resolvers.set(key, { reject, resolve });
@@ -4038,6 +4182,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
4038
4182
  } else if (frame.type === "rsc-error") {
4039
4183
  throw new Error(`[furin] RSC stream failed (${frame.digest})`);
4040
4184
  } else if (frame.type === "defer-resolve") {
4185
+ if (frame.queries && dataValue && typeof dataValue === "object") {
4186
+ const data = dataValue;
4187
+ mergeQuerySeeds(data.__furinQueries ??= [], fromCrossJSON(frame.queries, {}));
4188
+ }
4041
4189
  const value = fromCrossJSON(frame.value, {});
4042
4190
  const ids = new Set;
4043
4191
  collectRscDescriptorIds(value, ids);
@@ -4289,6 +4437,87 @@ async function readDeferredLines(readLine, resolvers) {
4289
4437
  }
4290
4438
  }
4291
4439
 
4440
+ // src/shared/query-bindings.ts
4441
+ function isContainer(value) {
4442
+ if (!value || typeof value !== "object") {
4443
+ return false;
4444
+ }
4445
+ const prototype = Object.getPrototypeOf(value);
4446
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
4447
+ }
4448
+ function replace(value, path, next) {
4449
+ const [key, ...rest] = path;
4450
+ if (key === undefined) {
4451
+ return next;
4452
+ }
4453
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
4454
+ return value;
4455
+ }
4456
+ const child = replace(value[key], rest, next);
4457
+ if (child === value[key]) {
4458
+ return value;
4459
+ }
4460
+ const copy = Array.isArray(value) ? [...value] : { ...value };
4461
+ Object.defineProperty(copy, key, {
4462
+ configurable: true,
4463
+ enumerable: true,
4464
+ value: child,
4465
+ writable: true
4466
+ });
4467
+ return copy;
4468
+ }
4469
+ function isDeferredTarget(data, target) {
4470
+ const [key] = target;
4471
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
4472
+ }
4473
+ function projectQueryData(data, seeds, read) {
4474
+ let projected = data;
4475
+ for (const seed of seeds) {
4476
+ const snapshot = read(seed);
4477
+ if (snapshot === undefined) {
4478
+ continue;
4479
+ }
4480
+ for (const binding of seed.bindings ?? []) {
4481
+ if (isDeferredTarget(data, binding.target)) {
4482
+ continue;
4483
+ }
4484
+ let value = snapshot;
4485
+ for (const key of binding.source) {
4486
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
4487
+ }
4488
+ projected = replace(projected, binding.target, value);
4489
+ }
4490
+ }
4491
+ return projected;
4492
+ }
4493
+ function projectDeferredQueryData(data, seeds, read, resolved) {
4494
+ let base = data;
4495
+ const deferred = new Map;
4496
+ for (const [key, promise] of Object.entries(data)) {
4497
+ if (!(promise instanceof Promise)) {
4498
+ continue;
4499
+ }
4500
+ const state = resolved.get(promise);
4501
+ if (state) {
4502
+ deferred.set(key, { promise, state });
4503
+ base = replace(base, [key], state.value);
4504
+ }
4505
+ }
4506
+ let projected = projectQueryData(base, seeds, read);
4507
+ for (const [key, { promise, state }] of deferred) {
4508
+ const value = isContainer(projected) ? projected[key] : undefined;
4509
+ if (value === state.value) {
4510
+ projected = replace(projected, [key], promise);
4511
+ continue;
4512
+ }
4513
+ if (!state.projection || state.projection.value !== value) {
4514
+ state.projection = { value, promise: Promise.resolve(value) };
4515
+ }
4516
+ projected = replace(projected, [key], state.projection.promise);
4517
+ }
4518
+ return projected;
4519
+ }
4520
+
4292
4521
  // src/client/browser-events.ts
4293
4522
  var BROWSER_EVENT_RUNTIME_KEY = Symbol.for("furin.browser-events.runtime");
4294
4523
  function subscribeBrowserEvent(channel, listener) {
@@ -4296,15 +4525,425 @@ function subscribeBrowserEvent(channel, listener) {
4296
4525
  return runtime?.subscribe(channel, listener);
4297
4526
  }
4298
4527
 
4528
+ // src/client/query.tsx
4529
+ import {
4530
+ createContext as createContext4,
4531
+ useCallback as useCallback2,
4532
+ useContext as useContext4,
4533
+ useEffect,
4534
+ useSyncExternalStore
4535
+ } from "react";
4536
+
4537
+ // src/client/query-store.ts
4538
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
4539
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
4540
+ class QueryStore {
4541
+ entries = new Map;
4542
+ listeners = new Set;
4543
+ revisionValue = 0;
4544
+ projections = new Set;
4545
+ session;
4546
+ epoch = 0;
4547
+ origin;
4548
+ constructor(origin) {
4549
+ this.origin = origin;
4550
+ }
4551
+ key(url) {
4552
+ const absolute = new URL(url, this.origin).href;
4553
+ return queryUrl(absolute, undefined);
4554
+ }
4555
+ entry(url) {
4556
+ const key = this.key(url);
4557
+ let entry = this.entries.get(key);
4558
+ if (!entry) {
4559
+ entry = {
4560
+ base: undefined,
4561
+ listeners: new Set,
4562
+ snapshot: { data: undefined, error: null, isFetching: false },
4563
+ stale: true,
4564
+ version: 0
4565
+ };
4566
+ this.entries.set(key, entry);
4567
+ }
4568
+ return entry;
4569
+ }
4570
+ publish(entry) {
4571
+ let data = entry.base;
4572
+ for (const projection of this.projections) {
4573
+ const transform = projection.transforms.get(entry);
4574
+ if (transform && data !== undefined) {
4575
+ data = transform(data);
4576
+ }
4577
+ }
4578
+ entry.snapshot = { ...entry.snapshot, data };
4579
+ for (const listener of entry.listeners) {
4580
+ listener();
4581
+ }
4582
+ this.revisionValue += 1;
4583
+ for (const listener of this.listeners) {
4584
+ listener();
4585
+ }
4586
+ }
4587
+ revision = () => this.revisionValue;
4588
+ subscribeAll = (listener) => {
4589
+ this.listeners.add(listener);
4590
+ return () => this.listeners.delete(listener);
4591
+ };
4592
+ observe(url, result, epoch, version) {
4593
+ const existing = this.entries.get(this.key(url));
4594
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
4595
+ return;
4596
+ }
4597
+ const header = result.response?.headers.get("x-furin-query");
4598
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
4599
+ if (identity) {
4600
+ this.setSession(identity.session);
4601
+ }
4602
+ const entry = this.entry(url);
4603
+ entry.base = result.data;
4604
+ entry.version += 1;
4605
+ entry.identity = identity;
4606
+ entry.local = result.local ?? result.response?.url === "";
4607
+ entry.stale = false;
4608
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
4609
+ for (const projection of this.projections) {
4610
+ if (!projection.pending) {
4611
+ projection.transforms.delete(entry);
4612
+ if (projection.transforms.size === 0) {
4613
+ this.projections.delete(projection);
4614
+ projection.onRemove?.();
4615
+ }
4616
+ }
4617
+ }
4618
+ this.publish(entry);
4619
+ if (this.entries.size > 100) {
4620
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
4621
+ if (oldest) {
4622
+ this.entries.delete(oldest[0]);
4623
+ }
4624
+ }
4625
+ }
4626
+ setSession(session) {
4627
+ if (this.session !== undefined && this.session !== session) {
4628
+ this.epoch += 1;
4629
+ for (const projection of this.projections) {
4630
+ projection.onRemove?.();
4631
+ }
4632
+ this.projections.clear();
4633
+ for (const entry of this.entries.values()) {
4634
+ entry.base = undefined;
4635
+ entry.identity = undefined;
4636
+ entry.stale = true;
4637
+ entry.version += 1;
4638
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
4639
+ this.publish(entry);
4640
+ }
4641
+ }
4642
+ this.session = session;
4643
+ }
4644
+ generation() {
4645
+ return this.epoch;
4646
+ }
4647
+ version(url) {
4648
+ return this.entry(url).version;
4649
+ }
4650
+ snapshot(url) {
4651
+ return this.entry(url).snapshot;
4652
+ }
4653
+ subscribe(url, listener) {
4654
+ const entry = this.entry(url);
4655
+ entry.listeners.add(listener);
4656
+ return () => entry.listeners.delete(listener);
4657
+ }
4658
+ bind(url, load, client) {
4659
+ const entry = this.entry(url);
4660
+ if (client && entry.client && client !== entry.client) {
4661
+ entry.base = undefined;
4662
+ entry.identity = undefined;
4663
+ entry.stale = true;
4664
+ entry.version += 1;
4665
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
4666
+ for (const projection of this.projections) {
4667
+ projection.transforms.delete(entry);
4668
+ }
4669
+ }
4670
+ entry.client = client ?? entry.client;
4671
+ entry.load = load;
4672
+ }
4673
+ pending(entry) {
4674
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
4675
+ }
4676
+ fetch(url) {
4677
+ const entry = this.entry(url);
4678
+ if (entry.promise) {
4679
+ return entry.promise;
4680
+ }
4681
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
4682
+ return Promise.resolve();
4683
+ }
4684
+ const { version } = entry;
4685
+ const { epoch } = this;
4686
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
4687
+ this.publish(entry);
4688
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
4689
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
4690
+ return;
4691
+ }
4692
+ if (result.error === null) {
4693
+ this.observe(url, result, epoch);
4694
+ } else {
4695
+ entry.snapshot = { ...entry.snapshot, error: result.error };
4696
+ }
4697
+ }).catch((error) => {
4698
+ if (epoch === this.epoch && version === entry.version) {
4699
+ entry.snapshot = { ...entry.snapshot, error };
4700
+ }
4701
+ }).finally(() => {
4702
+ entry.promise = undefined;
4703
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
4704
+ this.publish(entry);
4705
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
4706
+ this.fetch(url);
4707
+ }
4708
+ });
4709
+ return entry.promise;
4710
+ }
4711
+ invalidate(identities) {
4712
+ const tags = new Set(identities.map(queryTag));
4713
+ let affected = false;
4714
+ for (const [url, entry] of this.entries) {
4715
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
4716
+ affected = true;
4717
+ this.invalidateEntry(url, entry);
4718
+ }
4719
+ }
4720
+ return affected;
4721
+ }
4722
+ invalidateEntry(url, entry) {
4723
+ entry.stale = true;
4724
+ entry.version += 1;
4725
+ if (entry.listeners.size > 0) {
4726
+ this.fetch(url);
4727
+ }
4728
+ }
4729
+ invalidateAll() {
4730
+ for (const [url, entry] of this.entries) {
4731
+ this.invalidateEntry(url, entry);
4732
+ }
4733
+ }
4734
+ begin() {
4735
+ return { pending: true, transforms: new Map };
4736
+ }
4737
+ update(projection, url, transform) {
4738
+ const entry = this.entries.get(this.key(url));
4739
+ if (!entry || entry.base === undefined) {
4740
+ return;
4741
+ }
4742
+ const previous = projection.transforms.get(entry);
4743
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
4744
+ entry.version += 1;
4745
+ this.projections.add(projection);
4746
+ this.publish(entry);
4747
+ }
4748
+ finish(projection, outcome) {
4749
+ projection.pending = false;
4750
+ const entries = [...projection.transforms.keys()];
4751
+ if (outcome === "error") {
4752
+ this.projections.delete(projection);
4753
+ projection.onRemove?.();
4754
+ }
4755
+ for (const entry of entries) {
4756
+ this.publish(entry);
4757
+ if (outcome !== "error") {
4758
+ entry.stale = true;
4759
+ }
4760
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
4761
+ if (url && entry.stale) {
4762
+ this.fetch(url);
4763
+ }
4764
+ }
4765
+ }
4766
+ dehydrate() {
4767
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
4768
+ }
4769
+ seedUrl(seed, localOrigin) {
4770
+ const original = new URL(seed.url, this.origin);
4771
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
4772
+ }
4773
+ captureHydration() {
4774
+ const { epoch } = this;
4775
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
4776
+ return (seeds, localOrigin) => {
4777
+ if (epoch === this.epoch) {
4778
+ this.hydrate(seeds.filter((seed) => {
4779
+ const url = this.seedUrl(seed, localOrigin);
4780
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
4781
+ }), localOrigin);
4782
+ }
4783
+ };
4784
+ }
4785
+ hydrate(seeds, localOrigin) {
4786
+ for (const seed of seeds) {
4787
+ const url = this.seedUrl(seed, localOrigin);
4788
+ this.observe(url, {
4789
+ data: seed.data,
4790
+ error: null,
4791
+ identity: seed.identity,
4792
+ local: seed.local ?? false
4793
+ }, this.epoch);
4794
+ }
4795
+ }
4796
+ }
4797
+
4798
+ // src/client/query.tsx
4799
+ var QUERY_CONTEXT = Symbol.for("furin.query.context.v1");
4800
+ var contextGlobal2 = globalThis;
4801
+ var QueryStoreContext = contextGlobal2[QUERY_CONTEXT] ??= createContext4(null);
4802
+
4299
4803
  // src/client/router/abort.ts
4300
4804
  function isAbortError(error) {
4301
4805
  return error !== null && typeof error === "object" && "name" in error && error.name === "AbortError";
4302
4806
  }
4303
4807
 
4808
+ // src/client/router/optimistic.ts
4809
+ var SYNC_REQUEST = Symbol.for("furin.sync.request.v1");
4810
+ function identity(href) {
4811
+ const url = new URL(href, "http://furin.local");
4812
+ url.searchParams.sort();
4813
+ return url.pathname + url.search;
4814
+ }
4815
+ var RUNTIMES = Symbol.for("furin.optimistic.runtimes.v1");
4816
+ var runtimeGlobal = globalThis;
4817
+ var runtimes = runtimeGlobal[RUNTIMES] ??= new Set;
4818
+ function registerOptimisticRuntime(runtime) {
4819
+ runtimes.add(runtime);
4820
+ return () => {
4821
+ runtimes.delete(runtime);
4822
+ };
4823
+ }
4824
+ function createOptimisticRuntime(options) {
4825
+ const operations = new Set;
4826
+ const listeners = new Set;
4827
+ const revisions = new Map;
4828
+ let version = 0;
4829
+ const notify = (operation) => {
4830
+ version += 1;
4831
+ for (const { href } of operation.transforms) {
4832
+ revisions.set(href, (revisions.get(href) ?? 0) + 1);
4833
+ }
4834
+ if (operation.queryHref) {
4835
+ revisions.set(operation.queryHref, (revisions.get(operation.queryHref) ?? 0) + 1);
4836
+ }
4837
+ for (const listener of listeners) {
4838
+ listener();
4839
+ }
4840
+ };
4841
+ const pending = (href) => [...operations].some((operation) => operation.pending && (operation.queryHref === identity(href) || operation.transforms.some((transform) => transform.href === identity(href))));
4842
+ return {
4843
+ basePath: options.basePath,
4844
+ queries: options.queries,
4845
+ begin(optimistic, onRemove, hasQueries) {
4846
+ const operation = { onRemove, pending: true, transforms: [] };
4847
+ const cache = {
4848
+ update(target, transform) {
4849
+ const snapshot = options.snapshot();
4850
+ const path = typeof target === "string" ? target : buildHref(target.path, target.search, undefined);
4851
+ const href = identity(typeof target === "string" && target === snapshot.pattern ? snapshot.href : path);
4852
+ if (snapshot.loaded && href === identity(snapshot.href)) {
4853
+ operation.transforms.push({ href, transform });
4854
+ }
4855
+ }
4856
+ };
4857
+ optimistic?.(cache);
4858
+ if (hasQueries?.() && options.snapshot().loaded) {
4859
+ operation.queryHref = identity(options.snapshot().href);
4860
+ }
4861
+ if (operation.transforms.length > 0 || operation.queryHref !== undefined) {
4862
+ operations.add(operation);
4863
+ notify(operation);
4864
+ }
4865
+ return operation;
4866
+ },
4867
+ commit(href) {
4868
+ for (const operation of operations) {
4869
+ if (!operation.pending) {
4870
+ if (operation.queryHref === identity(href)) {
4871
+ operation.queryHref = undefined;
4872
+ }
4873
+ operation.transforms = operation.transforms.filter((transform) => transform.href !== identity(href));
4874
+ if (operation.transforms.length === 0 && operation.queryHref === undefined) {
4875
+ operations.delete(operation);
4876
+ operation.onRemove?.();
4877
+ }
4878
+ }
4879
+ }
4880
+ },
4881
+ finish(operation, outcome, response) {
4882
+ operation.pending = false;
4883
+ if (outcome === "error") {
4884
+ operations.delete(operation);
4885
+ }
4886
+ if (outcome === "error" || operation.transforms.length === 0 && operation.queryHref === undefined) {
4887
+ operation.onRemove?.();
4888
+ }
4889
+ if (operation.transforms.length > 0 || operation.queryHref !== undefined) {
4890
+ notify(operation);
4891
+ }
4892
+ options.onResponse(response, outcome !== "error" && (operation.transforms.length > 0 || operation.queryHref !== undefined));
4893
+ },
4894
+ has: (href) => [...operations].some((operation) => operation.queryHref === identity(href) || operation.transforms.some((transform) => transform.href === identity(href))),
4895
+ project(data, href) {
4896
+ let projected = data;
4897
+ for (const operation of operations) {
4898
+ for (const transformation of operation.transforms) {
4899
+ if (transformation.href === identity(href)) {
4900
+ projected = { ...projected, ...transformation.transform(projected) };
4901
+ }
4902
+ }
4903
+ }
4904
+ return projected;
4905
+ },
4906
+ publishable: (href, revision) => !pending(href) && (revisions.get(identity(href)) ?? 0) === revision,
4907
+ revision: (href) => href === undefined ? version : revisions.get(identity(href)) ?? 0,
4908
+ subscribe(listener) {
4909
+ listeners.add(listener);
4910
+ return () => {
4911
+ listeners.delete(listener);
4912
+ };
4913
+ },
4914
+ wait(href, signal) {
4915
+ if (signal?.aborted) {
4916
+ return Promise.reject(signal.reason);
4917
+ }
4918
+ if (!pending(href)) {
4919
+ return Promise.resolve();
4920
+ }
4921
+ return new Promise((resolve, reject) => {
4922
+ const cleanup = () => {
4923
+ listeners.delete(check);
4924
+ signal?.removeEventListener("abort", abort);
4925
+ };
4926
+ const abort = () => {
4927
+ cleanup();
4928
+ reject(signal?.reason);
4929
+ };
4930
+ const check = () => {
4931
+ if (!pending(href)) {
4932
+ cleanup();
4933
+ resolve();
4934
+ }
4935
+ };
4936
+ listeners.add(check);
4937
+ signal?.addEventListener("abort", abort, { once: true });
4938
+ });
4939
+ }
4940
+ };
4941
+ }
4942
+
4304
4943
  // src/client/router/search-store.ts
4305
- import { createContext as createContext3 } from "react";
4944
+ import { createContext as createContext5 } from "react";
4306
4945
  function searchSnapshotChanged(a, b) {
4307
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4946
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
4308
4947
  }
4309
4948
  function createSearchStore(initialSnapshot) {
4310
4949
  let snapshot = initialSnapshot;
@@ -4341,6 +4980,7 @@ function createSearchStore(initialSnapshot) {
4341
4980
  function searchSnapshotFromRouterContext(context) {
4342
4981
  return {
4343
4982
  currentHref: context.currentHref,
4983
+ currentPattern: context.currentPattern,
4344
4984
  navigate: context.navigate,
4345
4985
  search: context.search,
4346
4986
  searchRoutes: context.searchRoutes
@@ -4348,6 +4988,7 @@ function searchSnapshotFromRouterContext(context) {
4348
4988
  }
4349
4989
  var FALLBACK_SEARCH_STORE = createSearchStore({
4350
4990
  currentHref: "/",
4991
+ currentPattern: undefined,
4351
4992
  navigate: (href, _opts) => {
4352
4993
  if (typeof window !== "undefined") {
4353
4994
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -4360,10 +5001,10 @@ var FALLBACK_SEARCH_STORE = createSearchStore({
4360
5001
  search: {},
4361
5002
  searchRoutes: []
4362
5003
  });
4363
- var SearchStoreContext = createContext3(null);
5004
+ var SearchStoreContext = createContext5(null);
4364
5005
 
4365
5006
  // src/client/router/spa-response.ts
4366
- import { createElement as createElement4 } from "react";
5007
+ import { createElement as createElement5 } from "react";
4367
5008
  function isFurinErrorPayload(value) {
4368
5009
  if (!value || typeof value !== "object") {
4369
5010
  return false;
@@ -4398,10 +5039,10 @@ function pickDeepestNotFound(boundaries) {
4398
5039
  }
4399
5040
  }
4400
5041
  }
4401
- var DefaultClientNotFoundFallback = ({ error }) => createElement4(DefaultNotFoundScreen, { message: error.message });
5042
+ var DefaultClientNotFoundFallback = ({ error }) => createElement5(DefaultNotFoundScreen, { message: error.message });
4402
5043
  function buildNotFoundPageElement(boundaries, error) {
4403
5044
  const Fallback = pickDeepestNotFound(boundaries) ?? DefaultClientNotFoundFallback;
4404
- return createElement4(Fallback, { error });
5045
+ return createElement5(Fallback, { error });
4405
5046
  }
4406
5047
  async function parsePageResponse(res, basePath) {
4407
5048
  let finalHref;
@@ -4474,12 +5115,16 @@ function createSyncCatchUp(options) {
4474
5115
  do {
4475
5116
  page = await options.fetchPage(currentCursor ?? "0");
4476
5117
  if (page.reset) {
5118
+ options.onReset?.();
4477
5119
  options.onInvalidations(["/:layout"]);
4478
5120
  currentCursor = page.cursor;
4479
5121
  break;
4480
5122
  }
4481
5123
  for (const change of page.changes) {
4482
5124
  options.onInvalidations(change.invalidations);
5125
+ if (change.queries) {
5126
+ options.onQueries?.(change.queries);
5127
+ }
4483
5128
  }
4484
5129
  currentCursor = page.cursor;
4485
5130
  } while (page.hasMore);
@@ -4561,8 +5206,15 @@ function RouterProvider({
4561
5206
  syncPath
4562
5207
  }) {
4563
5208
  const initialDocumentState = useDocumentState();
5209
+ const [queries] = useState(() => {
5210
+ const store = new QueryStore(typeof window === "undefined" ? undefined : window.location.origin);
5211
+ store.hydrate(initialData.__furinQueries ?? [], typeof window === "undefined" ? undefined : window.location.origin);
5212
+ return store;
5213
+ });
4564
5214
  const [state, setState] = useState(() => ({
4565
- data: initialData,
5215
+ data: Object.fromEntries(Object.entries(initialData).filter(([key]) => key !== "__furinQueries")),
5216
+ querySeeds: initialData.__furinQueries,
5217
+ hydrateQueries: queries.captureHydration(),
4566
5218
  error: initialError ? {
4567
5219
  ...initialError,
4568
5220
  message: initialError.message || "Something went wrong"
@@ -4572,6 +5224,42 @@ function RouterProvider({
4572
5224
  notFound: initialNotFound
4573
5225
  }));
4574
5226
  const [boundaryResetVersion, setBoundaryResetVersion] = useState(0);
5227
+ const currentState = useRef(state);
5228
+ useLayoutEffect(() => {
5229
+ currentState.current = state;
5230
+ }, [state]);
5231
+ useLayoutEffect(() => {
5232
+ state.hydrateQueries?.(state.querySeeds ?? [], typeof window === "undefined" ? undefined : window.location.origin);
5233
+ }, [state.hydrateQueries, state.querySeeds]);
5234
+ const resolvedQueries = useRef(new WeakMap);
5235
+ const [deferredRevision, setDeferredRevision] = useState(0);
5236
+ useEffect2(() => {
5237
+ const snapshot = currentState.current;
5238
+ const hydrated = new Set(snapshot.querySeeds?.map((seed) => seed.url));
5239
+ let disposed = false;
5240
+ for (const promise of Object.values(state.data)) {
5241
+ if (!(promise instanceof Promise)) {
5242
+ continue;
5243
+ }
5244
+ promise.then((value) => {
5245
+ if (disposed) {
5246
+ return;
5247
+ }
5248
+ resolvedQueries.current.set(promise, { value });
5249
+ const seeds = (snapshot.querySeeds ?? []).filter((seed) => !hydrated.has(seed.url));
5250
+ snapshot.hydrateQueries?.(seeds, window.location.origin);
5251
+ for (const seed of seeds) {
5252
+ hydrated.add(seed.url);
5253
+ }
5254
+ setDeferredRevision((revision) => revision + 1);
5255
+ }, () => {
5256
+ return;
5257
+ });
5258
+ }
5259
+ return () => {
5260
+ disposed = true;
5261
+ };
5262
+ }, [queries, state.data]);
4575
5263
  const [isNavigating, setIsNavigating] = useState(false);
4576
5264
  const [currentHref, setCurrentHref] = useState(() => {
4577
5265
  if (typeof window === "undefined") {
@@ -4579,6 +5267,29 @@ function RouterProvider({
4579
5267
  }
4580
5268
  return normalizeHref(toLogical(window.location.pathname, basePath)) + window.location.search;
4581
5269
  });
5270
+ const optimisticSnapshot = useRef({
5271
+ href: currentHref,
5272
+ loaded: state.match !== null,
5273
+ pattern: state.match?.pattern
5274
+ });
5275
+ useLayoutEffect(() => {
5276
+ optimisticSnapshot.current = {
5277
+ href: currentHref,
5278
+ loaded: state.match !== null && !(state.error || state.notFound),
5279
+ pattern: state.match?.pattern
5280
+ };
5281
+ }, [currentHref, state.match, state.error, state.notFound]);
5282
+ const syncResponse = useRef(undefined);
5283
+ const [optimisticRuntime] = useState(() => createOptimisticRuntime({
5284
+ basePath,
5285
+ queries,
5286
+ snapshot: () => optimisticSnapshot.current,
5287
+ onResponse: (response, optimistic) => syncResponse.current?.(response, optimistic)
5288
+ }));
5289
+ useSyncExternalStore2(optimisticRuntime.subscribe, optimisticRuntime.revision, () => 0);
5290
+ const queryRevision = useSyncExternalStore2(queries.subscribeAll, queries.revision, () => 0);
5291
+ useEffect2(() => registerOptimisticRuntime(optimisticRuntime), [optimisticRuntime]);
5292
+ const snapshotVersions = useRef(new WeakMap);
4582
5293
  const prefetchCache = useRef(new Map);
4583
5294
  const navVersion = useRef(0);
4584
5295
  const hmrVersion = useRef(0);
@@ -4586,18 +5297,19 @@ function RouterProvider({
4586
5297
  const pendingUserNavigation = useRef(null);
4587
5298
  const navAbortRef = useRef(null);
4588
5299
  const pendingScrollRef = useRef(null);
5300
+ const renderedHistoryKey = useRef(undefined);
4589
5301
  const currentMatchRef = useRef(initialMatch);
4590
5302
  const [staticMode] = useState(detectStaticMode);
4591
5303
  const resolvedSearch = state.data.query ?? EMPTY_SEARCH;
4592
- const rootBoundaries = useMemo(() => {
5304
+ const rootBoundaries = useMemo2(() => {
4593
5305
  for (const route of routes) {
4594
- const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0);
5306
+ const depth0 = route.segmentBoundaries?.find((b) => b.depth === 0 && b.isRoot !== false);
4595
5307
  if (depth0) {
4596
5308
  return [depth0];
4597
5309
  }
4598
5310
  }
4599
5311
  }, [routes]);
4600
- const resolveNoMatchState = useCallback2(async (physicalHref, signal) => {
5312
+ const resolveNoMatchState = useCallback3(async (physicalHref, signal) => {
4601
5313
  const res = await fetch(physicalHref, { signal });
4602
5314
  if (isStaleDeployResponse(res)) {
4603
5315
  return null;
@@ -4617,7 +5329,8 @@ function RouterProvider({
4617
5329
  title
4618
5330
  };
4619
5331
  }, [basePath, rootBoundaries]);
4620
- const fetchPageState = useCallback2(async (rawLogicalHref, signal, hmrRefresh) => {
5332
+ const fetchPageState = useCallback3(async (rawLogicalHref, signal, hmrRefresh) => {
5333
+ const hydrateQueries = queries.captureHydration();
4621
5334
  const logicalHref = normalizeHref(rawLogicalHref);
4622
5335
  try {
4623
5336
  const physicalHref = basePath + logicalHref;
@@ -4665,6 +5378,7 @@ function RouterProvider({
4665
5378
  __furinRedirect,
4666
5379
  __furinError,
4667
5380
  __furinTitle,
5381
+ __furinQueries,
4668
5382
  ...cleanSyncData
4669
5383
  } = syncData;
4670
5384
  if (typeof __furinRedirect === "string") {
@@ -4716,7 +5430,14 @@ function RouterProvider({
4716
5430
  title
4717
5431
  };
4718
5432
  }
4719
- return { data, head: __furinHead, match: loadedMatch, title };
5433
+ return {
5434
+ data,
5435
+ head: __furinHead,
5436
+ match: loadedMatch,
5437
+ querySeeds: __furinQueries,
5438
+ hydrateQueries,
5439
+ title
5440
+ };
4720
5441
  } catch (err) {
4721
5442
  if (!isAbortError(err)) {
4722
5443
  _log.error({
@@ -4727,26 +5448,38 @@ function RouterProvider({
4727
5448
  }
4728
5449
  return null;
4729
5450
  }
4730
- }, [routes, basePath, resolveNoMatchState]);
4731
- const invalidatePrefetch = useCallback2((path, type) => {
4732
- const normalizedPath = stripHashFromHref(path);
4733
- if (type === "page") {
4734
- for (const key of [...prefetchCache.current.keys()]) {
4735
- if (stripHashFromHref(key) === normalizedPath) {
4736
- prefetchCache.current.delete(key);
5451
+ }, [routes, basePath, resolveNoMatchState, queries]);
5452
+ const fetchConfirmedPageState = useCallback3(async (href, signal, hmrRefresh) => {
5453
+ for (;; ) {
5454
+ try {
5455
+ await optimisticRuntime.wait(href, signal);
5456
+ } catch (error) {
5457
+ if (signal?.aborted) {
5458
+ return null;
4737
5459
  }
5460
+ throw error;
5461
+ }
5462
+ const version = optimisticRuntime.revision(href);
5463
+ const snapshot = await fetchPageState(href, signal, hmrRefresh);
5464
+ if (optimisticRuntime.publishable(href, version)) {
5465
+ if (snapshot) {
5466
+ snapshotVersions.current.set(snapshot, version);
5467
+ }
5468
+ return snapshot;
4738
5469
  }
4739
- return;
4740
5470
  }
4741
- const prefix = normalizedPath === "/" || normalizedPath.endsWith("/") ? normalizedPath : `${normalizedPath}/`;
5471
+ }, [fetchPageState, optimisticRuntime]);
5472
+ const invalidatePrefetch = useCallback3((path, type) => {
5473
+ const normalizedPath = normalizeHref(new URL(path, "http://furin.local").pathname);
4742
5474
  for (const key of [...prefetchCache.current.keys()]) {
4743
- const normalizedKey = stripHashFromHref(key);
4744
- if (normalizedKey === normalizedPath || normalizedKey.startsWith(prefix)) {
5475
+ if (shouldAutoRefreshPath(normalizeHref(stripHashFromHref(key)), [
5476
+ { path: normalizedPath, type }
5477
+ ])) {
4745
5478
  prefetchCache.current.delete(key);
4746
5479
  }
4747
5480
  }
4748
5481
  }, []);
4749
- const prefetch = useCallback2((href, opts) => {
5482
+ const prefetch = useCallback3((href, opts) => {
4750
5483
  const staleTime = opts?.staleTime ?? defaultPreloadStaleTime;
4751
5484
  const existing = prefetchCache.current.get(href);
4752
5485
  if (existing && !shouldRefetch(existing)) {
@@ -4760,13 +5493,13 @@ function RouterProvider({
4760
5493
  }, [fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
4761
5494
  async function resolveRedirectState(redirectLogical, myVersion, signal) {
4762
5495
  const cached = prefetchCache.current.get(redirectLogical);
4763
- const useCached = cached !== undefined && !shouldRefetch(cached);
4764
- let redirectState = useCached && cached ? await cached.promise : await fetchPageState(redirectLogical, signal, false);
5496
+ const useCached = cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(redirectLogical);
5497
+ let redirectState = useCached && cached ? await cached.promise : await fetchConfirmedPageState(redirectLogical, signal, false);
4765
5498
  if (navVersion.current !== myVersion) {
4766
5499
  return null;
4767
5500
  }
4768
- if (useCached && isRedirectState(redirectState)) {
4769
- redirectState = await fetchPageState(redirectLogical, signal, false);
5501
+ if (useCached && (isRedirectState(redirectState) || redirectState && !optimisticRuntime.publishable(redirectLogical, snapshotVersions.current.get(redirectState) ?? optimisticRuntime.revision(redirectLogical)))) {
5502
+ redirectState = await fetchConfirmedPageState(redirectLogical, signal, false);
4770
5503
  }
4771
5504
  return navVersion.current === myVersion ? redirectState : null;
4772
5505
  }
@@ -4788,8 +5521,9 @@ function RouterProvider({
4788
5521
  }
4789
5522
  return { href, state: redirectState };
4790
5523
  }
4791
- const navigate = useCallback2(async function navigateTo(rawLogicalHref, opts) {
5524
+ const navigate = useCallback3(async function navigateTo(rawLogicalHref, opts) {
4792
5525
  const logicalHref = normalizeHref(rawLogicalHref);
5526
+ const beforeCommit = opts?.beforeCommit;
4793
5527
  const finishUserNavigation = opts?.hmrRefresh === true ? undefined : beginUserNavigation(pendingUserNavigation);
4794
5528
  navVersion.current += 1;
4795
5529
  const myVersion = navVersion.current;
@@ -4800,11 +5534,11 @@ function RouterProvider({
4800
5534
  setIsNavigating(true);
4801
5535
  try {
4802
5536
  const cached = prefetchCache.current.get(logicalHref);
4803
- const useCached = cached !== undefined && !shouldRefetch(cached);
4804
- let newState = useCached && cached ? await cached.promise : await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
4805
- const cachedRedirect = useCached && isRedirectState(newState);
5537
+ const useCached = cached !== undefined && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref);
5538
+ let newState = useCached && cached ? await cached.promise : await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
5539
+ const cachedRedirect = useCached && (isRedirectState(newState) || newState && !optimisticRuntime.publishable(logicalHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref)));
4806
5540
  if (cachedRedirect) {
4807
- newState = await fetchPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
5541
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, opts?.hmrRefresh === true);
4808
5542
  }
4809
5543
  if (navVersion.current !== myVersion || opts?.shouldCommit?.() === false) {
4810
5544
  return;
@@ -4839,7 +5573,14 @@ function RouterProvider({
4839
5573
  if (opts?.shouldCommit?.() === false) {
4840
5574
  return;
4841
5575
  }
4842
- opts?.beforeCommit?.();
5576
+ const publicationHref = newState.finalHref ?? resolved.href;
5577
+ if (!optimisticRuntime.publishable(publicationHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref))) {
5578
+ return;
5579
+ }
5580
+ if (!(newState.error || newState.notFound)) {
5581
+ optimisticRuntime.commit(publicationHref);
5582
+ }
5583
+ beforeCommit?.();
4843
5584
  const effectiveLogical = newState.finalHref ?? resolved.href;
4844
5585
  const physicalEffective = basePath + effectiveLogical;
4845
5586
  if (opts?.resetScroll ?? true) {
@@ -4859,12 +5600,13 @@ function RouterProvider({
4859
5600
  _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
4860
5601
  }, "", physicalEffective);
4861
5602
  } else {
4862
- const currentKey = getHistoryKey(history.state);
5603
+ const currentKey = renderedHistoryKey.current;
4863
5604
  if (currentKey) {
4864
5605
  saveScrollPosition(currentKey);
4865
5606
  }
4866
5607
  window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
4867
5608
  }
5609
+ renderedHistoryKey.current = getHistoryKey(history.state);
4868
5610
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
4869
5611
  const logicalPath = normalizeHref(toLogical(effectiveUrl.pathname, basePath));
4870
5612
  setCurrentHref(logicalPath + effectiveUrl.search);
@@ -4874,24 +5616,32 @@ function RouterProvider({
4874
5616
  setIsNavigating(false);
4875
5617
  }
4876
5618
  }
4877
- }, [basePath, fetchPageState, defaultPreloadStaleTime, prefetchCacheSize]);
5619
+ }, [
5620
+ basePath,
5621
+ fetchConfirmedPageState,
5622
+ defaultPreloadStaleTime,
5623
+ prefetchCacheSize,
5624
+ optimisticRuntime
5625
+ ]);
4878
5626
  const [searchStore] = useState(() => createSearchStore({
4879
5627
  currentHref,
5628
+ currentPattern: state.match?.pattern,
4880
5629
  navigate,
4881
5630
  search: resolvedSearch,
4882
5631
  searchRoutes: routes
4883
5632
  }));
4884
- const searchSnapshot = useMemo(() => ({
5633
+ const searchSnapshot = useMemo2(() => ({
4885
5634
  currentHref,
5635
+ currentPattern: state.match?.pattern,
4886
5636
  navigate,
4887
5637
  search: resolvedSearch,
4888
5638
  searchRoutes: routes
4889
- }), [currentHref, navigate, resolvedSearch, routes]);
5639
+ }), [currentHref, state.match?.pattern, navigate, resolvedSearch, routes]);
4890
5640
  useLayoutEffect(() => {
4891
5641
  searchStore.setSnapshot(searchSnapshot);
4892
5642
  searchStore.flush();
4893
5643
  }, [searchStore, searchSnapshot]);
4894
- const refresh = useCallback2(async (opts) => {
5644
+ const refresh = useCallback3(async (opts) => {
4895
5645
  const logicalPath = toLogical(window.location.pathname, basePath);
4896
5646
  const logicalHref = logicalPath + window.location.search;
4897
5647
  invalidatePrefetch(logicalHref, "page");
@@ -4903,13 +5653,34 @@ function RouterProvider({
4903
5653
  shouldCommit: opts?.shouldCommit
4904
5654
  });
4905
5655
  }, [navigate, invalidatePrefetch, basePath]);
4906
- const invalidationRefresh = useMemo(() => createInvalidationRefresh({
5656
+ const invalidationRefresh = useMemo2(() => createInvalidationRefresh({
4907
5657
  onError: (error) => {
4908
5658
  _log.warn({ action: "sync_refresh_failed", error: String(error) });
4909
5659
  },
4910
- refresh: () => refresh(undefined)
5660
+ refresh: async () => {
5661
+ await waitForUserNavigation(pendingUserNavigation);
5662
+ await refresh(undefined);
5663
+ }
4911
5664
  }), [refresh]);
4912
- useEffect(() => {
5665
+ useLayoutEffect(() => {
5666
+ syncResponse.current = (response, optimistic) => {
5667
+ const invalidated = [];
5668
+ if (response && (response.url === "" || new URL(response.url).origin === window.location.origin)) {
5669
+ applyRevalidateHeader(response.headers, (path, type) => {
5670
+ const resolvedType = type ?? "page";
5671
+ invalidatePrefetch(path, resolvedType);
5672
+ invalidated.push({ path, type: resolvedType });
5673
+ });
5674
+ }
5675
+ if (optimistic || autoRefresh && shouldAutoRefreshPath(optimisticSnapshot.current.href, invalidated)) {
5676
+ invalidationRefresh.run();
5677
+ }
5678
+ };
5679
+ return () => {
5680
+ syncResponse.current = undefined;
5681
+ };
5682
+ }, [autoRefresh, invalidatePrefetch, invalidationRefresh]);
5683
+ useEffect2(() => {
4913
5684
  if (typeof window !== "undefined") {
4914
5685
  window.__FURIN_HMR_REFRESH__ = async (beforeCommit, dataChanged) => {
4915
5686
  hmrVersion.current += 1;
@@ -4943,8 +5714,11 @@ function RouterProvider({
4943
5714
  };
4944
5715
  }
4945
5716
  }, [refresh]);
4946
- const handlePopState = useCallback2(() => {
5717
+ const handlePopState = useCallback3(() => {
4947
5718
  const finishUserNavigation = beginUserNavigation(pendingUserNavigation);
5719
+ if (renderedHistoryKey.current) {
5720
+ saveScrollPosition(renderedHistoryKey.current);
5721
+ }
4948
5722
  const destKey = getHistoryKey(history.state);
4949
5723
  const logicalPath = normalizeHref(toLogical(window.location.pathname, basePath));
4950
5724
  const logicalHref = logicalPath + window.location.search;
@@ -4959,13 +5733,13 @@ function RouterProvider({
4959
5733
  try {
4960
5734
  const cached = prefetchCache.current.get(logicalHref);
4961
5735
  let newState;
4962
- if (cached && !shouldRefetch(cached)) {
5736
+ if (cached && !shouldRefetch(cached) && !optimisticRuntime.has(logicalHref)) {
4963
5737
  newState = await cached.promise;
4964
- if (isRedirectState(newState)) {
4965
- newState = await fetchPageState(logicalHref, navSignal, false);
5738
+ if (isRedirectState(newState) || newState && !optimisticRuntime.publishable(logicalHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(logicalHref))) {
5739
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
4966
5740
  }
4967
5741
  } else {
4968
- newState = await fetchPageState(logicalHref, navSignal, false);
5742
+ newState = await fetchConfirmedPageState(logicalHref, navSignal, false);
4969
5743
  }
4970
5744
  if (navVersion.current !== myVersion) {
4971
5745
  return;
@@ -4990,6 +5764,13 @@ function RouterProvider({
4990
5764
  return;
4991
5765
  }
4992
5766
  newState = resolved.state;
5767
+ const publicationHref = newState.finalHref ?? resolved.href;
5768
+ if (!optimisticRuntime.publishable(publicationHref, snapshotVersions.current.get(newState) ?? optimisticRuntime.revision(publicationHref))) {
5769
+ return;
5770
+ }
5771
+ if (!(newState.error || newState.notFound)) {
5772
+ optimisticRuntime.commit(publicationHref);
5773
+ }
4993
5774
  currentMatchRef.current = newState.match;
4994
5775
  if (!newState.error) {
4995
5776
  setBoundaryResetVersion((version) => version + 1);
@@ -5002,6 +5783,7 @@ function RouterProvider({
5002
5783
  if (effectiveLogical !== logicalHref) {
5003
5784
  window.history.replaceState(history.state, "", basePath + effectiveLogical);
5004
5785
  }
5786
+ renderedHistoryKey.current = destKey;
5005
5787
  setCurrentHref(normalizeHref(effectiveLogical));
5006
5788
  if (destKey) {
5007
5789
  pendingScrollRef.current = { key: destKey, type: "restore" };
@@ -5015,12 +5797,13 @@ function RouterProvider({
5015
5797
  }
5016
5798
  }
5017
5799
  })();
5018
- }, [fetchPageState, basePath]);
5019
- useEffect(() => {
5800
+ }, [fetchConfirmedPageState, basePath, optimisticRuntime]);
5801
+ useEffect2(() => {
5020
5802
  history.scrollRestoration = "manual";
5021
5803
  if (!getHistoryKey(history.state)) {
5022
5804
  history.replaceState({ ...getHistoryStateObject(), _furinKey: generateHistoryKey() }, "");
5023
5805
  }
5806
+ renderedHistoryKey.current = getHistoryKey(history.state);
5024
5807
  }, []);
5025
5808
  useLayoutEffect(() => {
5026
5809
  const instruction = pendingScrollRef.current;
@@ -5050,11 +5833,11 @@ function RouterProvider({
5050
5833
  window.scrollTo({ behavior: "instant", top: 0 });
5051
5834
  }
5052
5835
  }, [currentHref, state]);
5053
- useEffect(() => {
5836
+ useEffect2(() => {
5054
5837
  window.addEventListener("popstate", handlePopState);
5055
5838
  return () => window.removeEventListener("popstate", handlePopState);
5056
5839
  }, [handlePopState]);
5057
- useEffect(() => {
5840
+ useEffect2(() => {
5058
5841
  if (typeof window === "undefined") {
5059
5842
  return;
5060
5843
  }
@@ -5079,18 +5862,21 @@ function RouterProvider({
5079
5862
  return;
5080
5863
  }
5081
5864
  e.preventDefault();
5082
- navigate(logicalHref, { resetScroll: !logicalHref.includes("#") });
5865
+ navigate(logicalHref, undefined);
5083
5866
  };
5084
5867
  document.addEventListener("click", handler);
5085
5868
  return () => document.removeEventListener("click", handler);
5086
5869
  }, [navigate, basePath, routes]);
5087
- useEffect(() => {
5870
+ useEffect2(() => {
5088
5871
  if (typeof window === "undefined") {
5089
5872
  return;
5090
5873
  }
5091
5874
  const originalFetch = window.fetch;
5092
5875
  const wrapped = async (...args) => {
5093
5876
  const response = await originalFetch.apply(window, args);
5877
+ if (args[1] && SYNC_REQUEST in args[1]) {
5878
+ return response;
5879
+ }
5094
5880
  if (!isSameOriginFetchResult(args[0], response.url, window.location.origin)) {
5095
5881
  return response;
5096
5882
  }
@@ -5114,7 +5900,7 @@ function RouterProvider({
5114
5900
  window.fetch = originalFetch;
5115
5901
  };
5116
5902
  }, [invalidatePrefetch, invalidationRefresh, autoRefresh, basePath]);
5117
- useEffect(() => {
5903
+ useEffect2(() => {
5118
5904
  if (!syncPath || typeof window === "undefined") {
5119
5905
  return;
5120
5906
  }
@@ -5150,7 +5936,25 @@ function RouterProvider({
5150
5936
  }
5151
5937
  return await response.json();
5152
5938
  },
5153
- onInvalidations: applyInvalidations
5939
+ onInvalidations: applyInvalidations,
5940
+ onReset: () => queries.invalidateAll(),
5941
+ onQueries: (identities) => {
5942
+ queries.invalidate(identities);
5943
+ const tags = new Set(identities.map(queryTag));
5944
+ const affected = (snapshot) => snapshot.querySeeds?.some((seed) => tags.has(queryTag(seed.identity)));
5945
+ for (const [href, entry] of prefetchCache.current) {
5946
+ entry.promise.then((snapshot) => {
5947
+ if (snapshot && affected(snapshot) && prefetchCache.current.get(href) === entry) {
5948
+ prefetchCache.current.delete(href);
5949
+ }
5950
+ }).catch(() => {
5951
+ return;
5952
+ });
5953
+ }
5954
+ if (autoRefresh && affected(currentState.current)) {
5955
+ invalidationRefresh.run();
5956
+ }
5957
+ }
5154
5958
  });
5155
5959
  const recover = () => {
5156
5960
  if (disposed) {
@@ -5184,12 +5988,21 @@ function RouterProvider({
5184
5988
  disposed = true;
5185
5989
  unsubscribe?.();
5186
5990
  };
5187
- }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh]);
5991
+ }, [syncPath, basePath, invalidatePrefetch, invalidationRefresh, autoRefresh, queries]);
5992
+ const queryData = useMemo2(() => projectDeferredQueryData(state.data, state.querySeeds ?? [], (seed) => {
5993
+ if (seed.local && typeof window !== "undefined") {
5994
+ const original = new URL(seed.url);
5995
+ return queries.snapshot(new URL(original.pathname + original.search, window.location.origin).href).data;
5996
+ }
5997
+ return queries.snapshot(seed.url).data;
5998
+ }, resolvedQueries.current), [queries, state.data, state.querySeeds, queryRevision, deferredRevision]);
5999
+ const renderedData = optimisticRuntime.project(queryData, currentHref);
5188
6000
  let pageElement;
5189
6001
  if (state.notFound || !state.match) {
5190
- pageElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
6002
+ const notFoundElement = buildNotFoundPageElement(state.notFoundBoundaries ?? state.match?.segmentBoundaries ?? rootBoundaries, state.notFound ?? {});
6003
+ pageElement = root?.layout ? createElement6(root.layout, renderedData, notFoundElement) : notFoundElement;
5191
6004
  } else {
5192
- pageElement = buildPageElement(state.match, root, state.data, {
6005
+ pageElement = buildPageElement(state.match, root, renderedData, {
5193
6006
  onReset: () => {
5194
6007
  refresh(undefined).catch((err) => {
5195
6008
  _log.error({ action: "boundary_reset_failed", error: String(err) });
@@ -5203,6 +6016,7 @@ function RouterProvider({
5203
6016
  children: buildRouterTree({
5204
6017
  basePath,
5205
6018
  currentHref,
6019
+ currentPattern: state.match?.pattern,
5206
6020
  defaultPreload,
5207
6021
  defaultPreloadDelay,
5208
6022
  defaultPreloadStaleTime,
@@ -5225,14 +6039,20 @@ function RouterProvider({
5225
6039
  })
5226
6040
  }, undefined, false, undefined, this);
5227
6041
  if (initialDocumentState === null) {
5228
- return routerTree;
6042
+ return /* @__PURE__ */ jsxDEV5(QueryStoreContext.Provider, {
6043
+ value: queries,
6044
+ children: routerTree
6045
+ }, undefined, false, undefined, this);
5229
6046
  }
5230
6047
  return /* @__PURE__ */ jsxDEV5(DocumentProvider, {
5231
6048
  value: {
5232
6049
  ...initialDocumentState,
5233
6050
  head: state.head
5234
6051
  },
5235
- children: routerTree
6052
+ children: /* @__PURE__ */ jsxDEV5(QueryStoreContext.Provider, {
6053
+ value: queries,
6054
+ children: routerTree
6055
+ }, undefined, false, undefined, this)
5236
6056
  }, undefined, false, undefined, this);
5237
6057
  }
5238
6058
  // src/client/link.tsx
@@ -5284,7 +6104,7 @@ function LinkInteractive({
5284
6104
  href: _href,
5285
6105
  ...anchorProps
5286
6106
  }) {
5287
- const router2 = useRouter();
6107
+ const router2 = useRouterContext();
5288
6108
  const anchorRef = useRef2(null);
5289
6109
  const intentTimerRef = useRef2(null);
5290
6110
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -5292,15 +6112,15 @@ function LinkInteractive({
5292
6112
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
5293
6113
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
5294
6114
  const { prefetch } = router2;
5295
- const triggerPrefetch = useCallback3(() => {
6115
+ const triggerPrefetch = useCallback4(() => {
5296
6116
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
5297
6117
  }, [prefetch, logicalHref, effectiveStaleTime]);
5298
- useEffect2(() => {
6118
+ useEffect3(() => {
5299
6119
  if (effectivePreload === "render") {
5300
6120
  triggerPrefetch();
5301
6121
  }
5302
6122
  }, [effectivePreload, triggerPrefetch]);
5303
- useEffect2(() => {
6123
+ useEffect3(() => {
5304
6124
  if (effectivePreload !== "viewport" || !anchorRef.current) {
5305
6125
  return;
5306
6126
  }
@@ -5313,7 +6133,7 @@ function LinkInteractive({
5313
6133
  observer.observe(anchorRef.current);
5314
6134
  return () => observer.disconnect();
5315
6135
  }, [effectivePreload, triggerPrefetch]);
5316
- useEffect2(() => () => {
6136
+ useEffect3(() => () => {
5317
6137
  if (intentTimerRef.current !== null) {
5318
6138
  clearTimeout(intentTimerRef.current);
5319
6139
  intentTimerRef.current = null;
@@ -5367,7 +6187,7 @@ function LinkInteractive({
5367
6187
  triggerPrefetch();
5368
6188
  }
5369
6189
  };
5370
- return createElement5("a", {
6190
+ return createElement7("a", {
5371
6191
  "data-furin-link": true,
5372
6192
  href,
5373
6193
  onClick: handleClick,
@@ -5418,7 +6238,7 @@ function renderLinkElement(props, router2) {
5418
6238
  href: _href,
5419
6239
  ...anchorProps
5420
6240
  } = props;
5421
- return createElement5("a", {
6241
+ return createElement7("a", {
5422
6242
  "data-furin-link": true,
5423
6243
  href,
5424
6244
  ...isActive ? { "data-status": "active" } : {},
@@ -5429,11 +6249,11 @@ function renderLinkElement(props, router2) {
5429
6249
  }
5430
6250
  function Link(props) {
5431
6251
  if (typeof window === "undefined") {
5432
- return createElement5(RouterContext.Consumer, {
6252
+ return createElement7(RouterContext.Consumer, {
5433
6253
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
5434
6254
  });
5435
6255
  }
5436
- return createElement5(LinkInteractive, props);
6256
+ return createElement7(LinkInteractive, props);
5437
6257
  }
5438
6258
  export {
5439
6259
  CLIENT_FALLBACK_ROUTER,