@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
package/dist/furin.js CHANGED
@@ -759,6 +759,7 @@ function withMetadata(metadata) {
759
759
  return {
760
760
  mode: metadata.mode,
761
761
  revalidate: metadata.revalidate,
762
+ remountDeps: metadata.remountDeps,
762
763
  staticParams: metadata.staticParams,
763
764
  tags: metadata.tags
764
765
  };
@@ -787,11 +788,13 @@ function assertPageRequestLoaderMode(metadata, requestLoader) {
787
788
  }
788
789
 
789
790
  class NoSchemaChain {
791
+ headFunction;
790
792
  metadata;
791
793
  requestLoaderFunction;
792
- constructor(metadata, requestLoader) {
794
+ constructor(metadata, requestLoader, head) {
793
795
  this.metadata = metadata;
794
796
  this.requestLoaderFunction = requestLoader;
797
+ this.headFunction = head;
795
798
  }
796
799
  requestLoader(requestLoader) {
797
800
  return new NoSchemaChain(this.metadata, requestLoader);
@@ -802,6 +805,9 @@ class NoSchemaChain {
802
805
  loader(loader) {
803
806
  return new LoadedNoSchema(this.metadata, loader, undefined, this.requestLoaderFunction);
804
807
  }
808
+ head(head) {
809
+ return new NoSchemaChain(this.metadata, this.requestLoaderFunction, head);
810
+ }
805
811
  page(component, ..._requestLoaderCheck) {
806
812
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
807
813
  return {
@@ -809,6 +815,7 @@ class NoSchemaChain {
809
815
  ...withMetadata(this.metadata),
810
816
  component,
811
817
  elysia: registerPlain(undefined),
818
+ head: this.headFunction,
812
819
  page: component,
813
820
  requestLoader: this.requestLoaderFunction
814
821
  };
@@ -819,6 +826,7 @@ class NoSchemaChain {
819
826
  ...withMetadata(this.metadata),
820
827
  component,
821
828
  elysia: registerLayout(undefined, undefined, undefined),
829
+ head: this.headFunction,
822
830
  layout: component,
823
831
  requestLoader: this.requestLoaderFunction
824
832
  };
@@ -849,10 +857,7 @@ class LoadedNoSchema {
849
857
  head: this.headFunction,
850
858
  loader: this.loaderFunction,
851
859
  page: component,
852
- requestLoader: this.requestLoaderFunction,
853
- useLoaderData: () => {
854
- return;
855
- }
860
+ requestLoader: this.requestLoaderFunction
856
861
  };
857
862
  }
858
863
  layout(component) {
@@ -864,22 +869,21 @@ class LoadedNoSchema {
864
869
  head: this.headFunction,
865
870
  layout: component,
866
871
  loader: this.loaderFunction,
867
- requestLoader: this.requestLoaderFunction,
868
- useLoaderData: () => {
869
- return;
870
- }
872
+ requestLoader: this.requestLoaderFunction
871
873
  };
872
874
  }
873
875
  }
874
876
 
875
877
  class QuerySchemaChain {
878
+ headFunction;
876
879
  metadata;
877
880
  querySchema;
878
881
  requestLoaderFunction;
879
- constructor(metadata, querySchema, requestLoader) {
882
+ constructor(metadata, querySchema, requestLoader, head) {
880
883
  this.metadata = metadata;
881
884
  this.querySchema = querySchema;
882
885
  this.requestLoaderFunction = requestLoader;
886
+ this.headFunction = head;
883
887
  }
884
888
  requestLoader(requestLoader) {
885
889
  return new QuerySchemaChain(this.metadata, this.querySchema, requestLoader);
@@ -890,6 +894,9 @@ class QuerySchemaChain {
890
894
  loader(loader) {
891
895
  return new LoadedQuerySchema(this.metadata, this.querySchema, loader, undefined, this.requestLoaderFunction);
892
896
  }
897
+ head(head) {
898
+ return new QuerySchemaChain(this.metadata, this.querySchema, this.requestLoaderFunction, head);
899
+ }
893
900
  page(component, ..._requestLoaderCheck) {
894
901
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
895
902
  return {
@@ -897,6 +904,7 @@ class QuerySchemaChain {
897
904
  ...withMetadata(this.metadata),
898
905
  component,
899
906
  elysia: registerQuery(this.querySchema, undefined),
907
+ head: this.headFunction,
900
908
  page: component,
901
909
  requestLoader: this.requestLoaderFunction,
902
910
  schemas: { query: this.querySchema }
@@ -908,6 +916,7 @@ class QuerySchemaChain {
908
916
  ...withMetadata(this.metadata),
909
917
  component,
910
918
  elysia: registerLayout(undefined, this.querySchema, undefined),
919
+ head: this.headFunction,
911
920
  layout: component,
912
921
  requestLoader: this.requestLoaderFunction,
913
922
  schemas: { query: this.querySchema }
@@ -942,10 +951,7 @@ class LoadedQuerySchema {
942
951
  loader: this.loaderFunction,
943
952
  page: component,
944
953
  requestLoader: this.requestLoaderFunction,
945
- schemas: { query: this.querySchema },
946
- useLoaderData: () => {
947
- return;
948
- }
954
+ schemas: { query: this.querySchema }
949
955
  };
950
956
  }
951
957
  layout(component) {
@@ -958,24 +964,23 @@ class LoadedQuerySchema {
958
964
  layout: component,
959
965
  loader: this.loaderFunction,
960
966
  requestLoader: this.requestLoaderFunction,
961
- schemas: { query: this.querySchema },
962
- useLoaderData: () => {
963
- return;
964
- }
967
+ schemas: { query: this.querySchema }
965
968
  };
966
969
  }
967
970
  }
968
971
 
969
972
  class SchemaChain {
973
+ headFunction;
970
974
  metadata;
971
975
  paramsSchema;
972
976
  querySchema;
973
977
  requestLoaderFunction;
974
- constructor(metadata, paramsSchema, querySchema, requestLoader) {
978
+ constructor(metadata, paramsSchema, querySchema, requestLoader, head) {
975
979
  this.metadata = metadata;
976
980
  this.paramsSchema = paramsSchema;
977
981
  this.querySchema = querySchema;
978
982
  this.requestLoaderFunction = requestLoader;
983
+ this.headFunction = head;
979
984
  }
980
985
  requestLoader(requestLoader) {
981
986
  return new SchemaChain(this.metadata, this.paramsSchema, this.querySchema, requestLoader);
@@ -986,6 +991,9 @@ class SchemaChain {
986
991
  loader(loader) {
987
992
  return new LoadedSchema(this.metadata, this.paramsSchema, this.querySchema, loader, undefined, this.requestLoaderFunction);
988
993
  }
994
+ head(head) {
995
+ return new SchemaChain(this.metadata, this.paramsSchema, this.querySchema, this.requestLoaderFunction, head);
996
+ }
989
997
  page(component, ..._requestLoaderCheck) {
990
998
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
991
999
  return {
@@ -993,6 +1001,7 @@ class SchemaChain {
993
1001
  ...withMetadata(this.metadata),
994
1002
  component,
995
1003
  elysia: registerSchema(this.paramsSchema, this.querySchema, undefined),
1004
+ head: this.headFunction,
996
1005
  page: component,
997
1006
  requestLoader: this.requestLoaderFunction,
998
1007
  schemas: { params: this.paramsSchema, query: this.querySchema }
@@ -1004,6 +1013,7 @@ class SchemaChain {
1004
1013
  ...withMetadata(this.metadata),
1005
1014
  component,
1006
1015
  elysia: registerLayout(this.paramsSchema, this.querySchema, undefined),
1016
+ head: this.headFunction,
1007
1017
  layout: component,
1008
1018
  requestLoader: this.requestLoaderFunction,
1009
1019
  schemas: { params: this.paramsSchema, query: this.querySchema }
@@ -1040,10 +1050,7 @@ class LoadedSchema {
1040
1050
  loader: this.loaderFunction,
1041
1051
  page: component,
1042
1052
  requestLoader: this.requestLoaderFunction,
1043
- schemas: { params: this.paramsSchema, query: this.querySchema },
1044
- useLoaderData: () => {
1045
- return;
1046
- }
1053
+ schemas: { params: this.paramsSchema, query: this.querySchema }
1047
1054
  };
1048
1055
  }
1049
1056
  layout(component) {
@@ -1056,10 +1063,7 @@ class LoadedSchema {
1056
1063
  layout: component,
1057
1064
  loader: this.loaderFunction,
1058
1065
  requestLoader: this.requestLoaderFunction,
1059
- schemas: { params: this.paramsSchema, query: this.querySchema },
1060
- useLoaderData: () => {
1061
- return;
1062
- }
1066
+ schemas: { params: this.paramsSchema, query: this.querySchema }
1063
1067
  };
1064
1068
  }
1065
1069
  }
@@ -1329,6 +1333,9 @@ class AutoInvalidateRegistry {
1329
1333
  }
1330
1334
  return [...paths];
1331
1335
  }
1336
+ tagsForPath(path) {
1337
+ return [...this.pathToTags.get(path) ?? []];
1338
+ }
1332
1339
  unregisterPath(urlPath, owner) {
1333
1340
  if (owner === undefined) {
1334
1341
  this.pathOwners.delete(urlPath);
@@ -1365,7 +1372,7 @@ var init_registry = __esm(() => {
1365
1372
  // src/server/dev/graph.ts
1366
1373
  import { randomUUID } from "crypto";
1367
1374
  import { readFileSync, statSync } from "fs";
1368
- import { dirname as dirname2, extname, resolve as resolve2 } from "path";
1375
+ import { dirname as dirname2, extname, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
1369
1376
  function normalizeModulePath(path) {
1370
1377
  return path.replaceAll("\\", "/");
1371
1378
  }
@@ -1378,7 +1385,7 @@ function resolveDevSourceImports(source, path, loader) {
1378
1385
  const isSourceExtension = [".js", ".jsx", ".ts", ".tsx"].includes(extension);
1379
1386
  const absolute = imported.path.startsWith(".") && extension && !isSourceExtension ? resolve2(dirname2(path), imported.path) : Bun.resolveSync(imported.path, dirname2(path));
1380
1387
  const resolved = normalizeModulePath(absolute);
1381
- if (!resolved.includes("/node_modules/")) {
1388
+ if (isAbsolute2(resolved) && !resolved.includes("/node_modules/")) {
1382
1389
  imports.push(resolved);
1383
1390
  }
1384
1391
  } catch {}
@@ -1524,6 +1531,19 @@ class DevGraph {
1524
1531
  const normalizedTo = normalizeModulePath(to);
1525
1532
  return this.importChain(from, normalizedTo).includes(normalizedTo);
1526
1533
  }
1534
+ sourceDependencies(from) {
1535
+ const pending = [normalizeModulePath(from)];
1536
+ const visited = new Set;
1537
+ while (pending.length > 0) {
1538
+ const path = pending.pop();
1539
+ if (path === undefined || visited.has(path)) {
1540
+ continue;
1541
+ }
1542
+ visited.add(path);
1543
+ pending.push(...this.#dependencies.get(path) ?? []);
1544
+ }
1545
+ return [...visited];
1546
+ }
1527
1547
  clearSourceErrors(path) {
1528
1548
  const modulePath = normalizeModulePath(path);
1529
1549
  for (const [message, positions] of this.#sourceErrors) {
@@ -1761,7 +1781,14 @@ function matchesPath(urlPath, path, type) {
1761
1781
  }
1762
1782
  function createRouteCache(options) {
1763
1783
  const store = new Map;
1784
+ const generations = new Map;
1764
1785
  const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
1786
+ const invalidateGenerations = (key) => {
1787
+ for (const generation of generations.get(key) ?? []) {
1788
+ generation.valid = false;
1789
+ }
1790
+ generations.delete(key);
1791
+ };
1765
1792
  const evictOldest = () => {
1766
1793
  if (options.maxSize === undefined || store.size <= options.maxSize) {
1767
1794
  return;
@@ -1772,6 +1799,7 @@ function createRouteCache(options) {
1772
1799
  }
1773
1800
  };
1774
1801
  const deleteEntry = (key) => {
1802
+ invalidateGenerations(key);
1775
1803
  const entry = store.get(key);
1776
1804
  if (entry === undefined) {
1777
1805
  return false;
@@ -1781,7 +1809,20 @@ function createRouteCache(options) {
1781
1809
  return true;
1782
1810
  };
1783
1811
  return {
1812
+ captureGeneration(key) {
1813
+ const generation = { valid: true };
1814
+ let pending = generations.get(key);
1815
+ if (pending === undefined) {
1816
+ pending = new Set;
1817
+ generations.set(key, pending);
1818
+ }
1819
+ pending.add(generation);
1820
+ return generation;
1821
+ },
1784
1822
  clear() {
1823
+ for (const key of generations.keys()) {
1824
+ invalidateGenerations(key);
1825
+ }
1785
1826
  for (const key of [...store.keys()]) {
1786
1827
  deleteEntry(key);
1787
1828
  }
@@ -1807,14 +1848,15 @@ function createRouteCache(options) {
1807
1848
  invalidatePath(path, type) {
1808
1849
  let deleted = false;
1809
1850
  const purgedPaths = [];
1810
- for (const key of [...store.keys()]) {
1851
+ for (const key of new Set([...store.keys(), ...generations.keys()])) {
1811
1852
  const urlPath = pathFromKey(key);
1812
1853
  if (urlPath === null || !matchesPath(urlPath, path, type)) {
1813
1854
  continue;
1814
1855
  }
1815
- deleteEntry(key);
1816
- deleted = true;
1817
- purgedPaths.push(urlPath);
1856
+ if (deleteEntry(key)) {
1857
+ deleted = true;
1858
+ purgedPaths.push(urlPath);
1859
+ }
1818
1860
  }
1819
1861
  return { deleted, purgedPaths: [...new Set(purgedPaths)] };
1820
1862
  },
@@ -1822,6 +1864,13 @@ function createRouteCache(options) {
1822
1864
  return store.keys();
1823
1865
  },
1824
1866
  name: options.name,
1867
+ releaseGeneration(key, generation) {
1868
+ const pending = generations.get(key);
1869
+ pending?.delete(generation);
1870
+ if (pending?.size === 0) {
1871
+ generations.delete(key);
1872
+ }
1873
+ },
1825
1874
  set(key, entry) {
1826
1875
  const previous = store.get(key);
1827
1876
  if (previous !== undefined) {
@@ -2265,7 +2314,7 @@ var init_instrumentation = __esm(() => {
2265
2314
  init_request_context();
2266
2315
  });
2267
2316
 
2268
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
2317
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
2269
2318
  function elapsedMs(startTime) {
2270
2319
  return Math.max(0, Date.now() - startTime);
2271
2320
  }
@@ -2406,7 +2455,7 @@ var init_utils = __esm(() => {
2406
2455
  _isoDate = /* @__PURE__ */ new Date;
2407
2456
  });
2408
2457
 
2409
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
2458
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
2410
2459
  function normalizeRedactPathPattern(pattern) {
2411
2460
  if (!pattern.includes("*") && !pattern.includes("."))
2412
2461
  return `**.${pattern}`;
@@ -2715,7 +2764,7 @@ var init_redact_C7FmdhwI = __esm(() => {
2715
2764
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
2716
2765
  });
2717
2766
 
2718
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
2767
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
2719
2768
  function logPluginError(name, hook, err) {
2720
2769
  console.error(`[evlog/${name}] ${hook} failed:`, err);
2721
2770
  }
@@ -2885,7 +2934,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
2885
2934
  globalConfig = getRegistry().config;
2886
2935
  });
2887
2936
 
2888
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
2937
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
2889
2938
  function pushTreeSpacer(children) {
2890
2939
  children.push(PRETTY_ERROR_TREE_SPACER);
2891
2940
  }
@@ -3186,7 +3235,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
3186
3235
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
3187
3236
  });
3188
3237
 
3189
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
3238
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
3190
3239
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
3191
3240
  const compact = partial.compact ?? (inDev && pretty);
3192
3241
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -3239,7 +3288,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
3239
3288
  };
3240
3289
  });
3241
3290
 
3242
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
3291
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
3243
3292
  function hasWideEventPublisher() {
3244
3293
  return publisher !== null;
3245
3294
  }
@@ -3255,7 +3304,7 @@ function publishWideEvent(event) {
3255
3304
  var publisher = null;
3256
3305
  var init_wideEventChannel_BUDW48oP = () => {};
3257
3306
 
3258
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
3307
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
3259
3308
  function isEvlogError(error) {
3260
3309
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
3261
3310
  }
@@ -3264,7 +3313,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
3264
3313
  evlogErrorBrand = Symbol.for("evlog.error.brand");
3265
3314
  });
3266
3315
 
3267
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
3316
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
3268
3317
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
3269
3318
  var init_error = __esm(() => {
3270
3319
  init_utils();
@@ -3373,7 +3422,7 @@ var init_error = __esm(() => {
3373
3422
  });
3374
3423
  });
3375
3424
 
3376
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
3425
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
3377
3426
  function extractSafeHeaders(headers) {
3378
3427
  const raw = {};
3379
3428
  headers.forEach((value, key) => {
@@ -3394,7 +3443,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
3394
3443
  init_utils();
3395
3444
  });
3396
3445
 
3397
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
3446
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
3398
3447
  function writePrettyStdout(text) {
3399
3448
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
3400
3449
  }
@@ -4316,12 +4365,12 @@ var init_audit_C8euLMvu = __esm(() => {
4316
4365
  initLogger(__EVLOG_CONFIG__);
4317
4366
  });
4318
4367
 
4319
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
4368
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
4320
4369
  var init_dist = __esm(() => {
4321
4370
  init_audit_C8euLMvu();
4322
4371
  });
4323
4372
 
4324
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
4373
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
4325
4374
  function shouldDeferEmitForResponse(response) {
4326
4375
  if (!response.body)
4327
4376
  return false;
@@ -4401,7 +4450,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
4401
4450
  }
4402
4451
  var init_streamResponse_OlirMA5P = () => {};
4403
4452
 
4404
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
4453
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
4405
4454
  function extractErrorStatus(error) {
4406
4455
  if (error === null || typeof error !== "object")
4407
4456
  return 500;
@@ -4411,7 +4460,7 @@ function extractErrorStatus(error) {
4411
4460
  }
4412
4461
  var init_errors_CL8dDgIi = () => {};
4413
4462
 
4414
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
4463
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
4415
4464
  function shouldLog(path, include, exclude) {
4416
4465
  if (exclude && exclude.length > 0) {
4417
4466
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -4439,7 +4488,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
4439
4488
  init_utils();
4440
4489
  });
4441
4490
 
4442
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
4491
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
4443
4492
  function resolveMiddlewarePluginRunner(options) {
4444
4493
  const global2 = getGlobalPluginRunner();
4445
4494
  const local = options.plugins;
@@ -4634,7 +4683,7 @@ var init_middleware_fam3VyaL = __esm(() => {
4634
4683
  runnerCache = /* @__PURE__ */ new WeakMap;
4635
4684
  });
4636
4685
 
4637
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
4686
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
4638
4687
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
4639
4688
  const log = parent;
4640
4689
  log.fork = (label, fn) => {
@@ -4737,7 +4786,7 @@ var init_integration_CGD18W8r = __esm(() => {
4737
4786
  init_middleware_fam3VyaL();
4738
4787
  });
4739
4788
 
4740
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
4789
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
4741
4790
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
4742
4791
  function createLoggerStorage(contextHint, id = contextHint) {
4743
4792
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -4756,7 +4805,7 @@ var init_storage = __esm(() => {
4756
4805
  init_globalRegistry_Bh3bIGwA();
4757
4806
  });
4758
4807
 
4759
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
4808
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
4760
4809
  var init_toolkit = __esm(() => {
4761
4810
  init_streamResponse_OlirMA5P();
4762
4811
  init_integration_CGD18W8r();
@@ -4936,23 +4985,10 @@ function deleteISRCache(key) {
4936
4985
  return instanceIsrCache().cache.delete(key);
4937
4986
  }
4938
4987
  function captureISRCacheGeneration(key) {
4939
- const state = instanceIsrCache();
4940
- const generation = { valid: true };
4941
- const pending = state.generations.get(key);
4942
- if (pending === undefined) {
4943
- state.generations.set(key, new Set([generation]));
4944
- } else {
4945
- pending.add(generation);
4946
- }
4947
- return generation;
4988
+ return instanceIsrCache().cache.captureGeneration(key);
4948
4989
  }
4949
4990
  function releaseISRCacheGeneration(key, generation) {
4950
- const { generations } = instanceIsrCache();
4951
- const pending = generations.get(key);
4952
- pending?.delete(generation);
4953
- if (pending?.size === 0) {
4954
- generations.delete(key);
4955
- }
4991
+ instanceIsrCache().cache.releaseGeneration(key, generation);
4956
4992
  }
4957
4993
  function setISRCacheIfGenerationUnchanged(key, entry, generation) {
4958
4994
  releaseISRCacheGeneration(key, generation);
@@ -4971,22 +5007,10 @@ var init_isr = __esm(() => {
4971
5007
  init_isr_ssg();
4972
5008
  init_registry2();
4973
5009
  instanceIsrCache = instanceSlot((instance) => {
4974
- const generations = new Map;
4975
5010
  const pendingRevalidations = new Map;
4976
- const cache = createHtmlRouteCache("isr", {
4977
- onDelete: (key) => {
4978
- const pending = generations.get(key);
4979
- if (pending === undefined) {
4980
- return;
4981
- }
4982
- for (const generation of pending) {
4983
- generation.valid = false;
4984
- }
4985
- generations.delete(key);
4986
- }
4987
- });
5011
+ const cache = createHtmlRouteCache("isr");
4988
5012
  registerCacheInvalidator(cache, instance);
4989
- return { cache, generations, pendingRevalidations };
5013
+ return { cache, pendingRevalidations };
4990
5014
  });
4991
5015
  isrCache = createStoreView(() => instanceIsrCache().cache.store);
4992
5016
  });
@@ -5605,33 +5629,26 @@ function parseChangeQuery(request) {
5605
5629
  }
5606
5630
  return { after, limit };
5607
5631
  }
5608
- function clientInvalidations(change) {
5609
- const entries = new Set;
5610
- for (const invalidation of change.invalidations) {
5611
- if (invalidation.kind === "tags") {
5612
- entries.add("/:layout");
5613
- } else {
5614
- entries.add(invalidation.type === "layout" ? `${invalidation.path}:layout` : invalidation.path);
5615
- }
5616
- }
5617
- return [...entries];
5618
- }
5619
5632
  function createSyncChangesPlugin(options) {
5620
5633
  const syncPath = options.path ?? defaultSyncPath;
5621
5634
  const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
5622
- return new Elysia6({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async ({ request, set }) => {
5635
+ return new Elysia6({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
5636
+ const { request, set } = context;
5623
5637
  set.headers["cache-control"] = "no-store";
5624
5638
  const query = parseChangeQuery(request);
5625
5639
  if ("error" in query) {
5626
5640
  return query.error;
5627
5641
  }
5628
- const page = await runtime.adapter.readChanges(query);
5642
+ const principal = await options.principal(context);
5643
+ if (principal.length === 0) {
5644
+ return new Response("Unauthorized", { status: 401 });
5645
+ }
5646
+ const cursor = await runtime.adapter.currentCursor();
5629
5647
  return {
5630
- ...page,
5631
- changes: page.changes.map((change) => ({
5632
- cursor: change.cursor,
5633
- invalidations: clientInvalidations(change)
5634
- }))
5648
+ changes: [],
5649
+ cursor,
5650
+ hasMore: false,
5651
+ reset: query.after !== undefined && query.after !== cursor
5635
5652
  };
5636
5653
  });
5637
5654
  }
@@ -6483,7 +6500,7 @@ var init_symbolicate = __esm(() => {
6483
6500
  // src/server/dev/diagnostics.ts
6484
6501
  import { randomUUID as randomUUID2 } from "crypto";
6485
6502
  import { realpathSync } from "fs";
6486
- import { isAbsolute as isAbsolute2, relative as relative4 } from "path";
6503
+ import { isAbsolute as isAbsolute3, relative as relative4 } from "path";
6487
6504
  import { fileURLToPath } from "url";
6488
6505
  function messageOf(error) {
6489
6506
  return error instanceof Error ? error.message : String(error);
@@ -6553,7 +6570,7 @@ function explicitLocation(error, entryPath) {
6553
6570
  }
6554
6571
  return {
6555
6572
  column: position.column,
6556
- file: typeof position.file === "string" && (isAbsolute2(position.file) || position.file.startsWith("file://")) ? sourceFilePath(position.file) : entryPath,
6573
+ file: typeof position.file === "string" && (isAbsolute3(position.file) || position.file.startsWith("file://")) ? sourceFilePath(position.file) : entryPath,
6557
6574
  line: position.line
6558
6575
  };
6559
6576
  }
@@ -6972,6 +6989,7 @@ function adaptDefinedPage(route, parent) {
6972
6989
  params: route.schemas?.params,
6973
6990
  parent,
6974
6991
  query: route.schemas?.query,
6992
+ remountDeps: route.remountDeps,
6975
6993
  requestLoader: route.requestLoader
6976
6994
  },
6977
6995
  component,
@@ -10202,6 +10220,87 @@ function hasShadowingDeclaration(name, ancestors) {
10202
10220
  return ancestors.some((scope) => functionScopeHasName(scope, name) || scope.type === "CatchClause" && bindingPatternHasName(scope.param, name) || blockScopeHasName(scope, name) || loopScopeHasName(scope, name) || switchScopeHasName(scope, name));
10203
10221
  }
10204
10222
 
10223
+ // src/plugin/transform-client-module.ts
10224
+ import { realpathSync as realpathSync2 } from "fs";
10225
+ import { dirname as dirname4 } from "path";
10226
+ function clientModuleKey(modulePath) {
10227
+ const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
10228
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
10229
+ }
10230
+ function collectClientModuleBindings(program) {
10231
+ const bindings = new Set;
10232
+ for (const statement of program.body) {
10233
+ if (statement.type !== "ImportDeclaration") {
10234
+ continue;
10235
+ }
10236
+ const declaration = statement;
10237
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
10238
+ continue;
10239
+ }
10240
+ for (const specifier of declaration.specifiers) {
10241
+ const imported = specifier.imported;
10242
+ const local = specifier.local;
10243
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
10244
+ bindings.add(local.name);
10245
+ }
10246
+ }
10247
+ }
10248
+ return bindings;
10249
+ }
10250
+ function dynamicImportSpecifier(loader) {
10251
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
10252
+ return null;
10253
+ }
10254
+ const body = loader.body;
10255
+ const source = body.type === "ImportExpression" ? body.source : null;
10256
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
10257
+ }
10258
+ function transformClientModules(source, filename, environment) {
10259
+ if (!source.includes("clientModule")) {
10260
+ return source;
10261
+ }
10262
+ const { program } = parseSource(source, detectLangFromPath(filename));
10263
+ const bindings = collectClientModuleBindings(program);
10264
+ if (bindings.size === 0) {
10265
+ return source;
10266
+ }
10267
+ const transformed = new MagicString(source);
10268
+ walk(program, {
10269
+ CallExpression(node, context) {
10270
+ const call = node;
10271
+ const [loader, ...rest] = call.arguments;
10272
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
10273
+ return;
10274
+ }
10275
+ const unwrapped = unwrapTSExpression(loader);
10276
+ const specifier = dynamicImportSpecifier(unwrapped);
10277
+ if (specifier === null) {
10278
+ return;
10279
+ }
10280
+ let key;
10281
+ try {
10282
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname4(filename))));
10283
+ } catch (error) {
10284
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
10285
+ }
10286
+ if (environment === "client") {
10287
+ transformed.appendLeft(loader.end, `, ${key}`);
10288
+ } else {
10289
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
10290
+ }
10291
+ }
10292
+ });
10293
+ return transformed.toString();
10294
+ }
10295
+ var FURIN_CLIENT_MODULES, SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
10296
+ var init_transform_client_module = __esm(() => {
10297
+ init_dist2();
10298
+ init_dist3();
10299
+ init_lang_detect();
10300
+ init_parser();
10301
+ FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
10302
+ });
10303
+
10205
10304
  // src/plugin/transform-isomorphic.ts
10206
10305
  function importedName(specifier) {
10207
10306
  const { imported } = specifier;
@@ -10422,11 +10521,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
10422
10521
  }
10423
10522
  });
10424
10523
  }
10425
- function transformIsomorphicFunctions(source, filename, environment) {
10524
+ function transformIsomorphicFunctions(input, filename, environment) {
10426
10525
  const lang = detectLangFromPath(filename);
10427
10526
  if (lang === "dts") {
10428
- return { code: source, map: null, transformed: false };
10527
+ return { code: input, map: null, transformed: false };
10429
10528
  }
10529
+ const source = transformClientModules(input, filename, environment);
10530
+ const clientModulesTransformed = source !== input;
10430
10531
  const { program, diagnostics } = parseSource(source, lang);
10431
10532
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
10432
10533
  if (firstError) {
@@ -10438,7 +10539,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
10438
10539
  assertNoSplitChains(source, filename, program, builders);
10439
10540
  const candidates = collectCandidates(source, filename, program, bindings);
10440
10541
  if (candidates.length === 0) {
10441
- return { code: source, map: null, transformed: false };
10542
+ return { code: source, map: null, transformed: clientModulesTransformed };
10442
10543
  }
10443
10544
  const transformed = new MagicString(source);
10444
10545
  for (const candidate of candidates) {
@@ -10459,6 +10560,7 @@ var init_transform_isomorphic = __esm(() => {
10459
10560
  init_lang_detect();
10460
10561
  init_parser();
10461
10562
  init_dead_code_elimination();
10563
+ init_transform_client_module();
10462
10564
  FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
10463
10565
  });
10464
10566
 
@@ -10568,7 +10670,7 @@ var init_error2 = __esm(() => {
10568
10670
  });
10569
10671
 
10570
10672
  // src/server/dev/rewrite-module-specifiers.ts
10571
- import { dirname as dirname4, resolve as resolve5 } from "path";
10673
+ import { dirname as dirname5, resolve as resolve5 } from "path";
10572
10674
  function sourcePosition2(source, byteOffset) {
10573
10675
  const bytes = new TextEncoder().encode(source);
10574
10676
  const prefix = new TextDecoder().decode(bytes.slice(0, byteOffset));
@@ -10603,7 +10705,7 @@ function rewriteModuleSpecifiers(input) {
10603
10705
  Reflect.set(error, "position", sourcePosition2(input.code, parseError.start));
10604
10706
  throw error;
10605
10707
  }
10606
- const directory = dirname4(input.filePath);
10708
+ const directory = dirname5(input.filePath);
10607
10709
  const output = new MagicString(input.code);
10608
10710
  walkAST(program, (node) => {
10609
10711
  const literal = relativeSpecifier(node);
@@ -10633,7 +10735,7 @@ var init_rewrite_module_specifiers = __esm(() => {
10633
10735
 
10634
10736
  // src/server/dev-page-plugin.ts
10635
10737
  import { statSync as statSync3 } from "fs";
10636
- import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve6 } from "path";
10738
+ import { dirname as dirname6, isAbsolute as isAbsolute4, resolve as resolve6 } from "path";
10637
10739
  import { fileURLToPath as fileURLToPath3 } from "url";
10638
10740
  function toImportSpecifier(filePath) {
10639
10741
  return filePath.replaceAll("\\", "/");
@@ -10693,36 +10795,26 @@ function rewriteRelativeImportsWithVersion(source, filePath, versioned) {
10693
10795
  versioned
10694
10796
  });
10695
10797
  }
10696
- function rewriteBareImports(source, transpiled, dir) {
10697
- const scanner = new Bun.Transpiler({ loader: "tsx" });
10698
- let { imports } = scanner.scan(source);
10699
- const seen = new Set;
10700
- imports = imports.filter((imp) => {
10701
- if (seen.has(imp.path)) {
10702
- return false;
10703
- }
10704
- seen.add(imp.path);
10705
- return true;
10706
- });
10707
- let result = transpiled;
10708
- for (const imp of imports) {
10709
- const spec = imp.path;
10710
- if (spec.startsWith(".") || spec.startsWith("/") || spec.startsWith("file:")) {
10711
- continue;
10798
+ function rewriteBareImports(transpiled, dir) {
10799
+ const output = new MagicString(transpiled);
10800
+ walkAST(parseSource(transpiled, "js").program, (node) => {
10801
+ if (node.type !== "ImportDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "ExportAllDeclaration" && node.type !== "ImportExpression") {
10802
+ return;
10712
10803
  }
10713
- if (SINGLETON_PATHS.has(spec)) {
10714
- continue;
10804
+ const literal = node.source;
10805
+ const specifier = literal?.value;
10806
+ if (literal?.type !== "Literal" || typeof specifier !== "string" || specifier.startsWith(".") || isAbsolute4(specifier) || specifier.startsWith("file:") || SINGLETON_PATHS.has(specifier)) {
10807
+ return;
10715
10808
  }
10716
10809
  let resolved;
10717
10810
  try {
10718
- resolved = toImportSpecifier(Bun.resolveSync(spec, dir));
10811
+ resolved = toImportSpecifier(Bun.resolveSync(specifier, dir));
10719
10812
  } catch {
10720
- continue;
10813
+ return;
10721
10814
  }
10722
- const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
10723
- result = result.replace(re, (_, g1) => `${g1}${JSON.stringify(resolved)}`);
10724
- }
10725
- return result;
10815
+ output.update(literal.start, literal.end, JSON.stringify(resolved));
10816
+ });
10817
+ return output.toString();
10726
10818
  }
10727
10819
  function getSourceLoader(filePath) {
10728
10820
  if (filePath.endsWith(".tsx")) {
@@ -10739,6 +10831,44 @@ function getSourceLoader(filePath) {
10739
10831
  }
10740
10832
  return null;
10741
10833
  }
10834
+ function restoreImportAttributes(source, transpiled, loader) {
10835
+ if (!IMPORT_ATTRIBUTES_RE.test(source)) {
10836
+ return transpiled;
10837
+ }
10838
+ const declarations = parseSource(source, loader).program.body;
10839
+ const output = new MagicString(transpiled);
10840
+ const emitted = parseSource(transpiled, "js").program.body;
10841
+ const matched = new Set;
10842
+ for (const declaration of declarations) {
10843
+ if (declaration.importKind === "type" || declaration.exportKind === "type") {
10844
+ continue;
10845
+ }
10846
+ const specifiers = declaration.specifiers;
10847
+ if (specifiers?.length && specifiers.every((specifier) => specifier.importKind === "type" || specifier.exportKind === "type")) {
10848
+ continue;
10849
+ }
10850
+ const sourcePath = declaration.source?.value;
10851
+ if (typeof sourcePath !== "string") {
10852
+ continue;
10853
+ }
10854
+ const target = emitted.find((node) => !matched.has(node) && node.type === declaration.type && node.source?.value === sourcePath);
10855
+ if (!target) {
10856
+ continue;
10857
+ }
10858
+ matched.add(target);
10859
+ const attributes = declaration.attributes;
10860
+ if (!attributes?.length || target.attributes?.length) {
10861
+ continue;
10862
+ }
10863
+ const [first] = attributes;
10864
+ const last = attributes.at(-1);
10865
+ const imported = target.source;
10866
+ if (first && last && imported) {
10867
+ output.appendLeft(imported.end, ` with { ${source.slice(first.start, last.end)} }`);
10868
+ }
10869
+ }
10870
+ return output.toString();
10871
+ }
10742
10872
  function shouldSkipWorkspaceTransform(filePath) {
10743
10873
  const normalized = filePath.replace(/\\/g, "/");
10744
10874
  return normalized.includes("/.furin/");
@@ -10746,7 +10876,7 @@ function shouldSkipWorkspaceTransform(filePath) {
10746
10876
  function recordDevImports(source, filePath) {
10747
10877
  const { imports } = resolveDevSourceImports(source, filePath, getSourceLoader(filePath) ?? "tsx");
10748
10878
  for (const path of imports) {
10749
- if (!isAbsolute3(path) || getSourceLoader(path)) {
10879
+ if (!isAbsolute4(path) || getSourceLoader(path)) {
10750
10880
  continue;
10751
10881
  }
10752
10882
  const stats = statSync3(path, { bigint: true, throwIfNoEntry: false });
@@ -10813,10 +10943,10 @@ function transformDevSource(raw, filePath, options) {
10813
10943
  const serverSource = split?.contract ?? isomorphicSource;
10814
10944
  const sourceForTranspile = options.rewriteRelativeImports ? rewriteRelativeImportsWithVersion(serverSource, filePath, true) : serverSource;
10815
10945
  const transpiler = new Bun.Transpiler({ loader });
10816
- const transpiled = transpiler.transformSync(sourceForTranspile, loader);
10946
+ const transpiled = restoreImportAttributes(sourceForTranspile, transpiler.transformSync(sourceForTranspile, loader), loader);
10817
10947
  let result = transpiled;
10818
10948
  if (options.rewriteBareImports) {
10819
- result = rewriteBareImports(serverSource, result, dirname5(filePath));
10949
+ result = rewriteBareImports(result, dirname6(filePath));
10820
10950
  }
10821
10951
  result = rewriteSingletonImports(result);
10822
10952
  return injectJsxHelperImports(result);
@@ -10925,10 +11055,13 @@ function registerDevPagePlugin() {
10925
11055
  }
10926
11056
  });
10927
11057
  }
10928
- var FURIN_SERVER_FILTER, FURIN_RENDER_FILTER, ANY_FILTER, WORKSPACE_SOURCE_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, DELETED_DEV_PAGE_CONTENTS = "export const route = undefined;", _pluginRegistered = false, pluginSourceStamps, SINGLETON_PKGS, SINGLETON_PATHS;
11058
+ var FURIN_SERVER_FILTER, FURIN_RENDER_FILTER, ANY_FILTER, WORKSPACE_SOURCE_FILTER, T_PARAM_RE, STRIP_FURIN_SERVER_RE, STRIP_T_PARAM_RE, IMPORT_ATTRIBUTES_RE, DELETED_DEV_PAGE_CONTENTS = "export const route = undefined;", _pluginRegistered = false, pluginSourceStamps, SINGLETON_PKGS, SINGLETON_PATHS;
10929
11059
  var init_dev_page_plugin = __esm(() => {
11060
+ init_dist2();
10930
11061
  init_transform_dev_page();
10931
11062
  init_transform_isomorphic();
11063
+ init_parser();
11064
+ init_ast_walk();
10932
11065
  init_dev_loader();
10933
11066
  init_error2();
10934
11067
  init_graph();
@@ -10942,6 +11075,7 @@ var init_dev_page_plugin = __esm(() => {
10942
11075
  T_PARAM_RE = /&t=(\d+)/;
10943
11076
  STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
10944
11077
  STRIP_T_PARAM_RE = /\?t=\d+$/;
11078
+ IMPORT_ATTRIBUTES_RE = /\b(?:with|assert)\s*\{/;
10945
11079
  pluginSourceStamps = new Map;
10946
11080
  SINGLETON_PKGS = [
10947
11081
  "react",
@@ -10964,11 +11098,11 @@ import {
10964
11098
  existsSync as existsSync4,
10965
11099
  readdirSync,
10966
11100
  readFileSync as readFileSync4,
10967
- realpathSync as realpathSync2,
11101
+ realpathSync as realpathSync3,
10968
11102
  statSync as statSync4,
10969
11103
  watch
10970
11104
  } from "fs";
10971
- import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute4, join as join3, relative as relative7, resolve as resolve7, sep as sep2 } from "path";
11105
+ import { dirname as dirname7, extname as extname2, isAbsolute as isAbsolute5, join as join3, relative as relative7, resolve as resolve7, sep as sep2 } from "path";
10972
11106
  import { Elysia as Elysia12 } from "elysia";
10973
11107
  function instanceKey(instance) {
10974
11108
  return `${resolve7(instance.pagesDir)}\x00${instance.prefix}`;
@@ -11239,7 +11373,7 @@ function replaceSourceWatchers(state) {
11239
11373
  const directories = new Set;
11240
11374
  for (const path of routeDependencyPaths(state.instance)) {
11241
11375
  if (!(path === pagesDir || path.startsWith(`${pagesDir}${sep2}`))) {
11242
- directories.add(dirname6(path));
11376
+ directories.add(dirname7(path));
11243
11377
  }
11244
11378
  }
11245
11379
  const watchDirectory = (directory, recursive) => {
@@ -11368,19 +11502,19 @@ function routeModuleCache() {
11368
11502
  return cache;
11369
11503
  }
11370
11504
  function findPackageRoot(sourcePath) {
11371
- const fallback = dirname6(sourcePath);
11505
+ const fallback = dirname7(sourcePath);
11372
11506
  let directory = fallback;
11373
- while (dirname6(directory) !== directory) {
11507
+ while (dirname7(directory) !== directory) {
11374
11508
  if (existsSync4(join3(directory, "package.json"))) {
11375
11509
  return directory;
11376
11510
  }
11377
- directory = dirname6(directory);
11511
+ directory = dirname7(directory);
11378
11512
  }
11379
11513
  return existsSync4(join3(directory, "package.json")) ? directory : fallback;
11380
11514
  }
11381
11515
  function isWithinDirectory(path, directory) {
11382
11516
  const relativePath = relative7(directory, path);
11383
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute4(relativePath));
11517
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute5(relativePath));
11384
11518
  }
11385
11519
  function isFurinPackageImport(specifier) {
11386
11520
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -11397,8 +11531,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
11397
11531
  continue;
11398
11532
  }
11399
11533
  try {
11400
- const resolvedImport = realpathSync2.native(Bun.resolveSync(imported.path, dirname6(dependencyPath)));
11401
- if (isAbsolute4(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative7(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
11534
+ const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname7(dependencyPath)));
11535
+ if (isAbsolute5(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative7(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
11402
11536
  resolvedImports.push(resolvedImport);
11403
11537
  }
11404
11538
  } catch {}
@@ -11406,7 +11540,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
11406
11540
  return resolvedImports;
11407
11541
  }
11408
11542
  function collectRouteModuleDependencies(sourcePath) {
11409
- const packageRoot = realpathSync2.native(findPackageRoot(sourcePath));
11543
+ const packageRoot = realpathSync3.native(findPackageRoot(sourcePath));
11410
11544
  const pending = [sourcePath];
11411
11545
  const visited = new Set;
11412
11546
  const dependencies = [];
@@ -12393,12 +12527,19 @@ function compareRouteProperties(left, right) {
12393
12527
  return leftProperty < rightProperty ? -1 : 1;
12394
12528
  }
12395
12529
  function routeMapDeclaration(entries) {
12396
- const body = entries.toSorted(compareRouteProperties).map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12530
+ const sorted = entries.toSorted(compareRouteProperties);
12531
+ const body = sorted.map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12532
+ `);
12533
+ const patterns = sorted.map((entry) => ` ${JSON.stringify(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12397
12534
  `);
12398
12535
  return `declare module "@teyik0/furin/routes" {
12399
12536
  interface RouteMap {
12400
12537
  ${body}
12401
12538
  }
12539
+
12540
+ interface RoutePatternMap {
12541
+ ${patterns}
12542
+ }
12402
12543
  }`;
12403
12544
  }
12404
12545
 
@@ -12506,7 +12647,7 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
12506
12647
  }).join(" ");
12507
12648
  const boundaryResult = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
12508
12649
  const pageComponentKey = JSON.stringify(`page:${resolvedPage}`);
12509
- const loadBody = `Promise.all([${lazyImports.join(", ")}]).then(([${importIdents.join(", ")}]) => { const __furin_page_route = __furin_page.route; let __furin_parent = root; ${layoutAssignments} return { default: { __type: "FURIN_PAGE", _route: { __type: "FURIN_ROUTE", parent: __furin_parent }, component: hotComponent(${pageComponentKey}, __furin_page_route.component) }${boundaryResult} }; })`;
12650
+ const loadBody = `Promise.all([${lazyImports.join(", ")}]).then(([${importIdents.join(", ")}]) => { const __furin_page_route = __furin_page.route; let __furin_parent = root; ${layoutAssignments} return { default: { __type: "FURIN_PAGE", _route: { __type: "FURIN_ROUTE", parent: __furin_parent, remountDeps: __furin_page_route.remountDeps }, component: hotComponent(${pageComponentKey}, __furin_page_route.component) }${boundaryResult} }; })`;
12510
12651
  const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
12511
12652
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
12512
12653
  }
@@ -12740,6 +12881,12 @@ if (__deferred && __deferred._chunks) {
12740
12881
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
12741
12882
  } as any);
12742
12883
  } else {
12884
+ // A removed active route has no match in the new development manifest.
12885
+ // Reload its document so the server can render the current 404 response.
12886
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
12887
+ window.location.reload();
12888
+ return;
12889
+ }
12743
12890
  // No match and no 404 signal \u2014 either the client bundle is out of sync
12744
12891
  // with the server (stale deploy) or the server returned something we
12745
12892
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -12816,11 +12963,14 @@ if (__deferred && __deferred._chunks) {
12816
12963
  });
12817
12964
  `;
12818
12965
  }
12819
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
12966
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot, serverSourceVersion) {
12820
12967
  if (!existsSync7(outDir)) {
12821
12968
  mkdirSync(outDir, { recursive: true });
12822
12969
  }
12823
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
12970
+ const serverVersion = serverSourceVersion === undefined ? "" : `
12971
+ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};
12972
+ `;
12973
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
12824
12974
  const hydratePath = join6(outDir, "_hydrate.tsx");
12825
12975
  const existingHydrate = existsSync7(hydratePath) ? readFileSync7(hydratePath, "utf8") : "";
12826
12976
  let changed = false;
@@ -12848,67 +12998,461 @@ var init_hydrate = __esm(() => {
12848
12998
  init_route_types();
12849
12999
  });
12850
13000
 
12851
- // src/furin.ts
12852
- init_define_route();
12853
- import { existsSync as existsSync8, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
12854
- import { basename as basename2, delimiter, dirname as dirname7, join as join7, resolve as resolve9 } from "path";
12855
- import { fileURLToPath as fileURLToPath4 } from "url";
12856
- import { staticPlugin as staticPlugin2 } from "@elysia/static";
12857
- import { Elysia as Elysia13, file as file2, NotFound, problem as problem2 } from "elysia";
13001
+ // src/plugin/hmr-dependencies.ts
13002
+ import { readFileSync as readFileSync8 } from "fs";
13003
+ import { dirname as dirname8, isAbsolute as isAbsolute6, resolve as resolve9 } from "path";
13004
+ function hmrDependencySignature(imports, filename) {
13005
+ const routePath = resolve9(filename);
13006
+ const visited = new Set;
13007
+ const hash = new Bun.CryptoHasher("sha256");
13008
+ const visit = (specifier, importer) => {
13009
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
13010
+ return true;
13011
+ }
13012
+ const path = Bun.resolveSync(specifier, dirname8(importer));
13013
+ if (path === routePath) {
13014
+ return false;
13015
+ }
13016
+ hash.update(JSON.stringify([specifier, path]));
13017
+ if (!isAbsolute6(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
13018
+ return true;
13019
+ }
13020
+ visited.add(path);
13021
+ const source = readFileSync8(path, "utf8");
13022
+ hash.update(source);
13023
+ if (SCRIPT_FILE.test(path)) {
13024
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
13025
+ for (const dependency of transpiler.scanImports(source)) {
13026
+ if (!visit(dependency.path, path)) {
13027
+ return false;
13028
+ }
13029
+ }
13030
+ }
13031
+ return true;
13032
+ };
13033
+ try {
13034
+ for (const specifier of imports) {
13035
+ if (!visit(specifier, routePath)) {
13036
+ return;
13037
+ }
13038
+ }
13039
+ return hash.digest("hex");
13040
+ } catch {}
13041
+ }
13042
+ var SCRIPT_FILE;
13043
+ var init_hmr_dependencies = __esm(() => {
13044
+ init_lang_detect();
13045
+ SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
13046
+ });
12858
13047
 
12859
- // src/server/assets/production.ts
12860
- import { existsSync } from "fs";
12861
- import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
12862
- import { staticPlugin } from "@elysia/static";
12863
- import { Elysia as Elysia2, file } from "elysia";
12864
- function resolveEmbeddedAssetPath(directory, requestPath) {
12865
- const assetPath = resolve(directory, requestPath);
12866
- const pathFromDirectory = relative(directory, assetPath);
12867
- if (pathFromDirectory === "" || pathFromDirectory === ".." || pathFromDirectory.startsWith(`..${sep}`) || isAbsolute(pathFromDirectory)) {
13048
+ // src/plugin/transform-client.ts
13049
+ function isFurinRouteModule(source) {
13050
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
13051
+ }
13052
+ function importedName2(specifier) {
13053
+ const { imported } = specifier;
13054
+ if (!imported || typeof imported !== "object") {
12868
13055
  return null;
12869
13056
  }
12870
- return assetPath;
13057
+ const node = imported;
13058
+ if (node.type === "Identifier" && typeof node.name === "string") {
13059
+ return node.name;
13060
+ }
13061
+ if (node.type === "Literal" && typeof node.value === "string") {
13062
+ return node.value;
13063
+ }
13064
+ return null;
12871
13065
  }
12872
- async function loadEmbeddedAsset(directory, requestPath) {
12873
- const assetPath = resolveEmbeddedAssetPath(directory, requestPath);
12874
- if (assetPath === null) {
13066
+ function localName2(specifier) {
13067
+ const { local } = specifier;
13068
+ if (!local || typeof local !== "object") {
12875
13069
  return null;
12876
13070
  }
12877
- const asset = Bun.file(assetPath);
12878
- return await asset.exists() ? asset : null;
13071
+ const node = local;
13072
+ return node.type === "Identifier" && typeof node.name === "string" ? node.name : null;
12879
13073
  }
12880
- function createEmbeddedAssetsPlugin(embedded) {
12881
- const { clientDir, publicDir } = embedded;
12882
- if (!publicDir) {
12883
- return new Elysia2().get("/_client/*", async ({ params, set, status }) => {
12884
- const asset = await loadEmbeddedAsset(clientDir, params["*"]);
12885
- if (asset === null) {
12886
- return status("Not Found");
12887
- }
12888
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
12889
- return asset;
12890
- });
12891
- }
12892
- return new Elysia2().get("/favicon.ico", async ({ status }) => {
12893
- const asset = await loadEmbeddedAsset(publicDir, "favicon.ico");
12894
- return asset ?? status("Not Found");
12895
- }).get("/public/*", async ({ params, set, status }) => {
12896
- const asset = await loadEmbeddedAsset(publicDir, params["*"]);
12897
- if (asset === null) {
12898
- return status("Not Found");
13074
+ function collectDefineRouteBindings(program) {
13075
+ const bindings = new Set;
13076
+ for (const statement of program.body) {
13077
+ if (statement.type !== "ImportDeclaration") {
13078
+ continue;
12899
13079
  }
12900
- set.headers["cache-control"] = "public, max-age=86400";
12901
- return asset;
12902
- }).get("/_client/*", async ({ params, set, status }) => {
12903
- const asset = await loadEmbeddedAsset(clientDir, params["*"]);
12904
- if (asset === null) {
12905
- return status("Not Found");
13080
+ const declaration = statement;
13081
+ if (declaration.importKind === "type") {
13082
+ continue;
12906
13083
  }
12907
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
12908
- return asset;
12909
- });
13084
+ const source = declaration.source.value;
13085
+ if (!isFurinRouteModule(source)) {
13086
+ continue;
13087
+ }
13088
+ for (const specifier of declaration.specifiers) {
13089
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
13090
+ continue;
13091
+ }
13092
+ const imported = importedName2(specifier);
13093
+ if (imported !== "defineRoute" && imported !== "defineRootRoute") {
13094
+ continue;
13095
+ }
13096
+ const local = localName2(specifier);
13097
+ if (local) {
13098
+ bindings.add(local);
13099
+ }
13100
+ }
13101
+ }
13102
+ return bindings;
12910
13103
  }
12911
- async function createProductionAssetsPlugin(ctx, embedded, clientDir) {
13104
+ function asAstNode2(node) {
13105
+ if (!node || typeof node !== "object" || !("type" in node)) {
13106
+ return null;
13107
+ }
13108
+ return unwrapTSExpression(node);
13109
+ }
13110
+ function chainRootIsDefineRoute(node, bindings, ancestors) {
13111
+ let current = asAstNode2(node);
13112
+ while (current) {
13113
+ if (current.type === "MemberExpression") {
13114
+ current = asAstNode2(current.object);
13115
+ continue;
13116
+ }
13117
+ if (current.type === "CallExpression") {
13118
+ current = asAstNode2(current.callee);
13119
+ continue;
13120
+ }
13121
+ return current.type === "Identifier" && typeof current.name === "string" && bindings.has(current.name) && !hasShadowingDeclaration(current.name, ancestors);
13122
+ }
13123
+ return false;
13124
+ }
13125
+ function collectBindingNames(pattern, names) {
13126
+ const node = asAstNode2(pattern);
13127
+ if (!node) {
13128
+ return;
13129
+ }
13130
+ if (node.type === "Identifier" && typeof node.name === "string") {
13131
+ names.push(node.name);
13132
+ return;
13133
+ }
13134
+ if (node.type === "AssignmentPattern") {
13135
+ collectBindingNames(node.left, names);
13136
+ return;
13137
+ }
13138
+ if (node.type === "RestElement") {
13139
+ collectBindingNames(node.argument, names);
13140
+ return;
13141
+ }
13142
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
13143
+ for (const element of node.elements) {
13144
+ collectBindingNames(element, names);
13145
+ }
13146
+ return;
13147
+ }
13148
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
13149
+ for (const property of node.properties) {
13150
+ const propertyNode = asAstNode2(property);
13151
+ collectBindingNames(propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument, names);
13152
+ }
13153
+ }
13154
+ }
13155
+ function collectDeclarationBindings(declaration, declarations) {
13156
+ if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
13157
+ const identifier = asAstNode2(declaration.id);
13158
+ if (identifier?.type === "Identifier" && typeof identifier.name === "string") {
13159
+ declarations.set(identifier.name, declaration);
13160
+ }
13161
+ return;
13162
+ }
13163
+ if (declaration?.type !== "VariableDeclaration" || !Array.isArray(declaration.declarations)) {
13164
+ return;
13165
+ }
13166
+ for (const item of declaration.declarations) {
13167
+ const names = [];
13168
+ collectBindingNames(item.id, names);
13169
+ for (const name of names) {
13170
+ declarations.set(name, item);
13171
+ }
13172
+ }
13173
+ }
13174
+ function collectModuleBindings(program) {
13175
+ const declarations = new Map;
13176
+ const imports = new Map;
13177
+ for (const statement of program.body) {
13178
+ if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
13179
+ for (const specifier of statement.specifiers) {
13180
+ const local = localName2(specifier);
13181
+ if (local) {
13182
+ imports.set(local, statement);
13183
+ }
13184
+ }
13185
+ continue;
13186
+ }
13187
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? asAstNode2(statement.declaration) : statement;
13188
+ collectDeclarationBindings(declaration, declarations);
13189
+ }
13190
+ return { declarations, imports };
13191
+ }
13192
+ function isBindingIdentifier(identifier, pattern) {
13193
+ const node = asAstNode2(pattern);
13194
+ if (!node) {
13195
+ return false;
13196
+ }
13197
+ if (node.type === "Identifier") {
13198
+ return node.start === identifier.start && node.end === identifier.end;
13199
+ }
13200
+ if (node.type === "AssignmentPattern") {
13201
+ return isBindingIdentifier(identifier, node.left);
13202
+ }
13203
+ if (node.type === "RestElement") {
13204
+ return isBindingIdentifier(identifier, node.argument);
13205
+ }
13206
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
13207
+ return node.elements.some((element) => isBindingIdentifier(identifier, element));
13208
+ }
13209
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
13210
+ return node.properties.some((property) => {
13211
+ const propertyNode = asAstNode2(property);
13212
+ return isBindingIdentifier(identifier, propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument);
13213
+ });
13214
+ }
13215
+ return false;
13216
+ }
13217
+ function nodeContains(container, node) {
13218
+ if (Array.isArray(container)) {
13219
+ return container.some((entry) => nodeContains(entry, node));
13220
+ }
13221
+ const containerNode = asAstNode2(container);
13222
+ return Boolean(containerNode && containerNode.start <= node.start && node.end <= containerNode.end);
13223
+ }
13224
+ function isTypePosition(node, ancestors) {
13225
+ return ancestors.some((ancestor) => {
13226
+ if (!ancestor.type.startsWith("TS")) {
13227
+ return false;
13228
+ }
13229
+ const runtimeChildren = TYPESCRIPT_RUNTIME_WRAPPERS.get(ancestor.type);
13230
+ if (runtimeChildren) {
13231
+ return !runtimeChildren.some((key) => nodeContains(ancestor[key], node));
13232
+ }
13233
+ return true;
13234
+ });
13235
+ }
13236
+ function isNonReferenceKey(node, parent) {
13237
+ return Boolean(parent && (parent.type === "MemberExpression" && parent.computed !== true && parent.property === node || parent.type === "Property" && parent.computed !== true && parent.shorthand !== true && parent.key === node || (parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") && parent.computed !== true && parent.key === node || (parent.type === "LabeledStatement" || parent.type === "BreakStatement" || parent.type === "ContinueStatement") && parent.label === node));
13238
+ }
13239
+ function isReferenceIdentifier(node, ancestors) {
13240
+ if (isTypePosition(node, ancestors) || isNonReferenceKey(node, ancestors.at(-1))) {
13241
+ return false;
13242
+ }
13243
+ for (const ancestor of ancestors) {
13244
+ if (ancestor.type === "VariableDeclarator" && isBindingIdentifier(node, ancestor.id) || (ancestor.type === "FunctionDeclaration" || ancestor.type === "FunctionExpression" || ancestor.type === "ArrowFunctionExpression") && (isBindingIdentifier(node, ancestor.id) || Array.isArray(ancestor.params) && ancestor.params.some((parameter) => isBindingIdentifier(node, parameter))) || ancestor.type === "ClassDeclaration" && isBindingIdentifier(node, ancestor.id) || ancestor.type === "CatchClause" && isBindingIdentifier(node, ancestor.param)) {
13245
+ return false;
13246
+ }
13247
+ }
13248
+ return true;
13249
+ }
13250
+ function walkWithAncestors(value, ancestors, visitor) {
13251
+ if (Array.isArray(value)) {
13252
+ for (const entry of value) {
13253
+ walkWithAncestors(entry, ancestors, visitor);
13254
+ }
13255
+ return;
13256
+ }
13257
+ const node = asAstNode2(value);
13258
+ if (!node) {
13259
+ return;
13260
+ }
13261
+ visitor(node, ancestors);
13262
+ const nextAncestors = [...ancestors, node];
13263
+ for (const [key, child] of Object.entries(node)) {
13264
+ if (key !== "type" && key !== "start" && key !== "end" && key !== "comments") {
13265
+ walkWithAncestors(child, nextAncestors, visitor);
13266
+ }
13267
+ }
13268
+ }
13269
+ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
13270
+ const parent = ancestors.at(-1);
13271
+ const jsxReference = child.type === "JSXIdentifier" && (parent?.type === "JSXOpeningElement" && parent.name === child && typeof child.name === "string" && child.name[0] === child.name[0]?.toUpperCase() || parent?.type === "JSXMemberExpression" && parent.object === child);
13272
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
13273
+ return;
13274
+ }
13275
+ const declaration = state.moduleBindings.declarations.get(child.name);
13276
+ if (!declaration) {
13277
+ const imported = state.moduleBindings.imports.get(child.name);
13278
+ if (trackImports && imported) {
13279
+ state.imports.add(imported);
13280
+ }
13281
+ return;
13282
+ }
13283
+ const alreadyTracked = state.dependencies.has(declaration.start);
13284
+ if (!alreadyTracked) {
13285
+ state.dependencies.set(declaration.start, declaration);
13286
+ }
13287
+ if (trackImports) {
13288
+ if (state.importTrackedDependencies.has(declaration.start)) {
13289
+ return;
13290
+ }
13291
+ state.importTrackedDependencies.add(declaration.start);
13292
+ } else if (alreadyTracked) {
13293
+ return;
13294
+ }
13295
+ collectDependencies(declaration, trackImports, state);
13296
+ }
13297
+ function collectDependencies(node, trackImports, state) {
13298
+ walkWithAncestors(node, [], (child, ancestors) => {
13299
+ collectDependencyIdentifier(child, ancestors, trackImports, state);
13300
+ if (trackImports && child.type === "ImportExpression") {
13301
+ const specifier = asAstNode2(child.source)?.value;
13302
+ if (typeof specifier === "string") {
13303
+ state.dynamicImports.add(specifier);
13304
+ }
13305
+ }
13306
+ });
13307
+ }
13308
+ function createHmrDataSignature(code, program, bindings, filename) {
13309
+ const serverStages = [];
13310
+ const dependencyState = {
13311
+ dependencies: new Map,
13312
+ dynamicImports: new Set,
13313
+ imports: new Set,
13314
+ importTrackedDependencies: new Set,
13315
+ moduleBindings: collectModuleBindings(program)
13316
+ };
13317
+ walk(program, {
13318
+ CallExpression(call, context) {
13319
+ const callee = asAstNode2(call.callee);
13320
+ if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
13321
+ return;
13322
+ }
13323
+ const property = callee.property;
13324
+ if (property.type !== "Identifier" || typeof property.name !== "string" || !SERVER_ONLY_METHODS.has(property.name) || !chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
13325
+ return;
13326
+ }
13327
+ const object = asAstNode2(callee.object);
13328
+ if (!object) {
13329
+ return;
13330
+ }
13331
+ serverStages.push({
13332
+ source: code.slice(object.end, call.end),
13333
+ start: call.start
13334
+ });
13335
+ if (Array.isArray(call.arguments)) {
13336
+ for (const argument of call.arguments) {
13337
+ const argumentNode = asAstNode2(argument);
13338
+ if (argumentNode) {
13339
+ collectDependencies(argumentNode, property.name !== "config", dependencyState);
13340
+ }
13341
+ }
13342
+ }
13343
+ }
13344
+ });
13345
+ const dataSource = [
13346
+ ...serverStages,
13347
+ ...[...dependencyState.imports].map((imported) => ({
13348
+ source: code.slice(imported.start, imported.end),
13349
+ start: imported.start
13350
+ })),
13351
+ ...[...dependencyState.dependencies.values()].map((dependency) => ({
13352
+ source: code.slice(dependency.start, dependency.end),
13353
+ start: dependency.start
13354
+ }))
13355
+ ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
13356
+ `);
13357
+ const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
13358
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
13359
+ return hash;
13360
+ }
13361
+ const dependencies = hmrDependencySignature(new Set([
13362
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
13363
+ ...dependencyState.dynamicImports
13364
+ ]), filename);
13365
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
13366
+ }
13367
+ function getHmrDataSignature(code, filename) {
13368
+ const { diagnostics, program } = parseSource(code, detectLangFromPath(filename));
13369
+ const error = diagnostics.find((diagnostic) => diagnostic.severity === "error");
13370
+ if (error) {
13371
+ throw new Error(`Failed to parse ${filename}: ${error.message}`);
13372
+ }
13373
+ return createHmrDataSignature(code, program, collectDefineRouteBindings(program), filename);
13374
+ }
13375
+ var FURIN_CLIENT_MODULES2, FURIN_SERVER_MODULES, REACT_COMPONENT_WRAPPERS, SERVER_ONLY_METHODS, TYPESCRIPT_RUNTIME_WRAPPERS;
13376
+ var init_transform_client = __esm(() => {
13377
+ init_dist3();
13378
+ init_lang_detect();
13379
+ init_parser();
13380
+ init_hmr_dependencies();
13381
+ FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
13382
+ FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
13383
+ REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
13384
+ SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
13385
+ TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
13386
+ ["TSAsExpression", ["expression"]],
13387
+ ["TSInstantiationExpression", ["expression"]],
13388
+ ["TSNonNullExpression", ["expression"]],
13389
+ ["TSParameterProperty", ["decorators", "parameter"]],
13390
+ ["TSSatisfiesExpression", ["expression"]],
13391
+ ["TSTypeAssertion", ["expression"]]
13392
+ ]);
13393
+ });
13394
+
13395
+ // src/furin.ts
13396
+ init_define_route();
13397
+ import { existsSync as existsSync8, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "fs";
13398
+ import { basename as basename2, delimiter, dirname as dirname9, join as join7, resolve as resolve10 } from "path";
13399
+ import { fileURLToPath as fileURLToPath4 } from "url";
13400
+ import { staticPlugin as staticPlugin2 } from "@elysia/static";
13401
+ import { Elysia as Elysia13, file as file2, NotFound, problem as problem2 } from "elysia";
13402
+
13403
+ // src/server/assets/production.ts
13404
+ import { existsSync } from "fs";
13405
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
13406
+ import { staticPlugin } from "@elysia/static";
13407
+ import { Elysia as Elysia2, file } from "elysia";
13408
+ function resolveEmbeddedAssetPath(directory, requestPath) {
13409
+ const assetPath = resolve(directory, requestPath);
13410
+ const pathFromDirectory = relative(directory, assetPath);
13411
+ if (pathFromDirectory === "" || pathFromDirectory === ".." || pathFromDirectory.startsWith(`..${sep}`) || isAbsolute(pathFromDirectory)) {
13412
+ return null;
13413
+ }
13414
+ return assetPath;
13415
+ }
13416
+ async function loadEmbeddedAsset(directory, requestPath) {
13417
+ const assetPath = resolveEmbeddedAssetPath(directory, requestPath);
13418
+ if (assetPath === null) {
13419
+ return null;
13420
+ }
13421
+ const asset = Bun.file(assetPath);
13422
+ return await asset.exists() ? asset : null;
13423
+ }
13424
+ function createEmbeddedAssetsPlugin(embedded) {
13425
+ const { clientDir, publicDir } = embedded;
13426
+ if (!publicDir) {
13427
+ return new Elysia2().get("/_client/*", async ({ params, set, status }) => {
13428
+ const asset = await loadEmbeddedAsset(clientDir, params["*"]);
13429
+ if (asset === null) {
13430
+ return status("Not Found");
13431
+ }
13432
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
13433
+ return asset;
13434
+ });
13435
+ }
13436
+ return new Elysia2().get("/favicon.ico", async ({ status }) => {
13437
+ const asset = await loadEmbeddedAsset(publicDir, "favicon.ico");
13438
+ return asset ?? status("Not Found");
13439
+ }).get("/public/*", async ({ params, set, status }) => {
13440
+ const asset = await loadEmbeddedAsset(publicDir, params["*"]);
13441
+ if (asset === null) {
13442
+ return status("Not Found");
13443
+ }
13444
+ set.headers["cache-control"] = "public, max-age=86400";
13445
+ return asset;
13446
+ }).get("/_client/*", async ({ params, set, status }) => {
13447
+ const asset = await loadEmbeddedAsset(clientDir, params["*"]);
13448
+ if (asset === null) {
13449
+ return status("Not Found");
13450
+ }
13451
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
13452
+ return asset;
13453
+ });
13454
+ }
13455
+ async function createProductionAssetsPlugin(ctx, embedded, clientDir) {
12912
13456
  if (ctx.serveAssets === false) {
12913
13457
  return new Elysia2;
12914
13458
  }
@@ -15044,283 +15588,400 @@ function fromCrossJSON(source, options) {
15044
15588
  depthLimit: options.depthLimit
15045
15589
  }), source);
15046
15590
  }
15047
- // src/client/router/link-utils.ts
15048
- function navigationHrefPolicy(href, currentOrigin) {
15049
- for (let index = 0;index < href.length; index += 1) {
15050
- const code = href.charCodeAt(index);
15051
- if (code <= 31 || code === 127) {
15052
- return "blocked";
15591
+
15592
+ // src/shared/sync-query.ts
15593
+ function serializeQueryHeader(identity) {
15594
+ return JSON.stringify(identity).replace(/[^\u0020-\u007e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
15595
+ }
15596
+ function mergeQuerySeeds(target, incoming) {
15597
+ for (const seed of incoming) {
15598
+ const index = target.findIndex((existing) => existing.url === seed.url);
15599
+ const previous = target[index];
15600
+ const bindings = [...seed.bindings ?? []];
15601
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
15602
+ for (const binding of previous.bindings ?? []) {
15603
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
15604
+ bindings.push(binding);
15605
+ }
15606
+ }
15607
+ }
15608
+ const merged = { ...seed, bindings };
15609
+ if (index < 0) {
15610
+ target.push(merged);
15611
+ } else {
15612
+ target[index] = merged;
15053
15613
  }
15054
15614
  }
15055
- let url;
15056
- try {
15057
- url = new URL(href, currentOrigin ?? "http://localhost");
15058
- } catch {
15059
- return "blocked";
15060
- }
15061
- if (url.protocol !== "http:" && url.protocol !== "https:") {
15062
- return "blocked";
15063
- }
15064
- if (currentOrigin === undefined) {
15065
- return href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//") ? "external" : "internal";
15066
- }
15067
- return url.origin === currentOrigin ? "internal" : "external";
15068
15615
  }
15069
- function applyLinkParams(to, params) {
15070
- if (!params) {
15071
- return to;
15072
- }
15073
- let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
15074
- const wildcard = params["*"];
15075
- if (wildcard !== undefined && url.includes("/*")) {
15076
- const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
15077
- url = url.replace("/*", () => `/${encodedWildcard}`);
15078
- }
15079
- return url;
15616
+ function queryTagsFromData(data) {
15617
+ return (data.__furinQueries ?? []).map((seed) => queryTag(seed.identity));
15080
15618
  }
15081
- function buildHref(to, search, hash, searchDefaults) {
15082
- let url = to;
15083
- if (search && Object.keys(search).length > 0) {
15084
- const params = buildSearchParams(search, searchDefaults);
15085
- const qs = params.toString();
15086
- if (qs) {
15087
- url += `?${qs}`;
15619
+ var PREFIX = "__furin.query:";
15620
+ function queryTag(identity) {
15621
+ for (const [key, value] of Object.entries(identity.scope)) {
15622
+ if (value === undefined) {
15623
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
15088
15624
  }
15089
15625
  }
15090
- if (hash) {
15091
- url += `#${hash}`;
15092
- }
15093
- return url;
15626
+ return PREFIX + JSON.stringify([
15627
+ identity.id,
15628
+ Object.entries(identity.scope).sort(([a], [b]) => {
15629
+ if (a === b) {
15630
+ return 0;
15631
+ }
15632
+ return a < b ? -1 : 1;
15633
+ })
15634
+ ]);
15094
15635
  }
15095
- function normalizeHref(href) {
15096
- const url = new URL(href, "http://localhost");
15097
- let { pathname } = url;
15098
- if (pathname !== "/") {
15099
- pathname = pathname.replace(/\/+$/g, "");
15636
+ function queryFromTag(tag) {
15637
+ if (!tag.startsWith(PREFIX)) {
15638
+ return;
15100
15639
  }
15101
- return pathname + url.search + url.hash;
15640
+ try {
15641
+ const value = JSON.parse(tag.slice(PREFIX.length));
15642
+ if (!Array.isArray(value) || value.length !== 2 || typeof value[0] !== "string" || !Array.isArray(value[1]) || value[1].some((entry) => !Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !(entry[1] === null || typeof entry[1] === "string" || typeof entry[1] === "number" || typeof entry[1] === "boolean"))) {
15643
+ return;
15644
+ }
15645
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
15646
+ } catch {}
15102
15647
  }
15103
- function toLogical(physicalPathname, basePath) {
15104
- if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
15105
- return physicalPathname.slice(basePath.length) || "/";
15106
- }
15107
- return physicalPathname;
15648
+ function queryUrl(url, origin) {
15649
+ const parsed = new URL(url, origin);
15650
+ parsed.searchParams.sort();
15651
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
15108
15652
  }
15109
15653
 
15110
- // src/client/document.tsx
15111
- import { createContext, createElement, useContext } from "react";
15112
- import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
15113
- var DocumentContext = createContext(null);
15114
- function serializeJson(value) {
15115
- return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
15116
- }
15117
- function DocumentProvider({
15118
- children,
15119
- value
15120
- }) {
15121
- return /* @__PURE__ */ jsxDEV(DocumentContext.Provider, {
15122
- value,
15123
- children
15124
- }, undefined, false, undefined, this);
15125
- }
15126
- function renderMeta(meta, index) {
15127
- if ("title" in meta) {
15128
- return /* @__PURE__ */ jsxDEV("title", {
15129
- children: meta.title
15130
- }, `title:${index}`, false, undefined, this);
15654
+ // src/client/query-store.ts
15655
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
15656
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
15657
+ var environmentGlobal = globalThis;
15658
+ function setServerQueryEnvironment(read) {
15659
+ environmentGlobal[SERVER_ENVIRONMENT] = read;
15660
+ }
15661
+ function currentQueryEnvironment() {
15662
+ return environmentGlobal[SERVER_ENVIRONMENT]?.();
15663
+ }
15664
+ class QueryStore {
15665
+ entries = new Map;
15666
+ listeners = new Set;
15667
+ revisionValue = 0;
15668
+ projections = new Set;
15669
+ session;
15670
+ epoch = 0;
15671
+ origin;
15672
+ constructor(origin) {
15673
+ this.origin = origin;
15674
+ }
15675
+ key(url) {
15676
+ const absolute = new URL(url, this.origin).href;
15677
+ return queryUrl(absolute, undefined);
15678
+ }
15679
+ entry(url) {
15680
+ const key = this.key(url);
15681
+ let entry = this.entries.get(key);
15682
+ if (!entry) {
15683
+ entry = {
15684
+ base: undefined,
15685
+ listeners: new Set,
15686
+ snapshot: { data: undefined, error: null, isFetching: false },
15687
+ stale: true,
15688
+ version: 0
15689
+ };
15690
+ this.entries.set(key, entry);
15691
+ }
15692
+ return entry;
15131
15693
  }
15132
- if ("script:ld+json" in meta) {
15133
- return /* @__PURE__ */ jsxDEV("script", {
15134
- dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
15135
- type: "application/ld+json"
15136
- }, `json-ld:${index}`, false, undefined, this);
15694
+ publish(entry) {
15695
+ let data = entry.base;
15696
+ for (const projection of this.projections) {
15697
+ const transform = projection.transforms.get(entry);
15698
+ if (transform && data !== undefined) {
15699
+ data = transform(data);
15700
+ }
15701
+ }
15702
+ entry.snapshot = { ...entry.snapshot, data };
15703
+ for (const listener of entry.listeners) {
15704
+ listener();
15705
+ }
15706
+ this.revisionValue += 1;
15707
+ for (const listener of this.listeners) {
15708
+ listener();
15709
+ }
15137
15710
  }
15138
- if ("tagName" in meta) {
15139
- const { tagName, ...attributes } = meta;
15140
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
15711
+ revision = () => this.revisionValue;
15712
+ subscribeAll = (listener) => {
15713
+ this.listeners.add(listener);
15714
+ return () => this.listeners.delete(listener);
15715
+ };
15716
+ observe(url, result, epoch, version) {
15717
+ const existing = this.entries.get(this.key(url));
15718
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
15719
+ return;
15720
+ }
15721
+ const header = result.response?.headers.get("x-furin-query");
15722
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
15723
+ if (identity) {
15724
+ this.setSession(identity.session);
15725
+ }
15726
+ const entry = this.entry(url);
15727
+ entry.base = result.data;
15728
+ entry.version += 1;
15729
+ entry.identity = identity;
15730
+ entry.local = result.local ?? result.response?.url === "";
15731
+ entry.stale = false;
15732
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
15733
+ for (const projection of this.projections) {
15734
+ if (!projection.pending) {
15735
+ projection.transforms.delete(entry);
15736
+ if (projection.transforms.size === 0) {
15737
+ this.projections.delete(projection);
15738
+ projection.onRemove?.();
15739
+ }
15740
+ }
15741
+ }
15742
+ this.publish(entry);
15743
+ if (this.entries.size > 100) {
15744
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
15745
+ if (oldest) {
15746
+ this.entries.delete(oldest[0]);
15747
+ }
15748
+ }
15141
15749
  }
15142
- return createElement("meta", { ...meta, key: `meta:${index}` });
15143
- }
15144
- function HeadContent() {
15145
- const state = useContext(DocumentContext);
15146
- if (state === null) {
15147
- throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
15750
+ setSession(session) {
15751
+ if (this.session !== undefined && this.session !== session) {
15752
+ this.epoch += 1;
15753
+ for (const projection of this.projections) {
15754
+ projection.onRemove?.();
15755
+ }
15756
+ this.projections.clear();
15757
+ for (const entry of this.entries.values()) {
15758
+ entry.base = undefined;
15759
+ entry.identity = undefined;
15760
+ entry.stale = true;
15761
+ entry.version += 1;
15762
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
15763
+ this.publish(entry);
15764
+ }
15765
+ }
15766
+ this.session = session;
15148
15767
  }
15149
- return /* @__PURE__ */ jsxDEV(Fragment, {
15150
- children: [
15151
- state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
15152
- dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
15153
- "data-furin-extension-error-filter": "",
15154
- nonce: state.nonce
15155
- }, undefined, false, undefined, this),
15156
- /* @__PURE__ */ jsxDEV("meta", {
15157
- charSet: "utf-8",
15158
- "data-furin-head": ""
15159
- }, undefined, false, undefined, this),
15160
- /* @__PURE__ */ jsxDEV("meta", {
15161
- content: "width=device-width, initial-scale=1.0",
15162
- name: "viewport"
15163
- }, undefined, false, undefined, this),
15164
- state.assets.buildId ? /* @__PURE__ */ jsxDEV("meta", {
15165
- content: state.assets.buildId,
15166
- name: "furin-build-id"
15167
- }, undefined, false, undefined, this) : null,
15168
- state.assets.staticMode ? /* @__PURE__ */ jsxDEV("meta", {
15169
- content: "static",
15170
- name: "furin-mode"
15171
- }, undefined, false, undefined, this) : null,
15172
- state.assets.faviconHref ? /* @__PURE__ */ jsxDEV("link", {
15173
- href: state.assets.faviconHref,
15174
- rel: "icon"
15175
- }, undefined, false, undefined, this) : null,
15176
- state.assets.stylesheets.map((href) => /* @__PURE__ */ jsxDEV("link", {
15177
- crossOrigin: "",
15178
- href,
15179
- rel: "stylesheet"
15180
- }, href, false, undefined, this)),
15181
- state.head?.meta?.map(renderMeta),
15182
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV("link", {
15183
- ...link
15184
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
15185
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV("script", {
15186
- ...attributes,
15187
- dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children },
15188
- nonce: state.nonce ?? attributes.nonce
15189
- }, `script:${index}`, false, undefined, this)),
15190
- state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV("style", {
15191
- dangerouslySetInnerHTML: { __html: children },
15192
- nonce: state.nonce,
15193
- type
15194
- }, `style:${index}`, false, undefined, this))
15195
- ]
15196
- }, undefined, true, undefined, this);
15197
- }
15198
- function Scripts() {
15199
- const state = useContext(DocumentContext);
15200
- if (state === null) {
15201
- throw new Error("[furin] <Scripts /> must be rendered inside the root layout.");
15768
+ generation() {
15769
+ return this.epoch;
15202
15770
  }
15203
- return /* @__PURE__ */ jsxDEV(Fragment, {
15204
- children: [
15205
- state.syncJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
15206
- dangerouslySetInnerHTML: { __html: state.syncJson },
15207
- id: "__FURIN_SYNC__",
15208
- type: "application/json"
15209
- }, undefined, false, undefined, this),
15210
- state.dataJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
15211
- dangerouslySetInnerHTML: { __html: state.dataJson },
15212
- id: "__FURIN_DATA__",
15213
- type: "application/json"
15214
- }, undefined, false, undefined, this),
15215
- state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
15216
- dangerouslySetInnerHTML: {
15217
- __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
15218
- },
15219
- "data-furin-document-state": "",
15220
- id: "__FURIN_ROUTE_FRAMES__"
15221
- }, undefined, false, undefined, this),
15222
- /* @__PURE__ */ jsxDEV("script", {
15223
- dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
15224
- "data-furin-scripts": "",
15225
- id: "__FURIN_HEAD__",
15226
- type: "application/json"
15227
- }, undefined, false, undefined, this),
15228
- state.assets.frameworkModules.map((src) => /* @__PURE__ */ jsxDEV("script", {
15229
- crossOrigin: "",
15230
- "data-furin-framework-module": "",
15231
- nonce: state.nonce,
15232
- src,
15233
- type: "module"
15234
- }, src, false, undefined, this)),
15235
- state.assets.entryModule === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
15236
- crossOrigin: "",
15237
- "data-furin-entry": "",
15238
- nonce: state.nonce,
15239
- src: state.assets.entryModule,
15240
- type: "module"
15241
- }, undefined, false, undefined, this)
15242
- ]
15243
- }, undefined, true, undefined, this);
15244
- }
15245
- function FurinDocumentFallback({ children }) {
15246
- return /* @__PURE__ */ jsxDEV("html", {
15247
- lang: "en",
15248
- children: [
15249
- /* @__PURE__ */ jsxDEV("head", {
15250
- children: /* @__PURE__ */ jsxDEV(HeadContent, {}, undefined, false, undefined, this)
15251
- }, undefined, false, undefined, this),
15252
- /* @__PURE__ */ jsxDEV("body", {
15253
- children: [
15254
- children,
15255
- /* @__PURE__ */ jsxDEV(Scripts, {}, undefined, false, undefined, this)
15256
- ]
15257
- }, undefined, true, undefined, this)
15258
- ]
15259
- }, undefined, true, undefined, this);
15260
- }
15261
-
15262
- // src/shared/await.tsx
15263
- import { Component, createContext as createContext2, createElement as createElement2, use, useMemo } from "react";
15264
- var AsyncErrorContext = createContext2(undefined);
15265
- function useAsyncError() {
15266
- return use(AsyncErrorContext);
15267
- }
15268
- function useAsyncValue() {
15269
- const ctx = use(AwaitValueContext);
15270
- if (!ctx) {
15271
- throw new Error("useAsyncValue must be used inside <Await> children");
15771
+ version(url) {
15772
+ return this.entry(url).version;
15272
15773
  }
15273
- return use(ctx.promise);
15274
- }
15275
- var AwaitValueContext = createContext2(undefined);
15276
- function isAbortError(error) {
15277
- return error instanceof Error && error.name === "AbortError";
15278
- }
15279
- function silenceAbortError(promise) {
15280
- return promise.catch((error) => {
15281
- if (isAbortError(error)) {
15282
- return new Promise(() => {});
15774
+ snapshot(url) {
15775
+ return this.entry(url).snapshot;
15776
+ }
15777
+ subscribe(url, listener) {
15778
+ const entry = this.entry(url);
15779
+ entry.listeners.add(listener);
15780
+ return () => entry.listeners.delete(listener);
15781
+ }
15782
+ bind(url, load, client) {
15783
+ const entry = this.entry(url);
15784
+ if (client && entry.client && client !== entry.client) {
15785
+ entry.base = undefined;
15786
+ entry.identity = undefined;
15787
+ entry.stale = true;
15788
+ entry.version += 1;
15789
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
15790
+ for (const projection of this.projections) {
15791
+ projection.transforms.delete(entry);
15792
+ }
15283
15793
  }
15284
- throw error;
15285
- });
15286
- }
15287
-
15288
- class AsyncErrorBoundary extends Component {
15289
- constructor(props) {
15290
- super(props);
15291
- this.state = { error: undefined, hasError: false, resolve: props.resolve };
15794
+ entry.client = client ?? entry.client;
15795
+ entry.load = load;
15292
15796
  }
15293
- static getDerivedStateFromProps(props, state) {
15294
- if (props.resolve !== state.resolve) {
15295
- return { error: undefined, hasError: false, resolve: props.resolve };
15797
+ pending(entry) {
15798
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
15799
+ }
15800
+ fetch(url) {
15801
+ const entry = this.entry(url);
15802
+ if (entry.promise) {
15803
+ return entry.promise;
15296
15804
  }
15297
- return null;
15805
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
15806
+ return Promise.resolve();
15807
+ }
15808
+ const { version } = entry;
15809
+ const { epoch } = this;
15810
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
15811
+ this.publish(entry);
15812
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
15813
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
15814
+ return;
15815
+ }
15816
+ if (result.error === null) {
15817
+ this.observe(url, result, epoch);
15818
+ } else {
15819
+ entry.snapshot = { ...entry.snapshot, error: result.error };
15820
+ }
15821
+ }).catch((error) => {
15822
+ if (epoch === this.epoch && version === entry.version) {
15823
+ entry.snapshot = { ...entry.snapshot, error };
15824
+ }
15825
+ }).finally(() => {
15826
+ entry.promise = undefined;
15827
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
15828
+ this.publish(entry);
15829
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
15830
+ this.fetch(url);
15831
+ }
15832
+ });
15833
+ return entry.promise;
15298
15834
  }
15299
- static getDerivedStateFromError(error) {
15300
- return { error, hasError: true };
15835
+ invalidate(identities) {
15836
+ const tags = new Set(identities.map(queryTag));
15837
+ let affected = false;
15838
+ for (const [url, entry] of this.entries) {
15839
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
15840
+ affected = true;
15841
+ this.invalidateEntry(url, entry);
15842
+ }
15843
+ }
15844
+ return affected;
15301
15845
  }
15302
- render() {
15303
- const { hasError, error } = this.state;
15304
- const { children, errorElement } = this.props;
15305
- if (hasError) {
15306
- if (errorElement === undefined) {
15307
- throw error;
15846
+ invalidateEntry(url, entry) {
15847
+ entry.stale = true;
15848
+ entry.version += 1;
15849
+ if (entry.listeners.size > 0) {
15850
+ this.fetch(url);
15851
+ }
15852
+ }
15853
+ invalidateAll() {
15854
+ for (const [url, entry] of this.entries) {
15855
+ this.invalidateEntry(url, entry);
15856
+ }
15857
+ }
15858
+ begin() {
15859
+ return { pending: true, transforms: new Map };
15860
+ }
15861
+ update(projection, url, transform) {
15862
+ const entry = this.entries.get(this.key(url));
15863
+ if (!entry || entry.base === undefined) {
15864
+ return;
15865
+ }
15866
+ const previous = projection.transforms.get(entry);
15867
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
15868
+ entry.version += 1;
15869
+ this.projections.add(projection);
15870
+ this.publish(entry);
15871
+ }
15872
+ finish(projection, outcome) {
15873
+ projection.pending = false;
15874
+ const entries = [...projection.transforms.keys()];
15875
+ if (outcome === "error") {
15876
+ this.projections.delete(projection);
15877
+ projection.onRemove?.();
15878
+ }
15879
+ for (const entry of entries) {
15880
+ this.publish(entry);
15881
+ if (outcome !== "error") {
15882
+ entry.stale = true;
15883
+ }
15884
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
15885
+ if (url && entry.stale) {
15886
+ this.fetch(url);
15308
15887
  }
15309
- return createElement2(AsyncErrorContext.Provider, { value: error }, errorElement);
15310
15888
  }
15311
- return children;
15889
+ }
15890
+ dehydrate() {
15891
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
15892
+ }
15893
+ seedUrl(seed, localOrigin) {
15894
+ const original = new URL(seed.url, this.origin);
15895
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
15896
+ }
15897
+ captureHydration() {
15898
+ const { epoch } = this;
15899
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
15900
+ return (seeds, localOrigin) => {
15901
+ if (epoch === this.epoch) {
15902
+ this.hydrate(seeds.filter((seed) => {
15903
+ const url = this.seedUrl(seed, localOrigin);
15904
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
15905
+ }), localOrigin);
15906
+ }
15907
+ };
15908
+ }
15909
+ hydrate(seeds, localOrigin) {
15910
+ for (const seed of seeds) {
15911
+ const url = this.seedUrl(seed, localOrigin);
15912
+ this.observe(url, {
15913
+ data: seed.data,
15914
+ error: null,
15915
+ identity: seed.identity,
15916
+ local: seed.local ?? false
15917
+ }, this.epoch);
15918
+ }
15312
15919
  }
15313
15920
  }
15314
- function Await({ resolve, errorElement, children }) {
15315
- const guardedResolve = useMemo(() => silenceAbortError(resolve), [resolve]);
15316
- return createElement2(AsyncErrorBoundary, { errorElement, resolve: guardedResolve }, createElement2(AwaitInner, { children, resolve: guardedResolve }));
15921
+ // src/client/router/link-utils.ts
15922
+ function navigationHrefPolicy(href, currentOrigin) {
15923
+ for (let index = 0;index < href.length; index += 1) {
15924
+ const code = href.charCodeAt(index);
15925
+ if (code <= 31 || code === 127) {
15926
+ return "blocked";
15927
+ }
15928
+ }
15929
+ let url;
15930
+ try {
15931
+ url = new URL(href, currentOrigin ?? "http://localhost");
15932
+ } catch {
15933
+ return "blocked";
15934
+ }
15935
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
15936
+ return "blocked";
15937
+ }
15938
+ if (currentOrigin === undefined) {
15939
+ return href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//") ? "external" : "internal";
15940
+ }
15941
+ return url.origin === currentOrigin ? "internal" : "external";
15317
15942
  }
15318
- function AwaitInner({ resolve, children }) {
15319
- const value = use(resolve);
15320
- return createElement2(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
15943
+ function applyLinkParams(to, params) {
15944
+ if (!params) {
15945
+ return to;
15946
+ }
15947
+ let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
15948
+ const wildcard = params["*"];
15949
+ if (wildcard !== undefined && url.includes("/*")) {
15950
+ const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
15951
+ url = url.replace("/*", () => `/${encodedWildcard}`);
15952
+ }
15953
+ return url;
15954
+ }
15955
+ function buildHref(to, search, hash, searchDefaults) {
15956
+ let url = to;
15957
+ if (search && Object.keys(search).length > 0) {
15958
+ const params = buildSearchParams(search, searchDefaults);
15959
+ const qs = params.toString();
15960
+ if (qs) {
15961
+ url += `?${qs}`;
15962
+ }
15963
+ }
15964
+ if (hash) {
15965
+ url += `#${hash}`;
15966
+ }
15967
+ return url;
15968
+ }
15969
+ function normalizeHref(href) {
15970
+ const url = new URL(href, "http://localhost");
15971
+ let { pathname } = url;
15972
+ if (pathname !== "/") {
15973
+ pathname = pathname.replace(/\/+$/g, "");
15974
+ }
15975
+ return pathname + url.search + url.hash;
15976
+ }
15977
+ function toLogical(physicalPathname, basePath) {
15978
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
15979
+ return physicalPathname.slice(basePath.length) || "/";
15980
+ }
15981
+ return physicalPathname;
15321
15982
  }
15322
15983
 
15323
- // src/client.ts
15984
+ // src/shared/defer.ts
15324
15985
  var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
15325
15986
  function defer(data) {
15326
15987
  if (Object.hasOwn(data, DEFERRED_BRAND)) {
@@ -15332,6 +15993,96 @@ function isDeferred(value) {
15332
15993
  return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
15333
15994
  }
15334
15995
 
15996
+ // src/shared/query-bindings.ts
15997
+ function isContainer(value) {
15998
+ if (!value || typeof value !== "object") {
15999
+ return false;
16000
+ }
16001
+ const prototype = Object.getPrototypeOf(value);
16002
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
16003
+ }
16004
+ function bindQueryData(data, seeds) {
16005
+ return seeds.map((seed) => {
16006
+ const sources = new WeakMap;
16007
+ const index = (value, path) => {
16008
+ if (!isContainer(value) || sources.has(value)) {
16009
+ return;
16010
+ }
16011
+ sources.set(value, path);
16012
+ if (!Array.isArray(value)) {
16013
+ for (const [key, child] of Object.entries(value)) {
16014
+ index(child, [...path, key]);
16015
+ }
16016
+ }
16017
+ };
16018
+ index(seed.data, []);
16019
+ const bindings = [];
16020
+ const visiting = new WeakSet;
16021
+ const visit = (value, target) => {
16022
+ if (!isContainer(value) || visiting.has(value)) {
16023
+ return;
16024
+ }
16025
+ const source = sources.get(value);
16026
+ if (source) {
16027
+ bindings.push({ source, target });
16028
+ return;
16029
+ }
16030
+ visiting.add(value);
16031
+ for (const [key, child] of Object.entries(value)) {
16032
+ visit(child, [...target, key]);
16033
+ }
16034
+ visiting.delete(value);
16035
+ };
16036
+ visit(data, []);
16037
+ return { ...seed, bindings };
16038
+ });
16039
+ }
16040
+ function replace(value, path, next) {
16041
+ const [key, ...rest] = path;
16042
+ if (key === undefined) {
16043
+ return next;
16044
+ }
16045
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
16046
+ return value;
16047
+ }
16048
+ const child = replace(value[key], rest, next);
16049
+ if (child === value[key]) {
16050
+ return value;
16051
+ }
16052
+ const copy = Array.isArray(value) ? [...value] : { ...value };
16053
+ Object.defineProperty(copy, key, {
16054
+ configurable: true,
16055
+ enumerable: true,
16056
+ value: child,
16057
+ writable: true
16058
+ });
16059
+ return copy;
16060
+ }
16061
+ function isDeferredTarget(data, target) {
16062
+ const [key] = target;
16063
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
16064
+ }
16065
+ function projectQueryData(data, seeds, read) {
16066
+ let projected = data;
16067
+ for (const seed of seeds) {
16068
+ const snapshot = read(seed);
16069
+ if (snapshot === undefined) {
16070
+ continue;
16071
+ }
16072
+ for (const binding of seed.bindings ?? []) {
16073
+ if (isDeferredTarget(data, binding.target)) {
16074
+ continue;
16075
+ }
16076
+ let value = snapshot;
16077
+ for (const key of binding.source) {
16078
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
16079
+ }
16080
+ projected = replace(projected, binding.target, value);
16081
+ }
16082
+ }
16083
+ return projected;
16084
+ }
16085
+
15335
16086
  // src/server/render/mixed-cache.ts
15336
16087
  init_registry();
15337
16088
 
@@ -15352,6 +16103,9 @@ init_registry2();
15352
16103
  init_context_logger();
15353
16104
  init_instance();
15354
16105
  init_source_version();
16106
+ function capturedQueryTags() {
16107
+ return currentQueryEnvironment()?.store.dehydrate().map((seed) => queryTag(seed.identity)) ?? [];
16108
+ }
15355
16109
  var mixedCacheKey = Symbol("furin-mixed-loader-cache");
15356
16110
  function cachePathWithSearch(key) {
15357
16111
  const separator = key.indexOf("|");
@@ -15404,7 +16158,11 @@ async function readCachedSegment(entry, revalidate, parentData) {
15404
16158
  return;
15405
16159
  }
15406
16160
  }
15407
- return fromCrossJSON(snapshot.data, {});
16161
+ const environment = currentQueryEnvironment();
16162
+ environment?.store.hydrate(snapshot.queries ?? []);
16163
+ environment?.onRead();
16164
+ const data = fromCrossJSON(snapshot.data, {});
16165
+ return projectQueryData(data, snapshot.queries ?? [], (seed) => seed.data);
15408
16166
  } catch {
15409
16167
  getLogger().warn("Mixed loader cache entry is invalid; loading fresh data");
15410
16168
  }
@@ -15417,7 +16175,8 @@ async function createSegmentSnapshot(data, parentData, parentFieldsRead) {
15417
16175
  })));
15418
16176
  return JSON.stringify({
15419
16177
  data: await toCrossJSONAsync(data),
15420
- dependencies
16178
+ dependencies,
16179
+ queries: bindQueryData(data, currentQueryEnvironment()?.store.dehydrate() ?? []).filter((seed) => (seed.bindings?.length ?? 0) > 0)
15421
16180
  });
15422
16181
  }
15423
16182
  async function acquireSharedSegment(shared, identity) {
@@ -15444,6 +16203,10 @@ async function readSharedSegment(shared, identity, revalidate, parentData) {
15444
16203
  }
15445
16204
  }
15446
16205
  async function commitSharedSegment(shared, identity, lease, cached, revalidate) {
16206
+ const identityTags = new Set(identity.tags);
16207
+ if (capturedQueryTags().some((tag) => !identityTags.has(tag))) {
16208
+ return;
16209
+ }
15447
16210
  try {
15448
16211
  await shared.commit({
15449
16212
  entry: {
@@ -15471,6 +16234,7 @@ function storeLocalSegment(state, generation, key, path, tags, cached) {
15471
16234
  }
15472
16235
  async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, parentFieldsRead, run) {
15473
16236
  const instance = currentInstance();
16237
+ const declaredTags = route.tags ?? [];
15474
16238
  const mode = segment.mode ?? route.mode;
15475
16239
  const revalidate = mode === "isr" ? segment.revalidate ?? 60 : Number.POSITIVE_INFINITY;
15476
16240
  const requestUrl = new URL(ctx.request.url);
@@ -15491,7 +16255,12 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
15491
16255
  mode: mode === "isr" ? "isr" : "ssg",
15492
16256
  path,
15493
16257
  scope: instance.prefix,
15494
- tags: route.tags ?? []
16258
+ tags: [
16259
+ ...new Set([
16260
+ ...declaredTags,
16261
+ ...getAutoInvalidateRegistry().tagsForPath(`${path}${requestUrl.search}`)
16262
+ ])
16263
+ ]
15495
16264
  };
15496
16265
  const stored = shared === undefined ? undefined : await readSharedSegment(shared, identity, revalidate, parentData);
15497
16266
  if (stored !== undefined) {
@@ -15507,7 +16276,7 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
15507
16276
  cachedAt: Date.now(),
15508
16277
  payload: await createSegmentSnapshot(data, parentData, parentFieldsRead)
15509
16278
  };
15510
- storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, route.tags, cached);
16279
+ storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, [...declaredTags, ...capturedQueryTags()], cached);
15511
16280
  if (shared !== undefined && lease !== null) {
15512
16281
  await commitSharedSegment(shared, identity, lease, cached, revalidate);
15513
16282
  }
@@ -15832,6 +16601,70 @@ function isNotFoundError(err) {
15832
16601
  init_context_logger();
15833
16602
  init_instrumentation();
15834
16603
  init_patterns();
16604
+
16605
+ // src/server/sync/query-context.ts
16606
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
16607
+ init_registry();
16608
+ init_instance();
16609
+ var QUERY_CONTEXT = Symbol.for("furin.query.server-context.v1");
16610
+ var contextGlobal = globalThis;
16611
+ var contexts = contextGlobal[QUERY_CONTEXT] ??= new AsyncLocalStorage6;
16612
+ setServerQueryEnvironment(() => contexts.getStore());
16613
+ var trackedQueryPaths = instanceSlot(() => new Set);
16614
+ var deferredQueries = new WeakMap;
16615
+ function deferredQuerySeeds(promise) {
16616
+ return deferredQueries.get(promise);
16617
+ }
16618
+ function captureQueryReads(ctx, run, owner) {
16619
+ const { origin } = new URL(ctx.request.url);
16620
+ const store = new QueryStore(origin);
16621
+ const registry = getAutoInvalidateRegistry();
16622
+ const trackedPaths = trackedQueryPaths();
16623
+ const requestUrl = new URL(ctx.request.url);
16624
+ const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
16625
+ const onRead = () => {
16626
+ const seeds = store.dehydrate();
16627
+ registry.registerLoaderTags(path, seeds.map((seed) => queryTag(seed.identity)), owner ?? "eden-queries");
16628
+ trackedPaths.delete(path);
16629
+ if (seeds.length > 0) {
16630
+ trackedPaths.add(path);
16631
+ }
16632
+ if (trackedPaths.size > 1000) {
16633
+ const oldest = trackedPaths.values().next().value;
16634
+ if (oldest !== undefined) {
16635
+ trackedPaths.delete(oldest);
16636
+ registry.unregisterPath(oldest, "eden-queries");
16637
+ registry.unregisterPath(oldest, "eden-request-queries");
16638
+ }
16639
+ }
16640
+ };
16641
+ return contexts.run({ origin, store, onRead }, async () => {
16642
+ const result = { ...await run() };
16643
+ const seeds = store.dehydrate();
16644
+ if (result.type === "data" && seeds.length > 0) {
16645
+ const captured = [...result.syncData.__furinQueries ?? []];
16646
+ mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
16647
+ result.syncData = { ...result.syncData, __furinQueries: captured };
16648
+ }
16649
+ if (result.type === "data" && result.deferredPromises) {
16650
+ for (const [key, promise] of Object.entries(result.deferredPromises)) {
16651
+ promise.then((value) => {
16652
+ const completed = store.dehydrate();
16653
+ if (completed.length > 0) {
16654
+ const captured = deferredQueries.get(promise) ?? [];
16655
+ mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
16656
+ deferredQueries.set(promise, captured);
16657
+ }
16658
+ }).catch(() => {
16659
+ return;
16660
+ });
16661
+ }
16662
+ }
16663
+ return result;
16664
+ });
16665
+ }
16666
+
16667
+ // src/server/render/loaders.ts
15835
16668
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
15836
16669
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
15837
16670
  var ROUTE_CTX_RESERVED_KEYS = new Set([
@@ -15854,6 +16687,12 @@ function assertPublicLoaderKey(key) {
15854
16687
  throw new Error(`[furin] Loader data key "${key}" is reserved: it is overwritten by the route context when component props are assembled. Rename this field to avoid conflicts.`);
15855
16688
  }
15856
16689
  }
16690
+ function assertRequestLoaderKey(key, ctx) {
16691
+ assertPublicLoaderKey(key);
16692
+ if (key === "log" || Object.hasOwn(ctx, key) || key in ctx && !Object.hasOwn(Object.prototype, key)) {
16693
+ throw new Error(`[furin] requestLoader data key "${key}" is reserved: it is overwritten by the SSR loader context. Rename this field to avoid conflicts.`);
16694
+ }
16695
+ }
15857
16696
  function isHttpRedirect(res) {
15858
16697
  return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
15859
16698
  }
@@ -15868,7 +16707,7 @@ async function readResponseMessage(res) {
15868
16707
  return res.statusText;
15869
16708
  }
15870
16709
  }
15871
- function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
16710
+ function createLoaderCtx(ctx, accumulatedParentPromise, inheritedRequestFields, onParentFieldAccess) {
15872
16711
  const cache = new Map;
15873
16712
  return new Proxy(ctx, {
15874
16713
  get(target, prop) {
@@ -15881,6 +16720,9 @@ function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
15881
16720
  if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
15882
16721
  return target[prop];
15883
16722
  }
16723
+ if (inheritedRequestFields && Object.hasOwn(inheritedRequestFields, prop)) {
16724
+ return inheritedRequestFields[prop];
16725
+ }
15884
16726
  onParentFieldAccess?.(prop);
15885
16727
  let entry = cache.get(prop);
15886
16728
  if (!entry) {
@@ -15993,6 +16835,8 @@ function runRequestLoaderFields(route, ctx) {
15993
16835
  if (declarations?.length !== route.routeChain.length) {
15994
16836
  throw new Error(`[furin] Missing per-loader request field metadata for ${route.pattern}.`);
15995
16837
  }
16838
+ const declaredKeys = declarations.map((keys) => new Set(keys));
16839
+ const requestKeys = new Set(route.requestKeys);
15996
16840
  const requestContext = createRequestLoaderContext(ctx);
15997
16841
  const results = loaderIndexes.map((index) => {
15998
16842
  const loader = route.routeChain[index]?.requestLoader;
@@ -16003,8 +16847,8 @@ function runRequestLoaderFields(route, ctx) {
16003
16847
  const result = observeLoader(() => invocation, `request:${index}`, ctx.path).then((value) => {
16004
16848
  const data = value;
16005
16849
  for (const key of Object.keys(data)) {
16006
- assertPublicLoaderKey(key);
16007
- if (!declarations[index]?.includes(key)) {
16850
+ assertRequestLoaderKey(key, ctx);
16851
+ if (!declaredKeys[index]?.has(key)) {
16008
16852
  throw new Error(`[furin] requestLoader in ${route.pattern} returned undeclared field "${key}".`);
16009
16853
  }
16010
16854
  }
@@ -16013,27 +16857,36 @@ function runRequestLoaderFields(route, ctx) {
16013
16857
  result.catch(() => {});
16014
16858
  return { index, result };
16015
16859
  });
16016
- const fields = {};
16860
+ let fields = {};
16861
+ const fieldsByLoader = route.routeChain.map((_, boundaryIndex) => {
16862
+ fields = { ...fields };
16863
+ for (const key of declarations[boundaryIndex] ?? []) {
16864
+ if (!requestKeys.has(key)) {
16865
+ continue;
16866
+ }
16867
+ const candidates = results.filter(({ index }) => index <= boundaryIndex && declaredKeys[index]?.has(key));
16868
+ fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
16869
+ for (let index = values.length - 1;index >= 0; index -= 1) {
16870
+ const data = values[index];
16871
+ if (data && Object.hasOwn(data, key)) {
16872
+ return data[key];
16873
+ }
16874
+ }
16875
+ });
16876
+ fields[key].catch(() => {});
16877
+ }
16878
+ return fields;
16879
+ });
16017
16880
  for (const key of route.requestKeys) {
16018
- const candidates = results.filter(({ index }) => declarations[index]?.includes(key));
16019
- if (candidates.length === 0) {
16881
+ if (!Object.hasOwn(fields, key)) {
16020
16882
  throw new Error(`[furin] No requestLoader declares field "${key}" in ${route.pattern}.`);
16021
16883
  }
16022
- fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
16023
- for (let index = values.length - 1;index >= 0; index -= 1) {
16024
- const data = values[index];
16025
- if (data && Object.hasOwn(data, key)) {
16026
- return data[key];
16027
- }
16028
- }
16029
- });
16030
- fields[key].catch(() => {});
16031
16884
  }
16032
16885
  const noFieldCompletion = Promise.all(results.filter(({ index }) => declarations[index]?.length === 0).map(({ result }) => result)).then(() => {
16033
16886
  return;
16034
16887
  });
16035
16888
  noFieldCompletion.catch(() => {});
16036
- return { fields, noFieldCompletion };
16889
+ return { fields, fieldsByLoader, noFieldCompletion };
16037
16890
  }
16038
16891
  function requestFieldPromises(route, fields, syncData, publicDeferred) {
16039
16892
  for (const key of Object.keys(fields)) {
@@ -16043,19 +16896,21 @@ function requestFieldPromises(route, fields, syncData, publicDeferred) {
16043
16896
  }
16044
16897
  return fields;
16045
16898
  }
16046
- async function withRequestLoaderData(route, ctx, publicResult) {
16047
- const requestFields = runRequestLoaderFields(route, ctx);
16048
- if (requestFields === undefined) {
16049
- throw new Error("[furin] internal invariant: requestLoader data requested for a route without requestLoader");
16050
- }
16051
- await requestFields.noFieldCompletion;
16052
- return {
16053
- ...publicResult,
16054
- deferredPromises: {
16055
- ...publicResult.deferredPromises ?? {},
16056
- ...requestFieldPromises(route, requestFields.fields, publicResult.syncData, publicResult.deferredPromises)
16899
+ function withRequestLoaderData(route, ctx, publicResult) {
16900
+ return captureQueryReads(ctx, async () => {
16901
+ const requestFields = runRequestLoaderFields(route, ctx);
16902
+ if (requestFields === undefined) {
16903
+ throw new Error("[furin] internal invariant: requestLoader data requested for a route without requestLoader");
16057
16904
  }
16058
- };
16905
+ await requestFields.noFieldCompletion;
16906
+ return {
16907
+ ...publicResult,
16908
+ deferredPromises: {
16909
+ ...publicResult.deferredPromises ?? {},
16910
+ ...requestFieldPromises(route, requestFields.fields, publicResult.syncData, publicResult.deferredPromises)
16911
+ }
16912
+ };
16913
+ }, "eden-request-queries");
16059
16914
  }
16060
16915
  function mergeLoaderResults(results) {
16061
16916
  const allSync = {};
@@ -16128,6 +16983,15 @@ async function normalizeLoaderError(err, headers) {
16128
16983
  const message = body || "Something went wrong";
16129
16984
  return { error: err, headers, message, status, type: "error" };
16130
16985
  }
16986
+ if (err instanceof Error && "status" in err && typeof err.status === "number" && err.status >= 400 && err.status <= 599 && "value" in err && err.value !== null && typeof err.value === "object" && "status" in err.value && err.value.status === err.status && "type" in err.value && typeof err.value.type === "string") {
16987
+ let message = "Something went wrong";
16988
+ if ("detail" in err.value && typeof err.value.detail === "string") {
16989
+ message = err.value.detail;
16990
+ } else if ("title" in err.value && typeof err.value.title === "string") {
16991
+ message = err.value.title;
16992
+ }
16993
+ return { error: err, headers, message, status: err.status, type: "error" };
16994
+ }
16131
16995
  if (isFurinRscRenderError(err)) {
16132
16996
  getLogger().error(err);
16133
16997
  return {
@@ -16156,10 +17020,10 @@ function mergeParentData(parent, own, path) {
16156
17020
  }
16157
17021
  return { ...parent, ...own };
16158
17022
  }
16159
- function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, ctxRecord, publicCtxRecord, mixed) {
17023
+ function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, inheritedRequestFields, ctxRecord, publicCtxRecord, mixed) {
16160
17024
  const publicSegment = mixed && (segment.mode ?? route.mode) !== "ssr";
16161
17025
  const parentFieldsRead = new Set;
16162
- const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
17026
+ const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? undefined : inheritedRequestFields, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
16163
17027
  return observeLoader(() => {
16164
17028
  const run = async () => await segment.loader?.(loaderCtx) ?? {};
16165
17029
  return publicSegment ? cacheMixedPublicLoader(route, ctx, segment, index, publicParent, parentFieldsRead, run) : run();
@@ -16174,13 +17038,13 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
16174
17038
  let accumulatedParentPromise = Promise.resolve({});
16175
17039
  let publicParentPromise = Promise.resolve({});
16176
17040
  let loaderIndex = 0;
16177
- for (const r of route.routeChain) {
17041
+ for (const [routeIndex, r] of route.routeChain.entries()) {
16178
17042
  const parentAccum = accumulatedParentPromise;
16179
17043
  const publicParent = publicParentPromise;
16180
17044
  const privateSegment = mixed && (r.mode ?? route.mode) === "ssr";
16181
17045
  if (r.loader) {
16182
17046
  const index = loaderIndex;
16183
- const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, ctxRecord, publicCtxRecord, mixed);
17047
+ const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, requestFields?.fieldsByLoader[routeIndex - 1], ctxRecord, publicCtxRecord, mixed);
16184
17048
  loaderIndex += 1;
16185
17049
  loaderMap.set(r, loaderPromise);
16186
17050
  accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => mergeParentData(acc, own, ctx.path));
@@ -16194,7 +17058,7 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
16194
17058
  }
16195
17059
  }
16196
17060
  }
16197
- const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
17061
+ const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, requestFields?.fields, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
16198
17062
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
16199
17063
  await requestFields?.noFieldCompletion;
16200
17064
  const headers = {};
@@ -16237,10 +17101,10 @@ function createPublicLoaderContext(ctx) {
16237
17101
  return publicContext;
16238
17102
  }
16239
17103
  function runLoaders(route, ctx) {
16240
- return runLoadersInternal(route, ctx, true, false);
17104
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, false));
16241
17105
  }
16242
17106
  function runPublicLoaders(route, ctx) {
16243
- return runLoadersInternal(route, ctx, false, false);
17107
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, false));
16244
17108
  }
16245
17109
  function hasSsrLoaderAncestor(route) {
16246
17110
  return route.routeChain.some((entry) => entry.mode === "ssr" && entry.loader !== undefined);
@@ -16250,13 +17114,13 @@ function hasMixedLoaderModes(route) {
16250
17114
  return route.routeChain.some((entry) => entry.loader !== undefined && entry.mode !== undefined && (entry.mode !== route.mode || entry.mode === "isr" && (entry.revalidate ?? 60) !== pageRevalidate));
16251
17115
  }
16252
17116
  function runMixedLoaders(route, ctx) {
16253
- return runLoadersInternal(route, ctx, true, true);
17117
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, true));
16254
17118
  }
16255
17119
  function runRouteLoaders(route, ctx) {
16256
17120
  return hasMixedLoaderModes(route) ? runMixedLoaders(route, ctx) : runLoaders(route, ctx);
16257
17121
  }
16258
17122
  function runSegmentPublicLoaders(route, ctx) {
16259
- return runLoadersInternal(route, ctx, false, true);
17123
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, true));
16260
17124
  }
16261
17125
  function hasRequestLoader(route) {
16262
17126
  return route.routeChain.some((entry) => entry.requestLoader !== undefined);
@@ -16270,9 +17134,9 @@ import { prerender } from "react-dom/static.edge";
16270
17134
  import {
16271
17135
  Children,
16272
17136
  cloneElement,
16273
- createElement as createElement3,
17137
+ createElement,
16274
17138
  isValidElement,
16275
- use as use2
17139
+ use
16276
17140
  } from "react";
16277
17141
 
16278
17142
  // src/rsc/client-codec.ts
@@ -16292,7 +17156,7 @@ var RSC_SOURCE = Symbol.for("furin.rsc.source");
16292
17156
 
16293
17157
  // src/rsc/shared.tsx
16294
17158
  function RscNode({ state }) {
16295
- return use2(state.tree);
17159
+ return use(state.tree);
16296
17160
  }
16297
17161
  function decodeFlightBytes(bytes) {
16298
17162
  return decodeFlight(new ReadableStream({
@@ -16303,7 +17167,7 @@ function decodeFlightBytes(bytes) {
16303
17167
  }));
16304
17168
  }
16305
17169
  function createRenderableSource(state) {
16306
- const element = createElement3(RscNode, { state });
17170
+ const element = createElement(RscNode, { state });
16307
17171
  return new Proxy(element, {
16308
17172
  get(target, property, receiver) {
16309
17173
  if (property === RSC_SOURCE) {
@@ -16560,6 +17424,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
16560
17424
  const { frame } = envelope;
16561
17425
  if (frame.type === "data") {
16562
17426
  dataValue = fromCrossJSON(frame.value, {});
17427
+ if (frame.deferredKeys.length > 0 && dataValue && typeof dataValue === "object") {
17428
+ const data = dataValue;
17429
+ data.__furinQueries ??= [];
17430
+ }
16563
17431
  for (const key of frame.deferredKeys) {
16564
17432
  deferredPromises[key] = new Promise((resolve, reject) => {
16565
17433
  resolvers.set(key, { reject, resolve });
@@ -16594,6 +17462,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
16594
17462
  } else if (frame.type === "rsc-error") {
16595
17463
  throw new Error(`[furin] RSC stream failed (${frame.digest})`);
16596
17464
  } else if (frame.type === "defer-resolve") {
17465
+ if (frame.queries && dataValue && typeof dataValue === "object") {
17466
+ const data = dataValue;
17467
+ mergeQuerySeeds(data.__furinQueries ??= [], fromCrossJSON(frame.queries, {}));
17468
+ }
16597
17469
  const value = fromCrossJSON(frame.value, {});
16598
17470
  const ids = new Set;
16599
17471
  collectRscDescriptorIds(value, ids);
@@ -16625,42 +17497,219 @@ async function parseRouteFrameLines(firstLine, readLine) {
16625
17497
  if (data === null || typeof data !== "object" || Array.isArray(data)) {
16626
17498
  throw new Error("[furin] route data frame must decode to an object");
16627
17499
  }
16628
- const completion = (async () => {
16629
- for (;; ) {
16630
- const line = await readLine();
16631
- if (line === undefined) {
16632
- break;
16633
- }
16634
- processLine(line);
16635
- }
16636
- if (pending.size > 0) {
16637
- throw new Error("[furin] route frame stream ended before an RSC source completed");
16638
- }
16639
- if (deferredRscValues.size > 0) {
16640
- throw new Error("[furin] route frame stream ended before an RSC source completed");
16641
- }
16642
- for (const [key, resolver] of resolvers) {
16643
- resolver.reject(new Error(`[furin] deferred stream closed before "${key}" was resolved`));
16644
- }
16645
- resolvers.clear();
16646
- })().catch((error) => {
16647
- rejectPending(error);
16648
- throw error;
16649
- });
16650
- return {
16651
- abort: rejectPending,
16652
- completion,
16653
- deferredPromises,
16654
- syncData: data
16655
- };
17500
+ const completion = (async () => {
17501
+ for (;; ) {
17502
+ const line = await readLine();
17503
+ if (line === undefined) {
17504
+ break;
17505
+ }
17506
+ processLine(line);
17507
+ }
17508
+ if (pending.size > 0) {
17509
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
17510
+ }
17511
+ if (deferredRscValues.size > 0) {
17512
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
17513
+ }
17514
+ for (const [key, resolver] of resolvers) {
17515
+ resolver.reject(new Error(`[furin] deferred stream closed before "${key}" was resolved`));
17516
+ }
17517
+ resolvers.clear();
17518
+ })().catch((error) => {
17519
+ rejectPending(error);
17520
+ throw error;
17521
+ });
17522
+ return {
17523
+ abort: rejectPending,
17524
+ completion,
17525
+ deferredPromises,
17526
+ syncData: data
17527
+ };
17528
+ }
17529
+
17530
+ // src/server/render/ppr-document.ts
17531
+ init_context_logger();
17532
+ init_instance();
17533
+
17534
+ // src/server/render/document.tsx
17535
+ import { createElement as createElement3 } from "react";
17536
+
17537
+ // src/client/document.tsx
17538
+ import { createContext, createElement as createElement2, useContext } from "react";
17539
+ import { preloadModule } from "react-dom";
17540
+ import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
17541
+ var DocumentContext = createContext(null);
17542
+ function serializeJson(value) {
17543
+ return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
17544
+ }
17545
+ function DocumentProvider({
17546
+ children,
17547
+ value
17548
+ }) {
17549
+ return /* @__PURE__ */ jsxDEV(DocumentContext.Provider, {
17550
+ value,
17551
+ children
17552
+ }, undefined, false, undefined, this);
17553
+ }
17554
+ function renderMeta(meta, key) {
17555
+ if ("title" in meta) {
17556
+ return /* @__PURE__ */ jsxDEV("title", {
17557
+ children: meta.title
17558
+ }, key, false, undefined, this);
17559
+ }
17560
+ if ("script:ld+json" in meta) {
17561
+ return /* @__PURE__ */ jsxDEV("script", {
17562
+ dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
17563
+ type: "application/ld+json"
17564
+ }, key, false, undefined, this);
17565
+ }
17566
+ if ("tagName" in meta) {
17567
+ const { tagName, ...attributes } = meta;
17568
+ return createElement2(tagName, { ...attributes, key });
17569
+ }
17570
+ return createElement2("meta", { ...meta, key });
17571
+ }
17572
+ function HeadContent() {
17573
+ const state = useContext(DocumentContext);
17574
+ if (state === null) {
17575
+ throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
17576
+ }
17577
+ for (const href of state.assets.modulePreloads ?? []) {
17578
+ preloadModule(href, { as: "script", nonce: state.nonce });
17579
+ }
17580
+ const occurrences = new Map;
17581
+ const descriptorKey = (descriptor) => {
17582
+ const identity = JSON.stringify(descriptor);
17583
+ const occurrence = occurrences.get(identity) ?? 0;
17584
+ occurrences.set(identity, occurrence + 1);
17585
+ return `${identity}:${occurrence}`;
17586
+ };
17587
+ return /* @__PURE__ */ jsxDEV(Fragment, {
17588
+ children: [
17589
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17590
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
17591
+ "data-furin-extension-error-filter": "",
17592
+ nonce: state.nonce
17593
+ }, undefined, false, undefined, this),
17594
+ /* @__PURE__ */ jsxDEV("meta", {
17595
+ charSet: "utf-8",
17596
+ "data-furin-head": ""
17597
+ }, undefined, false, undefined, this),
17598
+ /* @__PURE__ */ jsxDEV("meta", {
17599
+ content: "width=device-width, initial-scale=1.0",
17600
+ name: "viewport"
17601
+ }, undefined, false, undefined, this),
17602
+ state.assets.buildId ? /* @__PURE__ */ jsxDEV("meta", {
17603
+ content: state.assets.buildId,
17604
+ name: "furin-build-id"
17605
+ }, undefined, false, undefined, this) : null,
17606
+ state.assets.staticMode ? /* @__PURE__ */ jsxDEV("meta", {
17607
+ content: "static",
17608
+ name: "furin-mode"
17609
+ }, undefined, false, undefined, this) : null,
17610
+ state.assets.faviconHref ? /* @__PURE__ */ jsxDEV("link", {
17611
+ href: state.assets.faviconHref,
17612
+ rel: "icon"
17613
+ }, undefined, false, undefined, this) : null,
17614
+ state.assets.stylesheets.map((href) => /* @__PURE__ */ jsxDEV("link", {
17615
+ crossOrigin: "",
17616
+ href,
17617
+ rel: "stylesheet"
17618
+ }, href, false, undefined, this)),
17619
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
17620
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV("link", {
17621
+ ...link
17622
+ }, descriptorKey(link), false, undefined, this)),
17623
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV("script", {
17624
+ ...attributes,
17625
+ nonce: state.nonce ?? attributes.nonce,
17626
+ children
17627
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
17628
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV("style", {
17629
+ dangerouslySetInnerHTML: { __html: children },
17630
+ nonce: state.nonce,
17631
+ type
17632
+ }, descriptorKey({ children, type }), false, undefined, this))
17633
+ ]
17634
+ }, undefined, true, undefined, this);
17635
+ }
17636
+ function Scripts() {
17637
+ const state = useContext(DocumentContext);
17638
+ if (state === null) {
17639
+ throw new Error("[furin] <Scripts /> must be rendered inside the root layout.");
17640
+ }
17641
+ return /* @__PURE__ */ jsxDEV(Fragment, {
17642
+ children: [
17643
+ state.syncJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17644
+ dangerouslySetInnerHTML: { __html: state.syncJson },
17645
+ id: "__FURIN_SYNC__",
17646
+ type: "application/json"
17647
+ }, undefined, false, undefined, this),
17648
+ state.dataJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17649
+ dangerouslySetInnerHTML: { __html: state.dataJson },
17650
+ id: "__FURIN_DATA__",
17651
+ type: "application/json"
17652
+ }, undefined, false, undefined, this),
17653
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
17654
+ dangerouslySetInnerHTML: {
17655
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
17656
+ },
17657
+ "data-furin-document-state": "",
17658
+ id: "__FURIN_ROUTE_FRAMES__"
17659
+ }, undefined, false, undefined, this),
17660
+ /* @__PURE__ */ jsxDEV("script", {
17661
+ dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
17662
+ "data-furin-scripts": "",
17663
+ id: "__FURIN_HEAD__",
17664
+ type: "application/json"
17665
+ }, undefined, false, undefined, this),
17666
+ state.assets.frameworkModules.map((src) => /* @__PURE__ */ jsxDEV("script", {
17667
+ crossOrigin: "",
17668
+ "data-furin-framework-module": "",
17669
+ nonce: state.nonce,
17670
+ src,
17671
+ type: "module"
17672
+ }, src, false, undefined, this)),
17673
+ state.assets.entryModule === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17674
+ crossOrigin: "",
17675
+ "data-furin-entry": "",
17676
+ nonce: state.nonce,
17677
+ src: state.assets.entryModule,
17678
+ type: "module"
17679
+ }, undefined, false, undefined, this)
17680
+ ]
17681
+ }, undefined, true, undefined, this);
17682
+ }
17683
+ function FurinDocumentFallback({ children }) {
17684
+ return /* @__PURE__ */ jsxDEV("html", {
17685
+ lang: "en",
17686
+ children: [
17687
+ /* @__PURE__ */ jsxDEV("head", {
17688
+ children: /* @__PURE__ */ jsxDEV(HeadContent, {}, undefined, false, undefined, this)
17689
+ }, undefined, false, undefined, this),
17690
+ /* @__PURE__ */ jsxDEV("body", {
17691
+ children: [
17692
+ children,
17693
+ /* @__PURE__ */ jsxDEV(Scripts, {}, undefined, false, undefined, this)
17694
+ ]
17695
+ }, undefined, true, undefined, this)
17696
+ ]
17697
+ }, undefined, true, undefined, this);
16656
17698
  }
16657
17699
 
16658
- // src/server/render/ppr-document.ts
16659
- init_context_logger();
16660
- init_instance();
17700
+ // src/client/query.tsx
17701
+ import {
17702
+ createContext as createContext2,
17703
+ useCallback,
17704
+ useContext as useContext2,
17705
+ useEffect,
17706
+ useSyncExternalStore
17707
+ } from "react";
17708
+ var QUERY_CONTEXT2 = Symbol.for("furin.query.context.v1");
17709
+ var contextGlobal2 = globalThis;
17710
+ var QueryStoreContext = contextGlobal2[QUERY_CONTEXT2] ??= createContext2(null);
16661
17711
 
16662
17712
  // src/server/render/document.tsx
16663
- import { createElement as createElement4 } from "react";
16664
17713
  init_instance();
16665
17714
  init_config();
16666
17715
  function withDocumentState(element, assets, head, data, nonce) {
@@ -16679,7 +17728,9 @@ function withDocumentState(element, assets, head, data, nonce) {
16679
17728
  routeFrames,
16680
17729
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
16681
17730
  };
16682
- return createElement4(DocumentProvider, { value: state }, element);
17731
+ const queries = new QueryStore(undefined);
17732
+ queries.hydrate(data?.__furinQueries ?? []);
17733
+ return createElement3(DocumentProvider, { value: state }, createElement3(QueryStoreContext.Provider, { value: queries }, element));
16683
17734
  }
16684
17735
 
16685
17736
  // src/server/render/ppr-document.ts
@@ -16687,10 +17738,9 @@ init_ppr_request();
16687
17738
 
16688
17739
  // src/server/render/ssr.ts
16689
17740
  import { createElement as createElement7 } from "react";
16690
- import { renderToReadableStream } from "react-dom/server";
16691
17741
 
16692
17742
  // src/client/router/context.ts
16693
- import { createContext as createContext3, useContext as useContext2 } from "react";
17743
+ import { createContext as createContext3, useCallback as useCallback2, useContext as useContext3, useMemo } from "react";
16694
17744
  var RouterContext = createContext3(null);
16695
17745
  var CLIENT_FALLBACK_ROUTER = {
16696
17746
  basePath: "",
@@ -16715,15 +17765,15 @@ var CLIENT_FALLBACK_ROUTER = {
16715
17765
  search: {},
16716
17766
  searchRoutes: []
16717
17767
  };
16718
- function useRouter() {
16719
- const ctx = useContext2(RouterContext);
17768
+ function useRouterContext() {
17769
+ const ctx = useContext3(RouterContext);
16720
17770
  return ctx ?? CLIENT_FALLBACK_ROUTER;
16721
17771
  }
16722
17772
 
16723
17773
  // src/client/router/search-store.ts
16724
17774
  import { createContext as createContext4 } from "react";
16725
17775
  function searchSnapshotChanged(a, b) {
16726
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
17776
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
16727
17777
  }
16728
17778
  function createSearchStore(initialSnapshot) {
16729
17779
  let snapshot = initialSnapshot;
@@ -16760,6 +17810,7 @@ function createSearchStore(initialSnapshot) {
16760
17810
  function searchSnapshotFromRouterContext(context) {
16761
17811
  return {
16762
17812
  currentHref: context.currentHref,
17813
+ currentPattern: context.currentPattern,
16763
17814
  navigate: context.navigate,
16764
17815
  search: context.search,
16765
17816
  searchRoutes: context.searchRoutes
@@ -16767,6 +17818,7 @@ function searchSnapshotFromRouterContext(context) {
16767
17818
  }
16768
17819
  var FALLBACK_SEARCH_STORE = createSearchStore({
16769
17820
  currentHref: "/",
17821
+ currentPattern: undefined,
16770
17822
  navigate: (href, _opts) => {
16771
17823
  if (typeof window !== "undefined") {
16772
17824
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -16834,12 +17886,14 @@ function serializeCompactJsonLine(value) {
16834
17886
  // src/server/render/ssr.ts
16835
17887
  init_context_logger();
16836
17888
  init_instance();
17889
+ init_schema_merge();
17890
+ init_schemas();
16837
17891
 
16838
17892
  // src/server/render/element.tsx
16839
17893
  import { createElement as createElement6 } from "react";
16840
17894
 
16841
17895
  // src/client/boundaries.tsx
16842
- import { Component as Component2, Fragment as Fragment2 } from "react";
17896
+ import { Component, Fragment as Fragment2 } from "react";
16843
17897
 
16844
17898
  // src/shared/error.ts
16845
17899
  function getPublicErrorMessage(error) {
@@ -16851,7 +17905,57 @@ function getPublicErrorMessage(error) {
16851
17905
  }
16852
17906
 
16853
17907
  // src/client/link.tsx
16854
- import { createElement as createElement5, useCallback, useEffect, useRef } from "react";
17908
+ import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef } from "react";
17909
+
17910
+ // src/shared/page-key.ts
17911
+ function identityValue(value) {
17912
+ return Object.is(value, -0) ? "-0" : String(value);
17913
+ }
17914
+ function pageKey(pattern, data, remountDeps) {
17915
+ const { params, query } = data;
17916
+ if (remountDeps) {
17917
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
17918
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
17919
+ }
17920
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
17921
+ if (left < right) {
17922
+ return -1;
17923
+ }
17924
+ return left > right ? 1 : 0;
17925
+ });
17926
+ return JSON.stringify([
17927
+ pattern,
17928
+ entries.map(([name, value]) => [
17929
+ name,
17930
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
17931
+ ])
17932
+ ]);
17933
+ }
17934
+
17935
+ // src/client/route-api.tsx
17936
+ import { createContext as createContext5, createElement as createElement4, useContext as useContext4 } from "react";
17937
+ var RESERVED_RENDER_KEYS = new Set([
17938
+ "catch",
17939
+ "children",
17940
+ "finally",
17941
+ "key",
17942
+ "ref",
17943
+ "then",
17944
+ "toJSON"
17945
+ ]);
17946
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
17947
+ var contextGlobal3 = globalThis;
17948
+ var RouteContext = contextGlobal3[ROUTE_CONTEXT] ??= createContext5(null);
17949
+ function withRouteSnapshot(element, pattern, props) {
17950
+ const {
17951
+ params,
17952
+ path: _path,
17953
+ query: _query,
17954
+ ...data
17955
+ } = props;
17956
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
17957
+ return createElement4(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
17958
+ }
16855
17959
 
16856
17960
  // src/client/server-error.ts
16857
17961
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
@@ -16918,7 +18022,7 @@ function LinkInteractive({
16918
18022
  href: _href,
16919
18023
  ...anchorProps
16920
18024
  }) {
16921
- const router2 = useRouter();
18025
+ const router2 = useRouterContext();
16922
18026
  const anchorRef = useRef(null);
16923
18027
  const intentTimerRef = useRef(null);
16924
18028
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -16926,15 +18030,15 @@ function LinkInteractive({
16926
18030
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
16927
18031
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
16928
18032
  const { prefetch } = router2;
16929
- const triggerPrefetch = useCallback(() => {
18033
+ const triggerPrefetch = useCallback3(() => {
16930
18034
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
16931
18035
  }, [prefetch, logicalHref, effectiveStaleTime]);
16932
- useEffect(() => {
18036
+ useEffect2(() => {
16933
18037
  if (effectivePreload === "render") {
16934
18038
  triggerPrefetch();
16935
18039
  }
16936
18040
  }, [effectivePreload, triggerPrefetch]);
16937
- useEffect(() => {
18041
+ useEffect2(() => {
16938
18042
  if (effectivePreload !== "viewport" || !anchorRef.current) {
16939
18043
  return;
16940
18044
  }
@@ -16947,7 +18051,7 @@ function LinkInteractive({
16947
18051
  observer.observe(anchorRef.current);
16948
18052
  return () => observer.disconnect();
16949
18053
  }, [effectivePreload, triggerPrefetch]);
16950
- useEffect(() => () => {
18054
+ useEffect2(() => () => {
16951
18055
  if (intentTimerRef.current !== null) {
16952
18056
  clearTimeout(intentTimerRef.current);
16953
18057
  intentTimerRef.current = null;
@@ -17370,7 +18474,7 @@ function normalizeCaughtError(error) {
17370
18474
  return normalized;
17371
18475
  }
17372
18476
 
17373
- class FurinErrorBoundary extends Component2 {
18477
+ class FurinErrorBoundary extends Component {
17374
18478
  state = {
17375
18479
  digest: null,
17376
18480
  epoch: 0,
@@ -17420,7 +18524,7 @@ class FurinErrorBoundary extends Component2 {
17420
18524
  }
17421
18525
  }
17422
18526
 
17423
- class FurinNotFoundBoundary extends Component2 {
18527
+ class FurinNotFoundBoundary extends Component {
17424
18528
  state = { epoch: 0, error: null };
17425
18529
  static getDerivedStateFromError(error) {
17426
18530
  return { error };
@@ -17473,7 +18577,10 @@ function wrapSegmentBoundaries(inner, segment, options) {
17473
18577
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
17474
18578
  function buildElement(route, data, rootLayout) {
17475
18579
  const Component = route.page.component;
17476
- let element = createElement6(Component, data);
18580
+ let element = createElement6(Component, {
18581
+ ...data,
18582
+ key: pageKey(route.pattern, data, route.page._route.remountDeps)
18583
+ });
17477
18584
  const byDepth = new Map;
17478
18585
  const legacyRoute = route;
17479
18586
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
@@ -17492,7 +18599,7 @@ function buildElement(route, data, rootLayout) {
17492
18599
  const RootLayoutComponent = rootLayout.layout;
17493
18600
  element = createElement6(RootLayoutComponent, data, element);
17494
18601
  }
17495
- return element;
18602
+ return withRouteSnapshot(element, route.pattern, data);
17496
18603
  }
17497
18604
  function wrapRootLayout(element, data, rootLayout) {
17498
18605
  if (!rootLayout.layout) {
@@ -17539,14 +18646,41 @@ function buildErrorElement(component, error, digest, messageOverride, status) {
17539
18646
  }, undefined, false, undefined, this);
17540
18647
  }
17541
18648
 
18649
+ // src/server/render/react-stream.ts
18650
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "async_hooks";
18651
+ import { renderToReadableStream as renderReactStream } from "react-dom/server";
18652
+
18653
+ // src/client/client-module.ts
18654
+ import { preloadModule as preloadModule2 } from "react-dom";
18655
+ var resolveModuleHrefs = () => [];
18656
+ var resolveNonce = () => {
18657
+ return;
18658
+ };
18659
+ function setClientModuleNonceResolver(resolver) {
18660
+ resolveNonce = resolver;
18661
+ }
18662
+ function setClientModuleHrefResolver(resolver) {
18663
+ resolveModuleHrefs = resolver;
18664
+ }
18665
+
18666
+ // src/server/render/react-stream.ts
18667
+ var renderNonces = new AsyncLocalStorage7;
18668
+ setClientModuleNonceResolver(() => renderNonces.getStore());
18669
+ function renderToReadableStream(element, options) {
18670
+ const nonce = options?.nonce;
18671
+ return renderNonces.run(typeof nonce === "string" ? nonce : nonce?.script, () => renderReactStream(element, options));
18672
+ }
18673
+
17542
18674
  // src/server/render/route-frame-transport.ts
17543
18675
  async function serializeDeferredRouteFrame(key, promise, idPrefix) {
17544
18676
  try {
17545
18677
  const { rscFrames, value } = serializeRouteFrameValue(await promise, idPrefix);
18678
+ const queries = deferredQuerySeeds(promise);
17546
18679
  return serializeRouteFrame({
17547
18680
  key,
17548
18681
  type: "defer-resolve",
17549
- value
18682
+ value,
18683
+ ...queries && { queries: toCrossJSON(queries) }
17550
18684
  }) + rscFrames;
17551
18685
  } catch (error) {
17552
18686
  return serializeRouteFrame({
@@ -17576,16 +18710,17 @@ function createDeferredRouteFrameStream(syncData, deferredPromises) {
17576
18710
  });
17577
18711
  }
17578
18712
  // src/server/render/template.ts
18713
+ import { readFileSync as readFileSync3 } from "fs";
17579
18714
  init_plugin2();
17580
18715
  init_instrumentation();
17581
18716
  init_instance();
17582
- import { readFileSync as readFileSync3 } from "fs";
17583
18717
  var instanceTemplateState = instanceSlot(() => ({
17584
18718
  devAssets: null,
17585
18719
  devCache: null,
17586
18720
  prodAssets: null,
17587
18721
  prodContent: null,
17588
- prodPath: null
18722
+ prodPath: null,
18723
+ prodPreload: null
17589
18724
  }));
17590
18725
  var DEV_TEMPLATE_TTL_MS = 1000;
17591
18726
  var TAG_ATTRIBUTE_PATTERN = /([A-Za-z][\w:-]*)="([^"]*)"/g;
@@ -17726,6 +18861,13 @@ function readDocumentAssets(state) {
17726
18861
  state.prodAssets = documentAssetsFromTemplate(template);
17727
18862
  return state.prodAssets;
17728
18863
  }
18864
+ function setProductionPreloadManifest(manifest, instance) {
18865
+ instanceTemplateState(instance).prodPreload = manifest;
18866
+ }
18867
+ function getProductionPreloadManifest() {
18868
+ return instanceTemplateState().prodPreload ?? instanceTemplateState(defaultInstanceBucket()).prodPreload;
18869
+ }
18870
+ setClientModuleHrefResolver((key) => getProductionPreloadManifest()?.modules[key] ?? []);
17729
18871
 
17730
18872
  // src/server/render/ssr.ts
17731
18873
  function withSSRRouterContext(element, contextValue) {
@@ -17801,7 +18943,8 @@ async function renderElementWithShellFallback(element, errorComponent, ssrContex
17801
18943
  }
17802
18944
  }
17803
18945
  function assertDeferredModeAllowed(route, deferredPromises) {
17804
- const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !route.requestKeys?.includes(key));
18946
+ const requestKeys = new Set(route.requestKeys);
18947
+ const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !requestKeys.has(key));
17805
18948
  if (deferredKeys.length > 0 && route.mode !== "ssr" && !hasSsrLoaderAncestor(route)) {
17806
18949
  throw new Error(`[furin] page "${route.pattern}" returned defer() but the route is rendered in "${route.mode}" mode. ` + "defer() streams data progressively and is only supported in SSR. " + "Return the data directly (await it inside the loader) or switch the route to SSR mode.");
17807
18950
  }
@@ -17836,6 +18979,10 @@ function resolveDocumentAssets(ctx) {
17836
18979
  }
17837
18980
  return documentAssetsFromTemplate(generateIndexHtml());
17838
18981
  }
18982
+ function withRouteModulePreloads(assets, pattern) {
18983
+ const modulePreloads = getProductionPreloadManifest()?.routes[pattern];
18984
+ return modulePreloads ? { ...assets, modulePreloads } : assets;
18985
+ }
17839
18986
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
17840
18987
  const loaderStart = Date.now();
17841
18988
  const loaderResult = precomputedLoaderResult ?? await runRouteLoaders(route, ctx);
@@ -17843,7 +18990,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17843
18990
  if (loaderResult.type === "redirect") {
17844
18991
  return loaderResult.response;
17845
18992
  }
17846
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
18993
+ if (throwOnFailure && loaderResult.type === "error") {
17847
18994
  throw loaderResult.error;
17848
18995
  }
17849
18996
  const isNotFound = loaderResult.type === "not-found";
@@ -17854,7 +19001,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17854
19001
  assertDeferredModeAllowed(route, deferredPromises);
17855
19002
  const { headers } = loaderResult;
17856
19003
  const componentProps = deferredPromises === undefined ? syncData : { ...syncData, ...deferredPromises };
17857
- const assets = await resolveDocumentAssets(ctx);
19004
+ const assets = withRouteModulePreloads(await resolveDocumentAssets(ctx), route.pattern);
17858
19005
  const errorComponent = route.error ?? root.error;
17859
19006
  let element;
17860
19007
  let headData;
@@ -17882,6 +19029,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17882
19029
  const ssrContext = {
17883
19030
  basePath: resolvedBasePath,
17884
19031
  currentHref: currentHrefFromContext(ctx, resolvedBasePath),
19032
+ currentPattern: route.pattern,
17885
19033
  defaultPreload: "intent",
17886
19034
  defaultPreloadDelay: 50,
17887
19035
  defaultPreloadStaleTime: 30000,
@@ -17937,9 +19085,30 @@ async function renderBufferedResult(prepared, route, root) {
17937
19085
  headers,
17938
19086
  html,
17939
19087
  ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
19088
+ queryTags: queryTagsFromData(syncData),
17940
19089
  status: prepared.status
17941
19090
  };
17942
19091
  }
19092
+ async function normalizePrerenderContext(route, ctx) {
19093
+ const parsedParams = await parseRouteParams(ctx.params, mergeRouteSchemas(route.routeChain, "params"));
19094
+ if (!parsedParams.ok) {
19095
+ throw new Error(`[furin] Invalid prerender params for "${route.pattern}".`, {
19096
+ cause: parsedParams.errors
19097
+ });
19098
+ }
19099
+ ctx.params = parsedParams.params;
19100
+ const querySchema = mergeRouteSchemas(route.routeChain, "query");
19101
+ if (querySchema === undefined) {
19102
+ return;
19103
+ }
19104
+ const parsedQuery = await parseRouteQuery(new URL(ctx.request.url), querySchema);
19105
+ if (!parsedQuery.ok) {
19106
+ throw new Error(`[furin] Invalid prerender query for "${route.pattern}".`, {
19107
+ cause: parsedQuery.errors
19108
+ });
19109
+ }
19110
+ ctx.query = parsedQuery.query;
19111
+ }
17943
19112
  function renderForPath(route, params, root, origin, mode, basePath, searchRoutes, search, requestContext) {
17944
19113
  return runInSyntheticRenderScope(async () => {
17945
19114
  const resolvedPath = resolvePath(route.pattern, params);
@@ -17965,6 +19134,9 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
17965
19134
  request: new Request(requestUrl),
17966
19135
  set: { headers: {} }
17967
19136
  };
19137
+ if (requestContext === undefined) {
19138
+ await normalizePrerenderContext(route, ctx);
19139
+ }
17968
19140
  const loaderResult = await (hasMixedLoaderModes(route) ? runSegmentPublicLoaders(route, ctx) : runPublicLoaders(route, ctx));
17969
19141
  const prepared = await prepareRender(route, ctx, root, basePath, true, loaderResult, searchRoutes);
17970
19142
  if (prepared instanceof Response) {
@@ -18323,7 +19495,7 @@ async function prerenderPprDocument(route, ctx, root, buildId, searchRoutes, bas
18323
19495
  prefix,
18324
19496
  version: 1
18325
19497
  },
18326
- tags: route.tags
19498
+ tags: [...route.tags ?? [], ...queryTagsFromData(result.syncData)]
18327
19499
  };
18328
19500
  }
18329
19501
  async function resumePprDocument(route, ctx, root, artifact, searchRoutes) {
@@ -18493,6 +19665,10 @@ async function renderSharedPpr(input, identity, lease, revalidate) {
18493
19665
  if (lease === null || !isPprArtifact(result)) {
18494
19666
  return result;
18495
19667
  }
19668
+ const identityTags = new Set(identity.tags);
19669
+ if ((result.tags ?? []).some((tag) => !identityTags.has(tag))) {
19670
+ return result;
19671
+ }
18496
19672
  try {
18497
19673
  await input.pageCache.commit({
18498
19674
  entry: {
@@ -18550,7 +19726,12 @@ async function getSharedPprArtifact(input) {
18550
19726
  mode: "ppr",
18551
19727
  path: input.resolvedPath,
18552
19728
  scope: prefix,
18553
- tags: input.route.tags ?? []
19729
+ tags: [
19730
+ ...new Set([
19731
+ ...input.route.tags ?? [],
19732
+ ...getAutoInvalidateRegistry().tagsForPath(input.cacheKey.slice(input.cacheKey.indexOf(":") + 1))
19733
+ ])
19734
+ ]
18554
19735
  };
18555
19736
  const revalidate = resolveDocumentRevalidate(input.route) ?? 60;
18556
19737
  const lookup = await lookupSharedPpr(input, identity);
@@ -18624,17 +19805,22 @@ async function getPprArtifact(route, ctx, root, buildId, searchRoutes) {
18624
19805
  }
18625
19806
  const pprRoutes = getPprRoutes();
18626
19807
  const cached = externalPrerender ? undefined : pprRoutes.get(cacheKey);
18627
- if (cached === undefined || cached.artifact.state.buildId !== buildId) {
18628
- const result = await prerenderPprDocument(route, ctx, root, buildId, searchRoutes, undefined);
18629
- if (!isPprArtifact(result)) {
19808
+ if (cached?.artifact.state.buildId !== buildId) {
19809
+ const generation = pprRoutes.captureGeneration(cacheKey);
19810
+ try {
19811
+ const result = await prerenderPprDocument(route, ctx, root, buildId, searchRoutes, undefined);
19812
+ if (!(isPprArtifact(result) && generation.valid)) {
19813
+ return result;
19814
+ }
19815
+ pprRoutes.set(cacheKey, {
19816
+ artifact: result,
19817
+ revalidate: resolveDocumentRevalidate(route) ?? 60
19818
+ });
19819
+ autoInvalidateRegistry.registerLoaderTags(resolvedPath, result.tags, "render:ppr-public-shell");
18630
19820
  return result;
19821
+ } finally {
19822
+ pprRoutes.releaseGeneration(cacheKey, generation);
18631
19823
  }
18632
- pprRoutes.set(cacheKey, {
18633
- artifact: result,
18634
- revalidate: resolveDocumentRevalidate(route) ?? 60
18635
- });
18636
- autoInvalidateRegistry.registerLoaderTags(resolvedPath, route.tags, "render:ppr-public-shell");
18637
- return result;
18638
19824
  }
18639
19825
  if (documentMode !== "isr" || Date.now() - cached.artifact.cachedAt < cached.revalidate * 1000) {
18640
19826
  return cached.artifact;
@@ -18679,6 +19865,9 @@ var instanceSsgCache = instanceSlot((instance) => {
18679
19865
  registerCacheInvalidator(cache, instance);
18680
19866
  return cache;
18681
19867
  });
19868
+ function ssgRouteCache(instance) {
19869
+ return instanceSsgCache(instance);
19870
+ }
18682
19871
  var ssgCache = createStoreView(() => instanceSsgCache().store);
18683
19872
  function getSSGCache(key) {
18684
19873
  return instanceSsgCache().get(key);
@@ -18806,7 +19995,6 @@ function initializeFurinLogger(config) {
18806
19995
 
18807
19996
  // src/server/render/not-found.ts
18808
19997
  import { createElement as createElement8 } from "react";
18809
- import { renderToReadableStream as renderToReadableStream2 } from "react-dom/server";
18810
19998
  init_context_logger();
18811
19999
  init_instance();
18812
20000
  init_schemas();
@@ -18862,10 +20050,11 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18862
20050
  render: "not-found"
18863
20051
  }
18864
20052
  });
18865
- const data = { __furinStatus: 404 };
20053
+ const rootData = { params: {}, path: logicalPath, query };
20054
+ const data = { ...rootData, __furinStatus: 404 };
18866
20055
  let reactStream;
18867
20056
  try {
18868
- reactStream = await renderToReadableStream2(withDocumentState(withSSRRouterContext(wrapRootLayout(buildNotFoundElement(root.notFound, notFoundError), { params: {}, path: logicalPath, query }, root.route), notFoundContext), assets, undefined, data, nonce), { nonce });
20057
+ reactStream = await renderToReadableStream(withDocumentState(withSSRRouterContext(wrapRootLayout(buildNotFoundElement(root.notFound, notFoundError), rootData, root.route), notFoundContext), assets, undefined, data, nonce), { nonce });
18869
20058
  } catch (renderError) {
18870
20059
  getLogger().set({
18871
20060
  furin: {
@@ -18874,7 +20063,7 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18874
20063
  render: "not-found"
18875
20064
  }
18876
20065
  });
18877
- reactStream = await renderToReadableStream2(withDocumentState(createElement8(FurinDocumentFallback, null, withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)), assets, undefined, data, nonce), { nonce });
20066
+ reactStream = await renderToReadableStream(withDocumentState(createElement8(FurinDocumentFallback, null, withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)), assets, undefined, data, nonce), { nonce });
18878
20067
  }
18879
20068
  await reactStream.allReady;
18880
20069
  const html = await streamToString(reactStream);
@@ -18883,7 +20072,9 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18883
20072
  status: 404
18884
20073
  });
18885
20074
  }
20075
+
18886
20076
  // src/server/render/ssg.ts
20077
+ init_registry();
18887
20078
  init_context_logger();
18888
20079
  init_instance();
18889
20080
  init_patterns();
@@ -19011,26 +20202,38 @@ async function prerenderRoute(route, params, root, origin, mode, basePath, searc
19011
20202
  html: renderResult.html,
19012
20203
  ndjson: renderResult.ndjson,
19013
20204
  status: renderResult.status,
19014
- tags: route.tags
20205
+ tags: [...route.tags ?? [], ...renderResult.queryTags ?? []]
19015
20206
  };
19016
20207
  }
19017
- async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
20208
+ async function prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes) {
19018
20209
  const resolvedPath = resolvePath(route.pattern, params);
19019
20210
  const cached = getSSGCache(resolvedPath);
19020
20211
  if (cached) {
19021
20212
  if (cached.tags === route.tags) {
19022
- return cached;
19023
- }
19024
- const taggedEntry = { ...cached, tags: route.tags };
20213
+ return { cacheStored: true, entry: cached };
20214
+ }
20215
+ const taggedEntry = {
20216
+ ...cached,
20217
+ tags: [
20218
+ ...route.tags ?? [],
20219
+ ...(cached.tags ?? []).filter((tag) => queryFromTag(tag) !== undefined)
20220
+ ]
20221
+ };
19025
20222
  setSSGCache(resolvedPath, taggedEntry);
19026
- return taggedEntry;
20223
+ return { cacheStored: true, entry: taggedEntry };
19027
20224
  }
19028
- const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
19029
- if (entry instanceof Response) {
19030
- return entry;
20225
+ const cache = ssgRouteCache();
20226
+ const generation = cache.captureGeneration(resolvedPath);
20227
+ try {
20228
+ const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
20229
+ if (entry instanceof Response || entry.status !== 200 || !generation.valid) {
20230
+ return { cacheStored: false, entry };
20231
+ }
20232
+ setSSGCache(resolvedPath, entry);
20233
+ return { cacheStored: true, entry };
20234
+ } finally {
20235
+ cache.releaseGeneration(resolvedPath, generation);
19031
20236
  }
19032
- setSSGCache(resolvedPath, entry);
19033
- return entry;
19034
20237
  }
19035
20238
  function parseSharedSsgEntry(payload) {
19036
20239
  const value = JSON.parse(payload);
@@ -19042,7 +20245,11 @@ function parseSharedSsgEntry(payload) {
19042
20245
  async function renderAndStoreSharedSsg(input, lease) {
19043
20246
  try {
19044
20247
  const entry = await input.renderFresh();
19045
- if (entry instanceof Response || lease === null) {
20248
+ if (entry instanceof Response || entry.status !== 200 || lease === null) {
20249
+ return { cacheStored: false, entry };
20250
+ }
20251
+ const identityTags = new Set(input.identity.tags);
20252
+ if ((entry.tags ?? []).some((tag) => !identityTags.has(tag))) {
19046
20253
  return { cacheStored: false, entry };
19047
20254
  }
19048
20255
  let cacheStored = false;
@@ -19104,10 +20311,7 @@ async function resolveSharedSsg(input) {
19104
20311
  async function prerenderRuntimeSSG(route, params, root, origin, buildId, searchRoutes) {
19105
20312
  const pageCache = getPageCacheAdapter();
19106
20313
  if (pageCache === undefined) {
19107
- return {
19108
- cacheStored: true,
19109
- entry: await prerenderSSG(route, params, root, origin, undefined, searchRoutes)
19110
- };
20314
+ return prerenderLocalSSG(route, params, root, origin, undefined, searchRoutes);
19111
20315
  }
19112
20316
  const resolvedPath = resolvePath(route.pattern, params);
19113
20317
  const identity = {
@@ -19116,10 +20320,12 @@ async function prerenderRuntimeSSG(route, params, root, origin, buildId, searchR
19116
20320
  mode: "ssg",
19117
20321
  path: resolvedPath,
19118
20322
  scope: currentInstance().prefix,
19119
- tags: route.tags ?? []
20323
+ tags: [
20324
+ ...new Set([...route.tags ?? [], ...getAutoInvalidateRegistry().tagsForPath(resolvedPath)])
20325
+ ]
19120
20326
  };
19121
20327
  const renderFresh = () => prerenderRoute(route, params, root, origin, "ssg", undefined, searchRoutes);
19122
- return resolveSharedSsg({ identity, pageCache, renderFresh });
20328
+ return await resolveSharedSsg({ identity, pageCache, renderFresh });
19123
20329
  }
19124
20330
  function logSsgError(furin, error) {
19125
20331
  const logger = createLogger({});
@@ -19488,7 +20694,8 @@ function computeRouteDependencies(pagePath, rootPath) {
19488
20694
  }
19489
20695
  }
19490
20696
  }
19491
- return deps;
20697
+ const graph = devGraph(undefined);
20698
+ return [...new Set(deps.flatMap((path) => graph.sourceDependencies(path)))].filter(existsSync3);
19492
20699
  }
19493
20700
 
19494
20701
  // src/furin.ts
@@ -19745,9 +20952,11 @@ async function renderISRCacheMiss(input) {
19745
20952
  route: input.route.pattern
19746
20953
  }
19747
20954
  });
19748
- const cacheStored = await storeRenderedISR(input, html, generatedAt);
20955
+ const discoveredTags = queryTagsFromData(syncData);
20956
+ const identityTags = new Set(input.pageCacheIdentity.tags);
20957
+ const cacheStored = input.pageCache !== undefined && discoveredTags.some((tag) => !identityTags.has(tag)) ? false : await storeRenderedISR(input, html, generatedAt);
19749
20958
  if (cacheStored && input.pageCache === undefined) {
19750
- autoInvalidateRegistry.registerLoaderTags(input.cacheKey, input.route.tags, "render:isr-html");
20959
+ autoInvalidateRegistry.registerLoaderTags(input.cacheKey, [...input.route.tags ?? [], ...discoveredTags], "render:isr-html");
19751
20960
  }
19752
20961
  for (const [key, value] of Object.entries(headers)) {
19753
20962
  input.ctx.set.headers[key] = value;
@@ -19776,7 +20985,9 @@ async function handleISR(route, ctx, root, buildId, searchRoutes) {
19776
20985
  mode: "isr",
19777
20986
  path: resolvedPath,
19778
20987
  scope: currentInstance().prefix,
19779
- tags: route.tags ?? []
20988
+ tags: [
20989
+ ...new Set([...route.tags ?? [], ...getAutoInvalidateRegistry().tagsForPath(cacheKey)])
20990
+ ]
19780
20991
  };
19781
20992
  const lookup = await lookupISRCache(pageCache, pageCacheIdentity, cacheKey, externalPrerender, revalidate);
19782
20993
  const { cached, sharedAvailable: initialSharedAvailable } = lookup;
@@ -19880,33 +21091,11 @@ function logRevalidationSkipped(route, reason, status) {
19880
21091
  logger.emit();
19881
21092
  }
19882
21093
  async function handleBackgroundRevalidationError(input, error) {
19883
- const logger = createLogger({});
19884
21094
  if (isNotFoundError(error)) {
19885
- if (input.sharedCache === undefined) {
19886
- deleteISRCache(input.cacheKey);
19887
- } else {
19888
- try {
19889
- await input.sharedCache.adapter.invalidate({
19890
- kind: "path",
19891
- path: input.sharedCache.identity.path,
19892
- scope: input.sharedCache.identity.scope,
19893
- type: "page"
19894
- });
19895
- } catch {
19896
- logger.warn("ISR shared page cache invalidation failed after not-found revalidation");
19897
- }
19898
- }
19899
- logger.set({
19900
- furin: {
19901
- cache: "revalidation_invalidated",
19902
- reason: "not_found",
19903
- render: "isr",
19904
- route: input.route.pattern
19905
- }
19906
- });
19907
- logger.emit();
21095
+ await invalidateBackgroundNotFound(input);
19908
21096
  return;
19909
21097
  }
21098
+ const logger = createLogger({});
19910
21099
  logger.set({
19911
21100
  furin: {
19912
21101
  cache: "revalidation_failed",
@@ -19917,6 +21106,35 @@ async function handleBackgroundRevalidationError(input, error) {
19917
21106
  logger.error(error instanceof Error ? error : new Error(String(error)));
19918
21107
  logger.emit();
19919
21108
  }
21109
+ async function invalidateBackgroundNotFound(input) {
21110
+ if (input.sharedCache === undefined && !input.cacheGeneration?.valid) {
21111
+ return;
21112
+ }
21113
+ const logger = createLogger({});
21114
+ if (input.sharedCache === undefined) {
21115
+ deleteISRCache(input.cacheKey);
21116
+ } else {
21117
+ try {
21118
+ await input.sharedCache.adapter.invalidate({
21119
+ kind: "path",
21120
+ path: input.sharedCache.identity.path,
21121
+ scope: input.sharedCache.identity.scope,
21122
+ type: "page"
21123
+ });
21124
+ } catch {
21125
+ logger.warn("ISR shared page cache invalidation failed after not-found revalidation");
21126
+ }
21127
+ }
21128
+ logger.set({
21129
+ furin: {
21130
+ cache: "revalidation_invalidated",
21131
+ reason: "not_found",
21132
+ render: "isr",
21133
+ route: input.route.pattern
21134
+ }
21135
+ });
21136
+ logger.emit();
21137
+ }
19920
21138
  async function releaseBackgroundRevalidation(input, lease) {
19921
21139
  if (input.sharedCache !== undefined && lease !== null) {
19922
21140
  try {
@@ -19946,18 +21164,30 @@ async function performBackgroundRevalidation(input) {
19946
21164
  if (result instanceof Response) {
19947
21165
  return;
19948
21166
  }
21167
+ if (result.status === 404) {
21168
+ await invalidateBackgroundNotFound(input);
21169
+ return;
21170
+ }
19949
21171
  if (result.status !== 200) {
19950
21172
  logRevalidationSkipped(input.route, "non_200_render", result.status);
19951
21173
  return;
19952
21174
  }
19953
21175
  if (input.sharedCache !== undefined && lease !== null) {
21176
+ const { identity } = input.sharedCache;
21177
+ const identityTags = new Set(identity.tags);
21178
+ if ((result.queryTags ?? []).some((tag) => !identityTags.has(tag))) {
21179
+ return;
21180
+ }
19954
21181
  await input.sharedCache.adapter.commit({
19955
21182
  entry: { cachedAt: Date.now(), payload: result.html, revalidate: input.revalidate },
19956
21183
  identity: input.sharedCache.identity,
19957
21184
  lease
19958
21185
  });
19959
21186
  } else if (input.cacheGeneration !== undefined) {
19960
- setISRCacheIfGenerationUnchanged(input.cacheKey, { generatedAt: Date.now(), html: result.html, revalidate: input.revalidate }, input.cacheGeneration);
21187
+ const stored = setISRCacheIfGenerationUnchanged(input.cacheKey, { generatedAt: Date.now(), html: result.html, revalidate: input.revalidate }, input.cacheGeneration);
21188
+ if (stored) {
21189
+ autoInvalidateRegistry.registerLoaderTags(input.cacheKey, [...input.route.tags ?? [], ...result.queryTags ?? []], "render:isr-html");
21190
+ }
19961
21191
  }
19962
21192
  } catch (error) {
19963
21193
  await handleBackgroundRevalidationError(input, error);
@@ -20000,14 +21230,10 @@ async function runDataEndpointLoaders(route, ctx, root, searchRoutes) {
20000
21230
  }
20001
21231
  async function serializeLoaderDataResponse(result, route, requestUrl, routeContext) {
20002
21232
  if (result.type === "redirect") {
20003
- const redirectUrl = new URL(result.response.headers.get("location") ?? "/", requestUrl);
20004
- const serialized = await toCrossJSONAsync({
20005
- __furinRedirect: redirectUrl.pathname + redirectUrl.search + redirectUrl.hash
20006
- });
20007
- return new Response(`${JSON.stringify(serialized)}
20008
- `, {
20009
- headers: { "content-type": "application/x-ndjson" }
20010
- });
21233
+ const { prefix } = currentInstance();
21234
+ const pageUrl = new URL(requestUrl);
21235
+ pageUrl.pathname = physicalPath(prefix, pageUrl.pathname);
21236
+ return serializeNavigationRedirect(result.response, pageUrl, prefix);
20011
21237
  }
20012
21238
  if (result.type === "not-found") {
20013
21239
  const serialized = await toCrossJSONAsync({
@@ -20052,11 +21278,19 @@ async function serializeGuardRedirect(response, request) {
20052
21278
  const rawPath = requestUrl.searchParams.get("path");
20053
21279
  const logicalPath = rawPath ? parseDataEndpointPath(rawPath) : undefined;
20054
21280
  const pageUrl = logicalPath ? new URL(prefix + logicalPath.pathname + logicalPath.url.search, requestUrl) : requestUrl;
21281
+ return await serializeNavigationRedirect(response, pageUrl, prefix);
21282
+ }
21283
+ async function serializeNavigationRedirect(response, pageUrl, prefix) {
21284
+ const location = response.headers.get("location");
21285
+ if (!location) {
21286
+ return response;
21287
+ }
20055
21288
  const target = new URL(location, pageUrl);
20056
21289
  const withinMount = prefix === "" || target.pathname === prefix || target.pathname.startsWith(`${prefix}/`);
20057
- const href = target.origin === requestUrl.origin && withinMount ? (target.pathname.slice(prefix.length) || "/") + target.search + target.hash : target.href;
21290
+ const href = target.origin === pageUrl.origin && withinMount ? (target.pathname.slice(prefix.length) || "/") + target.search + target.hash : target.href;
20058
21291
  const serialized = await toCrossJSONAsync({ __furinRedirect: href });
20059
21292
  const headers = new Headers(response.headers);
21293
+ headers.delete("content-length");
20060
21294
  headers.delete("location");
20061
21295
  headers.set("content-type", "application/x-ndjson");
20062
21296
  headers.set("cache-control", "private, no-store");
@@ -20120,14 +21354,15 @@ async function handleSSGRequest(route, ctx, root, buildId, searchRoutes) {
20120
21354
  if (entry instanceof Response) {
20121
21355
  return entry;
20122
21356
  }
21357
+ ctx.set.status = entry.status;
20123
21358
  const resolvedPath = resolvePath(route.pattern, params);
20124
21359
  const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
20125
- if (etag && ctx.request.headers.get("if-none-match") === etag) {
21360
+ if (entry.status === 200 && etag && ctx.request.headers.get("if-none-match") === etag) {
20126
21361
  ctx.set.status = 304;
20127
21362
  return;
20128
21363
  }
20129
21364
  ctx.set.headers["content-type"] = "text/html; charset=utf-8";
20130
- ctx.set.headers["cache-control"] = cacheStored ? "public, max-age=0, must-revalidate, s-maxage=31536000" : "no-store";
21365
+ ctx.set.headers["cache-control"] = cacheStored && entry.status === 200 ? "public, max-age=0, must-revalidate, s-maxage=31536000" : "no-store";
20131
21366
  if (etag) {
20132
21367
  ctx.set.headers.etag = etag;
20133
21368
  }
@@ -20181,6 +21416,87 @@ function withResolvedHead(route, syncData) {
20181
21416
  init_schema_merge();
20182
21417
  init_schemas();
20183
21418
  init_config();
21419
+
21420
+ // src/server/sync/validation.ts
21421
+ import { createContext as createContext7 } from "elysia/context";
21422
+
21423
+ // src/server/sync/mutation-handler.ts
21424
+ import { createContext as createContext6 } from "elysia/context";
21425
+ var mutationBeginnings = new WeakMap;
21426
+ var installedApplications = new WeakSet;
21427
+ var installedContexts = new WeakSet;
21428
+ function prepareMutationHandler(context, begin) {
21429
+ if (!installedContexts.has(context.constructor)) {
21430
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation routes.");
21431
+ }
21432
+ mutationBeginnings.set(context.request, begin);
21433
+ }
21434
+ function installMutationHandlers(app) {
21435
+ if (installedApplications.has(app)) {
21436
+ return;
21437
+ }
21438
+ installedApplications.add(app);
21439
+ app.decorate("_furinMutationHandlers", true);
21440
+ app.wrap((fetch2) => {
21441
+ installedContexts.add(createContext6(app));
21442
+ return fetch2;
21443
+ });
21444
+ const compileHandler = app.handler.bind(app);
21445
+ app.handler = (index, immediate, route, aliases, table) => {
21446
+ const nativeRoute = route ?? (table ? [
21447
+ table.method[index],
21448
+ table.path[index],
21449
+ table.handler[index],
21450
+ table.owner[index],
21451
+ table.localHook[index],
21452
+ table.appHook[index],
21453
+ table.inheritedChain[index],
21454
+ table.macroScope?.get(index)
21455
+ ] : app["~routes"][index]);
21456
+ if (!nativeRoute || ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0])) {
21457
+ return compileHandler(index, immediate, route, aliases, table);
21458
+ }
21459
+ const [method, path, handle, owner, hooks, chain, inherited, macroScope] = nativeRoute;
21460
+ const wrapped = async (context) => {
21461
+ const begin = mutationBeginnings.get(context.request);
21462
+ mutationBeginnings.delete(context.request);
21463
+ const response = await begin?.();
21464
+ if (response !== undefined) {
21465
+ return response;
21466
+ }
21467
+ return typeof handle === "function" ? handle(context) : handle;
21468
+ };
21469
+ return compileHandler(index, immediate, [method, path, wrapped, owner, hooks, chain, inherited, macroScope], aliases, table);
21470
+ };
21471
+ }
21472
+
21473
+ // src/server/sync/validation.ts
21474
+ var applications = new WeakMap;
21475
+ var boundApplications = new WeakSet;
21476
+ function bindSyncValidation(app) {
21477
+ installMutationHandlers(app);
21478
+ if (boundApplications.has(app)) {
21479
+ return;
21480
+ }
21481
+ boundApplications.add(app);
21482
+ app.decorate("_furinSyncValidation", true);
21483
+ app.wrap((fetch2) => {
21484
+ applications.set(createContext7(app), app);
21485
+ return fetch2;
21486
+ });
21487
+ app.setup((root) => {
21488
+ applications.set(createContext7(root), root);
21489
+ });
21490
+ }
21491
+ function syncValidationApp(context) {
21492
+ const app = applications.get(context.constructor);
21493
+ if (!app) {
21494
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation().");
21495
+ }
21496
+ return app;
21497
+ }
21498
+
21499
+ // src/furin.ts
20184
21500
  init_define_route();
20185
21501
 
20186
21502
  // src/isomorphic.ts
@@ -20298,6 +21614,7 @@ async function invalidateTagsForInstance(instance, tagList) {
20298
21614
  let deleted = false;
20299
21615
  const purgedPaths = new Set;
20300
21616
  const logicalPurgedPaths = new Set;
21617
+ const sharedInvalidations = [];
20301
21618
  const pageCache = getPageCacheAdapter(instance);
20302
21619
  const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
20303
21620
  kind: "tags",
@@ -20311,9 +21628,19 @@ async function invalidateTagsForInstance(instance, tagList) {
20311
21628
  ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
20312
21629
  ...sharedResult?.paths ?? []
20313
21630
  ]);
21631
+ const tags = new Set(tagList);
20314
21632
  for (const path of taggedPaths) {
20315
21633
  const logicalPath = pathWithoutSearch(path);
21634
+ const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
20316
21635
  const result = revalidatePathForInstance(instance, logicalPath, "page", false);
21636
+ if (pageCache !== undefined && registered) {
21637
+ sharedInvalidations.push(pageCache.invalidate({
21638
+ kind: "path",
21639
+ scope: instance.prefix,
21640
+ path: logicalPath,
21641
+ type: "page"
21642
+ }));
21643
+ }
20317
21644
  deleted = result.deleted || deleted;
20318
21645
  purgedPaths.add(physicalPath(instance.prefix, logicalPath));
20319
21646
  logicalPurgedPaths.add(logicalPath);
@@ -20322,6 +21649,8 @@ async function invalidateTagsForInstance(instance, tagList) {
20322
21649
  logicalPurgedPaths.add(purged);
20323
21650
  }
20324
21651
  }
21652
+ const pathResults = await Promise.all(sharedInvalidations);
21653
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
20325
21654
  if (IS_DEV) {
20326
21655
  withInstance(instance, () => {
20327
21656
  const request = currentInstrumentationRequest();
@@ -20385,41 +21714,41 @@ function furinInvalidate() {
20385
21714
  });
20386
21715
  }
20387
21716
  // src/server/sync/plugin.ts
20388
- import { Elysia as Elysia11 } from "elysia";
21717
+ import { Elysia as Elysia11, ElysiaStatus as ElysiaStatus3 } from "elysia";
20389
21718
  init_context_logger();
20390
21719
 
20391
- // src/server/sync/fingerprint.ts
20392
- function compareCodePoints(left, right) {
20393
- if (left === right) {
20394
- return 0;
21720
+ // src/server/sync/atomic.ts
21721
+ import { ElysiaStatus as ElysiaStatus2, StatusMap as StatusMap2, Validator as Validator2 } from "elysia";
21722
+ init_context_logger();
21723
+
21724
+ // src/server/sync/queries.ts
21725
+ function resolveSyncInvalidations(input, context, value) {
21726
+ if (input === undefined) {
21727
+ return;
20395
21728
  }
20396
- return left < right ? -1 : 1;
21729
+ const selected = typeof input === "function" ? input(Object.assign(Object.create(Object.getPrototypeOf(context)), context, {
21730
+ responseValue: value
21731
+ })) : input;
21732
+ const rules = Array.isArray(selected) ? selected : [selected];
21733
+ return rules.map((rule) => ("id" in rule) ? { tags: [queryTag(rule)] } : rule);
20397
21734
  }
20398
- function canonicalize(value) {
20399
- if (Array.isArray(value)) {
20400
- return value.map(canonicalize);
21735
+ function appendQueryInvalidations(input, context) {
21736
+ if (input === undefined) {
21737
+ return;
21738
+ }
21739
+ const queries = [];
21740
+ for (const rule of Array.isArray(input) ? input : [input]) {
21741
+ for (const tag of rule.tags ?? []) {
21742
+ const identity = queryFromTag(tag);
21743
+ if (identity) {
21744
+ queries.push(identity);
21745
+ }
21746
+ }
20401
21747
  }
20402
- if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
20403
- return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
21748
+ if (queries.length > 0) {
21749
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
21750
+ context.set.headers["x-furin-sync"] = "1";
20404
21751
  }
20405
- return value;
20406
- }
20407
- function sha256Hex(source) {
20408
- const hasher = new Bun.CryptoHasher("sha256");
20409
- hasher.update(source);
20410
- return hasher.digest("hex");
20411
- }
20412
- function createMutationFingerprint(input) {
20413
- const url = new URL(input.request.url);
20414
- const query = [...url.searchParams.entries()].sort(([leftKey, leftValue], [rightKey, rightValue]) => leftKey === rightKey ? compareCodePoints(leftValue, rightValue) : compareCodePoints(leftKey, rightKey));
20415
- const source = JSON.stringify({
20416
- body: canonicalize(input.body) ?? null,
20417
- contentType: input.request.headers.get("content-type") ?? "",
20418
- method: input.request.method,
20419
- pathname: url.pathname,
20420
- query
20421
- });
20422
- return sha256Hex(source);
20423
21752
  }
20424
21753
 
20425
21754
  // src/server/sync/response.ts
@@ -20560,6 +21889,15 @@ async function storeResponse(responseValue, set) {
20560
21889
  const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
20561
21890
  return storedResponseResult(headers, body, clone.status);
20562
21891
  }
21892
+ return storeResponseSync(responseValue, set);
21893
+ }
21894
+ function storeResponseSync(responseValue, set) {
21895
+ if (responseValue instanceof Response) {
21896
+ if (responseValue.body !== null) {
21897
+ return unreplayable();
21898
+ }
21899
+ return storedResponseResult(new Headers([...responseValue.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))), new Uint8Array, responseValue.status);
21900
+ }
20563
21901
  const headers = responseHeaders(set.headers);
20564
21902
  const statusResponse = unwrapStatusResponse(responseValue);
20565
21903
  const value = statusResponse?.value ?? responseValue;
@@ -20590,34 +21928,166 @@ function replayResponse(stored) {
20590
21928
  });
20591
21929
  }
20592
21930
 
20593
- // src/server/sync/plugin.ts
20594
- init_runtime();
20595
- var routeMetadata = new WeakMap;
20596
- var activeMutations = new WeakMap;
20597
- function hideTransportResponse(hook) {
20598
- return hook;
21931
+ // src/server/sync/atomic.ts
21932
+ var TRAILING_SLASH_PATTERN = /\/$/;
21933
+
21934
+ class RejectedMutation {
21935
+ value;
21936
+ constructor(value) {
21937
+ this.value = value;
21938
+ }
20599
21939
  }
20600
- function invalidationInputFromSync(input) {
20601
- if (input && typeof input === "object" && "invalidate" in input) {
20602
- return input.invalidate;
21940
+ function responseStatus(context, value) {
21941
+ if (value instanceof Response && value.status !== 200) {
21942
+ return value.status;
20603
21943
  }
20604
- return input;
21944
+ if (value instanceof ElysiaStatus2) {
21945
+ return value.status;
21946
+ }
21947
+ if (typeof context.set.status === "string") {
21948
+ return StatusMap2[context.set.status];
21949
+ }
21950
+ return context.set.status ?? 200;
20605
21951
  }
20606
- function isMutationMethod(method) {
20607
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
21952
+ function withStatus(original, value) {
21953
+ return original instanceof ElysiaStatus2 ? new ElysiaStatus2(original.status, value, original.headers) : value;
20608
21954
  }
20609
- function getIdempotencyKey(ctx) {
20610
- const fromCtxHeaders = ctx.headers["idempotency-key"];
20611
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
20612
- return fromCtxHeaders;
21955
+ function validateResult(execution, value) {
21956
+ if (value instanceof Error) {
21957
+ throw value;
20613
21958
  }
20614
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
20615
- return fromRequest || undefined;
21959
+ if (value instanceof Response) {
21960
+ return value;
21961
+ }
21962
+ const { app, context, adapter } = execution;
21963
+ const registeredPath = context.route ?? context.path;
21964
+ const strictPath = app["~config"]?.strictPath === true;
21965
+ const [match] = app.routes.toReversed().filter((entry) => entry.method === context.request.method || entry.method === "*").map((candidate) => {
21966
+ const paths = [candidate.path, encodeURI(candidate.path)];
21967
+ const exact = paths.includes(registeredPath);
21968
+ const loose = !strictPath && paths.some((path) => path.replace(TRAILING_SLASH_PATTERN, "") === registeredPath.replace(TRAILING_SLASH_PATTERN, ""));
21969
+ return { route: candidate, priority: exact ? 2 : Number(loose) };
21970
+ }).filter((entry) => entry.priority > 0).sort((left, right) => Number(right.route.method === context.request.method) - Number(left.route.method === context.request.method) || right.priority - left.priority);
21971
+ if (!match) {
21972
+ throw new Error("[furin] Could not resolve the effective mutation route for response validation.");
21973
+ }
21974
+ const { route } = match;
21975
+ const validators = Validator2.response(route?.hooks.response, {
21976
+ models: app["~ext"]?.models,
21977
+ normalize: app["~config"]?.normalize,
21978
+ sanitize: app["~config"]?.sanitize,
21979
+ schemas: route?.hooks.schemas?.flatMap((schema) => schema.response ? [schema.response] : [])
21980
+ });
21981
+ const validator = validators?.[responseStatus(context, value)];
21982
+ if (!validator) {
21983
+ return value;
21984
+ }
21985
+ const body = value instanceof ElysiaStatus2 ? value.response : value;
21986
+ const encoder = validator;
21987
+ const encoded = validator.mayReturnPromise ? validator.From?.(body, "response", adapter.transactionMode !== "sync") : encoder.EncodeFrom?.(body, "response");
21988
+ if (!(encoded instanceof Promise)) {
21989
+ return withStatus(value, encoded);
21990
+ }
21991
+ if (adapter.transactionMode === "sync") {
21992
+ throw new Error("[furin] Bun SQLite mutations require synchronous response validation.");
21993
+ }
21994
+ return encoded.then((result) => withStatus(value, result));
21995
+ }
21996
+ function prepare(execution, value, original) {
21997
+ const { context } = execution;
21998
+ const status = responseStatus(context, value);
21999
+ if (status < 200 || status >= 400) {
22000
+ throw new RejectedMutation(original);
22001
+ }
22002
+ const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
22003
+ execution.resolvedInvalidate = invalidate;
22004
+ appendQueryInvalidations(invalidate, context);
22005
+ const invalidations = [
22006
+ ...normalizedInvalidations(invalidate),
22007
+ ...pendingPathInvalidations(peekPendingInvalidations())
22008
+ ];
22009
+ if (invalidations.length > 0) {
22010
+ context.set.headers["x-furin-sync"] = "1";
22011
+ }
22012
+ const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => entry.type === "layout" ? `${entry.path}:layout` : entry.path);
22013
+ if (paths.length > 0) {
22014
+ context.set.headers["x-furin-revalidate"] = paths.join(",");
22015
+ }
22016
+ const finish = (stored) => {
22017
+ if (stored.kind === "unreplayable") {
22018
+ throw new Error("[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses.");
22019
+ }
22020
+ let { headers } = context.set;
22021
+ if (value instanceof ElysiaStatus2) {
22022
+ headers = { ...headers, ...value.headers };
22023
+ } else if (value instanceof Response) {
22024
+ headers = { ...headers, ...Object.fromEntries(value.headers) };
22025
+ }
22026
+ return {
22027
+ invalidations,
22028
+ response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
22029
+ value: original
22030
+ };
22031
+ };
22032
+ return execution.adapter.transactionMode === "sync" ? finish(storeResponseSync(value, context.set)) : storeResponse(value, context.set).then(finish);
20616
22033
  }
20617
- function supportsReplayBody(request) {
20618
- const contentType = request.headers.get("content-type")?.toLowerCase();
20619
- const mediaType = contentType?.split(";", 1)[0]?.trim();
20620
- return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
22034
+ function assertSynchronous(mode, value) {
22035
+ if (mode === "sync" && (value instanceof Promise || Object.prototype.toString.call(value) === "[object AsyncFunction]")) {
22036
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
22037
+ }
22038
+ }
22039
+ function invoke(execution, callback, tx) {
22040
+ assertSynchronous(execution.adapter.transactionMode, callback);
22041
+ const value = callback(tx);
22042
+ assertSynchronous(execution.adapter.transactionMode, value);
22043
+ if (value instanceof Promise) {
22044
+ return value.then(async (original) => prepare(execution, await validateResult(execution, original), original));
22045
+ }
22046
+ const encoded = validateResult(execution, value);
22047
+ return encoded instanceof Promise ? encoded.then((result) => prepare(execution, result, value)) : prepare(execution, encoded, value);
22048
+ }
22049
+ async function afterCommit(execution, result) {
22050
+ execution.onCommit(result);
22051
+ if (execution.resolvedInvalidate) {
22052
+ await runInvalidationRules(execution.resolvedInvalidate).catch(() => getLogger().warn("Sync cache invalidation failed after mutation; preserving the idempotent result"));
22053
+ appendPendingInvalidationHeader(execution.context.set);
22054
+ }
22055
+ const { notifier } = execution.runtime;
22056
+ if (result.cursor !== undefined) {
22057
+ notifier.publish(result.cursor).catch(() => {
22058
+ return;
22059
+ });
22060
+ }
22061
+ }
22062
+ async function executeAtomicMutation(execution, callback) {
22063
+ const { context } = execution;
22064
+ const previousSyncHeader = context.set.headers["x-furin-sync"];
22065
+ const previousPathHeader = context.set.headers["x-furin-revalidate"];
22066
+ const previousQueryHeader = context.set.headers["x-furin-queries"];
22067
+ let committed = false;
22068
+ try {
22069
+ const result = await execution.adapter.executeMutation(execution.lease, (tx) => invoke(execution, callback, tx));
22070
+ committed = true;
22071
+ await afterCommit(execution, result);
22072
+ return result.value;
22073
+ } catch (error) {
22074
+ if (!committed) {
22075
+ restoreHeader(context, "x-furin-sync", previousSyncHeader);
22076
+ restoreHeader(context, "x-furin-revalidate", previousPathHeader);
22077
+ restoreHeader(context, "x-furin-queries", previousQueryHeader);
22078
+ }
22079
+ if (error instanceof RejectedMutation) {
22080
+ return error.value;
22081
+ }
22082
+ throw error;
22083
+ }
22084
+ }
22085
+ function restoreHeader(context, key, value) {
22086
+ if (value === undefined) {
22087
+ delete context.set.headers[key];
22088
+ } else {
22089
+ context.set.headers[key] = value;
22090
+ }
20621
22091
  }
20622
22092
  function conflictResponse(reason) {
20623
22093
  const inProgress = reason === "in-progress";
@@ -20629,12 +22099,6 @@ function conflictResponse(reason) {
20629
22099
  status: 409
20630
22100
  });
20631
22101
  }
20632
- function leaseLostResponse() {
20633
- return Response.json({
20634
- code: "FURIN_SYNC_LEASE_LOST",
20635
- message: "The mutation lease was lost before its response could be committed."
20636
- }, { status: 503 });
20637
- }
20638
22102
  function normalizedInvalidations(input) {
20639
22103
  if (!input) {
20640
22104
  return [];
@@ -20654,8 +22118,122 @@ function normalizedInvalidations(input) {
20654
22118
  function pendingPathInvalidations(entries) {
20655
22119
  return entries.map((entry) => entry.endsWith(":layout") ? { kind: "path", path: entry.slice(0, -":layout".length), type: "layout" } : { kind: "path", path: entry, type: "page" });
20656
22120
  }
20657
- function furinSync(options) {
22121
+
22122
+ // src/server/sync/execution-error.ts
22123
+ class MutationLeaseLost extends Error {
22124
+ }
22125
+
22126
+ // src/server/sync/fingerprint.ts
22127
+ function compareCodePoints(left, right) {
22128
+ if (left === right) {
22129
+ return 0;
22130
+ }
22131
+ return left < right ? -1 : 1;
22132
+ }
22133
+ function canonicalize(value) {
22134
+ if (Array.isArray(value)) {
22135
+ return value.map(canonicalize);
22136
+ }
22137
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
22138
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
22139
+ }
22140
+ return value;
22141
+ }
22142
+ function sha256Hex(source) {
22143
+ const hasher = new Bun.CryptoHasher("sha256");
22144
+ hasher.update(source);
22145
+ return hasher.digest("hex");
22146
+ }
22147
+ function createMutationFingerprint(input) {
22148
+ const url = new URL(input.request.url);
22149
+ url.searchParams.sort();
22150
+ const query = [...url.searchParams.entries()];
22151
+ const source = JSON.stringify({
22152
+ body: canonicalize(input.body) ?? null,
22153
+ contentType: input.request.headers.get("content-type") ?? "",
22154
+ method: input.request.method,
22155
+ pathname: url.pathname,
22156
+ query
22157
+ });
22158
+ return sha256Hex(source);
22159
+ }
22160
+
22161
+ // src/server/sync/plugin.ts
22162
+ init_runtime();
22163
+ var routeMetadata = new WeakMap;
22164
+ var activeMutations = new WeakMap;
22165
+ var atomicCalls = new WeakSet;
22166
+ var atomicResponses = new WeakMap;
22167
+ function hideTransportResponse(hook) {
22168
+ return hook;
22169
+ }
22170
+ function invalidationInputFromSync(input) {
22171
+ if (input && typeof input === "object" && "invalidate" in input) {
22172
+ return input.invalidate;
22173
+ }
22174
+ if ("id" in input) {
22175
+ return;
22176
+ }
22177
+ return input;
22178
+ }
22179
+ function isMutationMethod(method) {
22180
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
22181
+ }
22182
+ function getIdempotencyKey(ctx) {
22183
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
22184
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
22185
+ return fromCtxHeaders;
22186
+ }
22187
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
22188
+ return fromRequest || undefined;
22189
+ }
22190
+ function supportsReplayBody(request) {
22191
+ const contentType = request.headers.get("content-type")?.toLowerCase();
22192
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
22193
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
22194
+ }
22195
+ function leaseLostResponse() {
22196
+ return Response.json({
22197
+ code: "FURIN_SYNC_LEASE_LOST",
22198
+ message: "The mutation lease was lost before its response could be committed."
22199
+ }, { status: 503 });
22200
+ }
22201
+ function createSyncPlugin(options) {
20658
22202
  const runtime = resolveSyncRuntime(options);
22203
+ const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
22204
+ function mutationFor(ctx) {
22205
+ const mutation = async (callback) => {
22206
+ const active = activeMutations.get(ctx.request);
22207
+ if (!(transactional && active)) {
22208
+ throw new Error("[furin] mutation() requires a transactional sync adapter and an enabled mutation route.");
22209
+ }
22210
+ if (atomicCalls.has(ctx.request)) {
22211
+ throw new Error("[furin] Call mutation() once and return its result from the handler.");
22212
+ }
22213
+ atomicCalls.add(ctx.request);
22214
+ try {
22215
+ return await executeAtomicMutation({
22216
+ adapter: transactional,
22217
+ app: syncValidationApp(ctx),
22218
+ context: ctx,
22219
+ lease: active.lease,
22220
+ invalidate: routeMetadata.get(ctx.request)?.invalidate,
22221
+ runtime,
22222
+ onCommit: (result) => atomicResponses.set(ctx.request, result)
22223
+ }, callback);
22224
+ } finally {
22225
+ if (atomicResponses.has(ctx.request)) {
22226
+ releaseMutation(ctx.request);
22227
+ } else {
22228
+ await abortMutation(ctx.request).catch(() => {
22229
+ return;
22230
+ });
22231
+ }
22232
+ atomicCalls.delete(ctx.request);
22233
+ }
22234
+ };
22235
+ return mutation;
22236
+ }
20659
22237
  async function beginMutation(ctx) {
20660
22238
  if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
20661
22239
  return;
@@ -20703,21 +22281,25 @@ function furinSync(options) {
20703
22281
  activeMutations.set(ctx.request, active);
20704
22282
  scheduleRenewal();
20705
22283
  }
20706
- async function abortMutation(request) {
22284
+ function releaseMutation(request) {
20707
22285
  const active = activeMutations.get(request);
20708
- if (!active) {
20709
- return;
20710
- }
20711
22286
  activeMutations.delete(request);
20712
- if (active.renewal) {
22287
+ if (active?.renewal) {
20713
22288
  clearTimeout(active.renewal);
20714
22289
  }
20715
- await runtime.adapter.abortMutation(active.lease);
22290
+ return active;
22291
+ }
22292
+ async function abortMutation(request) {
22293
+ const active = releaseMutation(request);
22294
+ if (active) {
22295
+ await runtime.adapter.abortMutation(active.lease);
22296
+ }
20716
22297
  }
20717
22298
  async function persistMutation(ctx, active) {
20718
22299
  const result = await storeResponse(ctx.responseValue, ctx.set);
20719
22300
  const manualPending = peekPendingInvalidations();
20720
- const invalidate = routeMetadata.get(ctx.request)?.invalidate;
22301
+ const invalidate = resolveSyncInvalidations(routeMetadata.get(ctx.request)?.invalidate, ctx, ctx.responseValue);
22302
+ appendQueryInvalidations(invalidate, ctx);
20721
22303
  const logger = getLogger();
20722
22304
  if (invalidate) {
20723
22305
  try {
@@ -20747,7 +22329,7 @@ function furinSync(options) {
20747
22329
  if (completion.kind === "lost") {
20748
22330
  return leaseLostResponse();
20749
22331
  }
20750
- const notificationAlreadyPublished = runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
22332
+ const notificationAlreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
20751
22333
  if (completion.cursor !== undefined && !notificationAlreadyPublished) {
20752
22334
  runtime.notifier.publish(completion.cursor).catch(() => {
20753
22335
  return;
@@ -20758,6 +22340,19 @@ function furinSync(options) {
20758
22340
  }
20759
22341
  }
20760
22342
  async function finishMutation(ctx) {
22343
+ const atomic = atomicResponses.get(ctx.request);
22344
+ atomicResponses.delete(ctx.request);
22345
+ atomicCalls.delete(ctx.request);
22346
+ if (atomic && ctx.responseValue === atomic.value) {
22347
+ if (atomic.value instanceof Response) {
22348
+ return atomic.value;
22349
+ }
22350
+ if (atomic.value instanceof ElysiaStatus3) {
22351
+ ctx.set.status = atomic.value.status;
22352
+ Object.assign(ctx.set.headers, atomic.value.headers);
22353
+ }
22354
+ return replayResponse(atomic.response);
22355
+ }
20761
22356
  const active = activeMutations.get(ctx.request);
20762
22357
  if (!active) {
20763
22358
  return;
@@ -20780,21 +22375,121 @@ function furinSync(options) {
20780
22375
  }
20781
22376
  }
20782
22377
  }
20783
- const beginMutationHook = hideTransportResponse(beginMutation);
20784
22378
  const finishMutationHook = hideTransportResponse(finishMutation);
20785
- return new Elysia11({ name: "furin-sync" }).beforeHandle("global", beginMutationHook).afterHandle("global", finishMutationHook).error("global", ({ request }) => abortMutation(request)).macro({
22379
+ const plugin = new Elysia11({ name: "furin-sync" }).derive("global", (ctx) => ({ mutation: mutationFor(ctx) })).beforeHandle("global", (context) => {
22380
+ if (isMutationMethod(context.request.method) && !routeMetadata.get(context.request)?.disabled) {
22381
+ prepareMutationHandler(context, () => beginMutation(context));
22382
+ }
22383
+ }).afterHandle("global", finishMutationHook).afterHandle("global", async (ctx) => {
22384
+ const read = routeMetadata.get(ctx.request)?.read;
22385
+ if (ctx.request.method !== "GET" || !read || !isSuccessfulMutationResponse({
22386
+ set: ctx.set,
22387
+ responseValue: ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
22388
+ })) {
22389
+ return;
22390
+ }
22391
+ const principal = await options.principal(ctx);
22392
+ if (principal.length === 0) {
22393
+ throw new Error("[furin] Sync principal must not be empty.");
22394
+ }
22395
+ const identity = {
22396
+ id: read.id,
22397
+ scope: typeof read.scope === "function" ? read.scope(ctx) : read.scope ?? {},
22398
+ session: new Bun.CryptoHasher("sha256").update(principal).digest("hex")
22399
+ };
22400
+ queryTag(identity);
22401
+ ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
22402
+ }).error("global", MutationLeaseLost, hideTransportResponse(() => Promise.resolve(leaseLostResponse()))).error("global", hideTransportResponse(async ({ request }) => {
22403
+ atomicResponses.delete(request);
22404
+ atomicCalls.delete(request);
22405
+ await abortMutation(request);
22406
+ })).macro({
20786
22407
  sync(input) {
20787
22408
  return {
20788
22409
  transform({ request }) {
20789
- routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
22410
+ routeMetadata.set(request, input === false ? { disabled: true } : {
22411
+ disabled: false,
22412
+ invalidate: invalidationInputFromSync(input),
22413
+ read: "id" in input ? input : undefined
22414
+ });
20790
22415
  }
20791
22416
  };
20792
22417
  }
20793
22418
  });
22419
+ return plugin;
22420
+ }
22421
+ function furinSync(options) {
22422
+ return (app) => {
22423
+ installMutationHandlers(app);
22424
+ if ("executeMutation" in options.adapter) {
22425
+ bindSyncValidation(app);
22426
+ }
22427
+ return app.use(createSyncPlugin(options));
22428
+ };
20794
22429
  }
20795
22430
 
20796
22431
  // src/server/sync/index.ts
20797
22432
  var furinSync2 = furinSync;
22433
+ // src/shared/await.tsx
22434
+ import { Component as Component2, createContext as createContext8, createElement as createElement10, use as use2, useMemo as useMemo2 } from "react";
22435
+ var AsyncErrorContext = createContext8(undefined);
22436
+ function useAsyncError() {
22437
+ return use2(AsyncErrorContext);
22438
+ }
22439
+ function useAsyncValue() {
22440
+ const ctx = use2(AwaitValueContext);
22441
+ if (!ctx) {
22442
+ throw new Error("useAsyncValue must be used inside <Await> children");
22443
+ }
22444
+ return use2(ctx.promise);
22445
+ }
22446
+ var AwaitValueContext = createContext8(undefined);
22447
+ function isAbortError(error) {
22448
+ return error instanceof Error && error.name === "AbortError";
22449
+ }
22450
+ function silenceAbortError(promise) {
22451
+ return promise.catch((error) => {
22452
+ if (isAbortError(error)) {
22453
+ return new Promise(() => {});
22454
+ }
22455
+ throw error;
22456
+ });
22457
+ }
22458
+
22459
+ class AsyncErrorBoundary extends Component2 {
22460
+ constructor(props) {
22461
+ super(props);
22462
+ this.state = { error: undefined, hasError: false, resolve: props.resolve };
22463
+ }
22464
+ static getDerivedStateFromProps(props, state) {
22465
+ if (props.resolve !== state.resolve) {
22466
+ return { error: undefined, hasError: false, resolve: props.resolve };
22467
+ }
22468
+ return null;
22469
+ }
22470
+ static getDerivedStateFromError(error) {
22471
+ return { error, hasError: true };
22472
+ }
22473
+ render() {
22474
+ const { hasError, error } = this.state;
22475
+ const { children, errorElement } = this.props;
22476
+ if (hasError) {
22477
+ if (errorElement === undefined) {
22478
+ throw error;
22479
+ }
22480
+ return createElement10(AsyncErrorContext.Provider, { value: error }, errorElement);
22481
+ }
22482
+ return children;
22483
+ }
22484
+ }
22485
+ function Await({ resolve, errorElement, children }) {
22486
+ const guardedResolve = useMemo2(() => silenceAbortError(resolve), [resolve]);
22487
+ return createElement10(AsyncErrorBoundary, { errorElement, resolve: guardedResolve }, createElement10(AwaitInner, { children, resolve: guardedResolve }));
22488
+ }
22489
+ function AwaitInner({ resolve, children }) {
22490
+ const value = use2(resolve);
22491
+ return createElement10(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
22492
+ }
20798
22493
 
20799
22494
  // src/furin.ts
20800
22495
  async function createProductionBrowserEventsPlugin(sync, deploymentTarget) {
@@ -20827,8 +22522,8 @@ function resolveClientDirFromEnv(dirName) {
20827
22522
  if (!envClientDir) {
20828
22523
  return null;
20829
22524
  }
20830
- const base = envClientDir.startsWith("/") ? envClientDir : resolve9(process.cwd(), envClientDir);
20831
- return dirName === "client" ? base : join7(dirname7(base), dirName);
22525
+ const base = envClientDir.startsWith("/") ? envClientDir : resolve10(process.cwd(), envClientDir);
22526
+ return dirName === "client" ? base : join7(dirname9(base), dirName);
20832
22527
  }
20833
22528
  function resolveClientDirFromModuleUrl(dirName) {
20834
22529
  try {
@@ -20840,7 +22535,7 @@ function resolveClientDirFromModuleUrl(dirName) {
20840
22535
  if (modulePath.includes("/$bunfs/")) {
20841
22536
  return null;
20842
22537
  }
20843
- const moduleClientDir = join7(dirname7(modulePath), dirName);
22538
+ const moduleClientDir = join7(dirname9(modulePath), dirName);
20844
22539
  if (existsSync8(join7(moduleClientDir, "index.html"))) {
20845
22540
  return moduleClientDir;
20846
22541
  }
@@ -20870,9 +22565,9 @@ function resolveClientDirFromCandidate(candidate, dirName) {
20870
22565
  if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
20871
22566
  return null;
20872
22567
  }
20873
- const absolute = candidate.startsWith("/") ? candidate : resolve9(process.cwd(), candidate);
22568
+ const absolute = candidate.startsWith("/") ? candidate : resolve10(process.cwd(), candidate);
20874
22569
  if (existsSync8(absolute)) {
20875
- const clientDir = join7(dirname7(absolute), dirName);
22570
+ const clientDir = join7(dirname9(absolute), dirName);
20876
22571
  if (existsSync8(join7(clientDir, "index.html"))) {
20877
22572
  return clientDir;
20878
22573
  }
@@ -20887,7 +22582,7 @@ function resolveClientDirFromPath(candidate, dirName) {
20887
22582
  for (const dir of pathEntries) {
20888
22583
  const fullPath = join7(dir, candidate);
20889
22584
  if (existsSync8(fullPath)) {
20890
- const clientDir = join7(dirname7(fullPath), dirName);
22585
+ const clientDir = join7(dirname9(fullPath), dirName);
20891
22586
  if (existsSync8(join7(clientDir, "index.html"))) {
20892
22587
  return clientDir;
20893
22588
  }
@@ -20896,7 +22591,7 @@ function resolveClientDirFromPath(candidate, dirName) {
20896
22591
  return null;
20897
22592
  }
20898
22593
  function resolveFallbackClientDir(dirName) {
20899
- const defaultClientDir = resolve9(process.cwd(), ".furin/build/bun", dirName);
22594
+ const defaultClientDir = resolve10(process.cwd(), ".furin/build/bun", dirName);
20900
22595
  if (existsSync8(join7(defaultClientDir, "index.html"))) {
20901
22596
  return defaultClientDir;
20902
22597
  }
@@ -20919,6 +22614,9 @@ async function setupProdTemplate(embedded, clientDir, instance) {
20919
22614
  setProductionTemplatePath(templatePath, instance);
20920
22615
  }
20921
22616
  async function setupCompiledTemplate(ctx, embedded, clientDir, instance) {
22617
+ if (ctx.preloadManifest) {
22618
+ setProductionPreloadManifest(ctx.preloadManifest, instance);
22619
+ }
20922
22620
  if (ctx.templateHtml === undefined) {
20923
22621
  await setupProdTemplate(embedded, clientDir, instance);
20924
22622
  return;
@@ -21099,9 +22797,12 @@ function wrapWithRequestScope(app) {
21099
22797
  });
21100
22798
  });
21101
22799
  }
21102
- function createFurinPlugin(app, hmrPrefix) {
22800
+ function createFurinPlugin(app, hmrPrefix, hasSync) {
21103
22801
  const scopedApp = wrapWithRequestScope(app);
21104
22802
  return (parentApp) => {
22803
+ if (hasSync) {
22804
+ bindSyncValidation(parentApp);
22805
+ }
21105
22806
  const mounted = parentApp.use(scopedApp);
21106
22807
  if (hmrPrefix !== undefined) {
21107
22808
  const parentConfig = Reflect.get(parentApp, "~config");
@@ -21129,7 +22830,7 @@ function createNativeRouteRenderer(prefix, routes, root, buildId, searchRoutes)
21129
22830
  const hasPrefix = prefix !== "" && (pathname === prefix || pathname.startsWith(`${prefix}/`));
21130
22831
  const logicalPath = hasPrefix ? pathname.slice(prefix.length) : pathname;
21131
22832
  const matched = matchNativeRoute(logicalPath || "/");
21132
- if (!matched) {
22833
+ if (!matched || IS_DEV && !existsSync8(matched.route.path)) {
21133
22834
  const listenerOrigin = context.server?.url?.origin;
21134
22835
  return renderRootNotFound(root, request, listenerOrigin);
21135
22836
  }
@@ -21200,10 +22901,10 @@ async function furin({
21200
22901
  const syncPath = resolveSyncPath(sync);
21201
22902
  const elysiaLoggerOptions = initializeLogger(logger);
21202
22903
  const cwd = process.cwd();
21203
- const paramPagesDir = resolve9(cwd, pagesDir ?? "src/pages");
22904
+ const paramPagesDir = resolve10(cwd, pagesDir ?? "src/pages");
21204
22905
  const ctx = getCompileContext(paramPagesDir, prefix);
21205
22906
  const loggerPlugin = createLoggerPlugin(prefix, syncPath, elysiaLoggerOptions, clientLogging === true || ctx?.clientLogging === true);
21206
- const resolvedPagesDir = ctx?.rootPath ? dirname7(ctx.rootPath) : paramPagesDir;
22907
+ const resolvedPagesDir = ctx?.rootPath ? dirname9(ctx.rootPath) : paramPagesDir;
21207
22908
  const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
21208
22909
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
21209
22910
  assertPrefixAvailable(prefix, normalizedPagesDir);
@@ -21212,7 +22913,7 @@ async function furin({
21212
22913
  configurePageCache(instance, ctx, pageCache);
21213
22914
  if (IS_DEV) {
21214
22915
  const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
21215
- const furinDir = resolve9(cwd, ".furin", instanceSlug);
22916
+ const furinDir = resolve10(cwd, ".furin", instanceSlug);
21216
22917
  await Promise.resolve().then(() => init_diagnostics());
21217
22918
  await Promise.resolve().then(() => init_graph());
21218
22919
  await Promise.resolve().then(() => init_plugin3());
@@ -21232,7 +22933,7 @@ async function furin({
21232
22933
  for (const sourcePath of sourcePaths) {
21233
22934
  let source;
21234
22935
  try {
21235
- source = readFileSync8(sourcePath, "utf8");
22936
+ source = readFileSync9(sourcePath, "utf8");
21236
22937
  } catch (error) {
21237
22938
  console.warn(`[furin] Could not read ${sourcePath} for route config autofix: ${error instanceof Error ? error.message : String(error)}`);
21238
22939
  continue;
@@ -21258,7 +22959,40 @@ async function furin({
21258
22959
  let matchNavigationData = buildRouteMatcher(initialSnapshot.routes);
21259
22960
  navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
21260
22961
  await Promise.resolve().then(() => init_hydrate());
21261
- const writeCurrentDevFiles = (snapshot) => {
22962
+ await Promise.resolve().then(() => init_transform_client());
22963
+ let serverSourceVersion = 0;
22964
+ let serverDataSignatures = new Map;
22965
+ let serverSourcePaths;
22966
+ const writeCurrentDevFiles = (snapshot, changedSources) => {
22967
+ const paths = [
22968
+ ...new Set([
22969
+ snapshot.root.path,
22970
+ ...snapshot.routes.flatMap((route) => [
22971
+ route.path,
22972
+ ...route.routeChain.flatMap((entry) => entry.sourcePath ? [entry.sourcePath] : [])
22973
+ ])
22974
+ ])
22975
+ ].toSorted();
22976
+ const nextPaths = JSON.stringify(paths);
22977
+ const nextSignatures = new Map(paths.map((path) => {
22978
+ let signature;
22979
+ try {
22980
+ signature = getHmrDataSignature(readFileSync9(path, "utf8"), path);
22981
+ if (signature.startsWith("external:")) {
22982
+ signature = graph.sourceVersion(path);
22983
+ }
22984
+ } catch {
22985
+ signature = graph.sourceVersion(path);
22986
+ }
22987
+ return [path, signature];
22988
+ }));
22989
+ const changedPaths = new Set(changedSources);
22990
+ const importsChanged = paths.some((path) => !changedPaths.has(path) && serverDataSignatures.get(path) !== nextSignatures.get(path));
22991
+ if (importsChanged && serverSourcePaths === nextPaths) {
22992
+ serverSourceVersion += 1;
22993
+ }
22994
+ serverSourcePaths = nextPaths;
22995
+ serverDataSignatures = nextSignatures;
21262
22996
  writeDevFiles(snapshot.routes, {
21263
22997
  basePath: prefix,
21264
22998
  clientLogging: clientLogging ?? false,
@@ -21266,9 +23000,9 @@ async function furin({
21266
23000
  publicPath: `${prefix}/_client/`,
21267
23001
  rootLayout: snapshot.root.path,
21268
23002
  skipRouteTypes: prefix !== ""
21269
- }, cwd);
23003
+ }, cwd, String(serverSourceVersion));
21270
23004
  };
21271
- writeCurrentDevFiles(initialSnapshot);
23005
+ writeCurrentDevFiles(initialSnapshot, []);
21272
23006
  graph.commit(initialSnapshot);
21273
23007
  const hmrEntry = (await import(join7(furinDir, "index.html"))).default;
21274
23008
  const refreshDevelopmentRoutes = (changedSources) => withInstance(instance, async () => {
@@ -21277,8 +23011,12 @@ async function furin({
21277
23011
  const previousSnapshot = currentSnapshot();
21278
23012
  const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
21279
23013
  const next = await loadDevelopmentRoutes(resolvedPagesDir);
21280
- const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
21281
- writeCurrentDevFiles(nextSnapshot);
23014
+ const nextRoutes = next.routes.map((route) => route.routeChain.length > 0 ? route : {
23015
+ ...route,
23016
+ tags: previousSnapshot.routes.find((previous) => previous.path === route.path)?.tags
23017
+ });
23018
+ const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, nextRoutes);
23019
+ writeCurrentDevFiles(nextSnapshot, changedSources);
21282
23020
  graph.commit(nextSnapshot);
21283
23021
  matchNavigationData = buildRouteMatcher(nextSnapshot.routes);
21284
23022
  const diagnostics = devDiagnosticStore(instance);
@@ -21299,7 +23037,7 @@ async function furin({
21299
23037
  throw error;
21300
23038
  }
21301
23039
  });
21302
- const publicDir = resolve9(cwd, "public");
23040
+ const publicDir = resolve10(cwd, "public");
21303
23041
  const publicExists = existsSync8(publicDir);
21304
23042
  let routeTopologyWatcher;
21305
23043
  navigationDataRefreshers.set(instance, async () => {
@@ -21352,7 +23090,7 @@ async function furin({
21352
23090
  return await dispatchNativeRoute(notFoundContext);
21353
23091
  }));
21354
23092
  registerInstance(instance);
21355
- return createFurinPlugin(devApp, prefix);
23093
+ return createFurinPlugin(devApp, prefix, Boolean(sync));
21356
23094
  }
21357
23095
  if (!ctx) {
21358
23096
  throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
@@ -21394,7 +23132,7 @@ async function furin({
21394
23132
  await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
21395
23133
  }).use(await createProductionAssetsPlugin(ctx, embedded, clientDir)).use(await createProductionBrowserEventsPlugin(sync, ctx?.deploymentTarget)).use(sync ? (await Promise.resolve().then(() => (init_stream(), exports_stream))).createSyncChangesPlugin(sync) : new Elysia13).decorate(FURIN_RENDER_DECORATOR, dispatchNativeRoute).use(ctx.nativeRoutes).use(createNotFoundHandling(prefix, routes, root));
21396
23134
  registerInstance(instance);
21397
- return createFurinPlugin(prodApp, undefined);
23135
+ return createFurinPlugin(prodApp, undefined, Boolean(sync));
21398
23136
  }
21399
23137
  function createNotFoundHandling(prefix, routes, root, tryNativeDispatch) {
21400
23138
  const app = new Elysia13;