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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
package/dist/furin.js CHANGED
@@ -258,6 +258,12 @@ function routeSegmentToPattern(segment) {
258
258
  }
259
259
  return dynamic.catchAll ? "*" : `:${dynamic.name}`;
260
260
  }
261
+ function isRouteGroup(segment) {
262
+ return ROUTE_GROUP_RE.test(segment);
263
+ }
264
+ function routePatternKey(pattern) {
265
+ return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
266
+ }
261
267
  function filePathToPattern(path) {
262
268
  const parts = path.replaceAll("\\", "/").split("/");
263
269
  const segments = [];
@@ -269,6 +275,9 @@ function filePathToPattern(path) {
269
275
  }
270
276
  const isFile = idx === lastIndex;
271
277
  const name = isFile ? parse(part).name : part;
278
+ if (!isFile && isRouteGroup(name)) {
279
+ continue;
280
+ }
272
281
  if (isFile && name === "index") {
273
282
  continue;
274
283
  }
@@ -363,9 +372,11 @@ function buildRouteMatcher(routes) {
363
372
  return null;
364
373
  };
365
374
  }
366
- var DYNAMIC_PARAMETER_NAME_RE, REGEX_META_CHARS_RE;
375
+ var DYNAMIC_PARAMETER_NAME_RE, ROUTE_GROUP_RE, DYNAMIC_ROUTE_SEGMENT_RE, REGEX_META_CHARS_RE;
367
376
  var init_patterns = __esm(() => {
368
377
  DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
378
+ ROUTE_GROUP_RE = /^\([^()]+\)$/;
379
+ DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
369
380
  REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
370
381
  });
371
382
 
@@ -759,6 +770,7 @@ function withMetadata(metadata) {
759
770
  return {
760
771
  mode: metadata.mode,
761
772
  revalidate: metadata.revalidate,
773
+ remountDeps: metadata.remountDeps,
762
774
  staticParams: metadata.staticParams,
763
775
  tags: metadata.tags
764
776
  };
@@ -787,11 +799,13 @@ function assertPageRequestLoaderMode(metadata, requestLoader) {
787
799
  }
788
800
 
789
801
  class NoSchemaChain {
802
+ headFunction;
790
803
  metadata;
791
804
  requestLoaderFunction;
792
- constructor(metadata, requestLoader) {
805
+ constructor(metadata, requestLoader, head) {
793
806
  this.metadata = metadata;
794
807
  this.requestLoaderFunction = requestLoader;
808
+ this.headFunction = head;
795
809
  }
796
810
  requestLoader(requestLoader) {
797
811
  return new NoSchemaChain(this.metadata, requestLoader);
@@ -802,6 +816,9 @@ class NoSchemaChain {
802
816
  loader(loader) {
803
817
  return new LoadedNoSchema(this.metadata, loader, undefined, this.requestLoaderFunction);
804
818
  }
819
+ head(head) {
820
+ return new NoSchemaChain(this.metadata, this.requestLoaderFunction, head);
821
+ }
805
822
  page(component, ..._requestLoaderCheck) {
806
823
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
807
824
  return {
@@ -809,6 +826,7 @@ class NoSchemaChain {
809
826
  ...withMetadata(this.metadata),
810
827
  component,
811
828
  elysia: registerPlain(undefined),
829
+ head: this.headFunction,
812
830
  page: component,
813
831
  requestLoader: this.requestLoaderFunction
814
832
  };
@@ -819,6 +837,7 @@ class NoSchemaChain {
819
837
  ...withMetadata(this.metadata),
820
838
  component,
821
839
  elysia: registerLayout(undefined, undefined, undefined),
840
+ head: this.headFunction,
822
841
  layout: component,
823
842
  requestLoader: this.requestLoaderFunction
824
843
  };
@@ -849,10 +868,7 @@ class LoadedNoSchema {
849
868
  head: this.headFunction,
850
869
  loader: this.loaderFunction,
851
870
  page: component,
852
- requestLoader: this.requestLoaderFunction,
853
- useLoaderData: () => {
854
- return;
855
- }
871
+ requestLoader: this.requestLoaderFunction
856
872
  };
857
873
  }
858
874
  layout(component) {
@@ -864,22 +880,21 @@ class LoadedNoSchema {
864
880
  head: this.headFunction,
865
881
  layout: component,
866
882
  loader: this.loaderFunction,
867
- requestLoader: this.requestLoaderFunction,
868
- useLoaderData: () => {
869
- return;
870
- }
883
+ requestLoader: this.requestLoaderFunction
871
884
  };
872
885
  }
873
886
  }
874
887
 
875
888
  class QuerySchemaChain {
889
+ headFunction;
876
890
  metadata;
877
891
  querySchema;
878
892
  requestLoaderFunction;
879
- constructor(metadata, querySchema, requestLoader) {
893
+ constructor(metadata, querySchema, requestLoader, head) {
880
894
  this.metadata = metadata;
881
895
  this.querySchema = querySchema;
882
896
  this.requestLoaderFunction = requestLoader;
897
+ this.headFunction = head;
883
898
  }
884
899
  requestLoader(requestLoader) {
885
900
  return new QuerySchemaChain(this.metadata, this.querySchema, requestLoader);
@@ -890,6 +905,9 @@ class QuerySchemaChain {
890
905
  loader(loader) {
891
906
  return new LoadedQuerySchema(this.metadata, this.querySchema, loader, undefined, this.requestLoaderFunction);
892
907
  }
908
+ head(head) {
909
+ return new QuerySchemaChain(this.metadata, this.querySchema, this.requestLoaderFunction, head);
910
+ }
893
911
  page(component, ..._requestLoaderCheck) {
894
912
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
895
913
  return {
@@ -897,6 +915,7 @@ class QuerySchemaChain {
897
915
  ...withMetadata(this.metadata),
898
916
  component,
899
917
  elysia: registerQuery(this.querySchema, undefined),
918
+ head: this.headFunction,
900
919
  page: component,
901
920
  requestLoader: this.requestLoaderFunction,
902
921
  schemas: { query: this.querySchema }
@@ -908,6 +927,7 @@ class QuerySchemaChain {
908
927
  ...withMetadata(this.metadata),
909
928
  component,
910
929
  elysia: registerLayout(undefined, this.querySchema, undefined),
930
+ head: this.headFunction,
911
931
  layout: component,
912
932
  requestLoader: this.requestLoaderFunction,
913
933
  schemas: { query: this.querySchema }
@@ -942,10 +962,7 @@ class LoadedQuerySchema {
942
962
  loader: this.loaderFunction,
943
963
  page: component,
944
964
  requestLoader: this.requestLoaderFunction,
945
- schemas: { query: this.querySchema },
946
- useLoaderData: () => {
947
- return;
948
- }
965
+ schemas: { query: this.querySchema }
949
966
  };
950
967
  }
951
968
  layout(component) {
@@ -958,24 +975,23 @@ class LoadedQuerySchema {
958
975
  layout: component,
959
976
  loader: this.loaderFunction,
960
977
  requestLoader: this.requestLoaderFunction,
961
- schemas: { query: this.querySchema },
962
- useLoaderData: () => {
963
- return;
964
- }
978
+ schemas: { query: this.querySchema }
965
979
  };
966
980
  }
967
981
  }
968
982
 
969
983
  class SchemaChain {
984
+ headFunction;
970
985
  metadata;
971
986
  paramsSchema;
972
987
  querySchema;
973
988
  requestLoaderFunction;
974
- constructor(metadata, paramsSchema, querySchema, requestLoader) {
989
+ constructor(metadata, paramsSchema, querySchema, requestLoader, head) {
975
990
  this.metadata = metadata;
976
991
  this.paramsSchema = paramsSchema;
977
992
  this.querySchema = querySchema;
978
993
  this.requestLoaderFunction = requestLoader;
994
+ this.headFunction = head;
979
995
  }
980
996
  requestLoader(requestLoader) {
981
997
  return new SchemaChain(this.metadata, this.paramsSchema, this.querySchema, requestLoader);
@@ -986,6 +1002,9 @@ class SchemaChain {
986
1002
  loader(loader) {
987
1003
  return new LoadedSchema(this.metadata, this.paramsSchema, this.querySchema, loader, undefined, this.requestLoaderFunction);
988
1004
  }
1005
+ head(head) {
1006
+ return new SchemaChain(this.metadata, this.paramsSchema, this.querySchema, this.requestLoaderFunction, head);
1007
+ }
989
1008
  page(component, ..._requestLoaderCheck) {
990
1009
  assertPageRequestLoaderMode(this.metadata, this.requestLoaderFunction);
991
1010
  return {
@@ -993,6 +1012,7 @@ class SchemaChain {
993
1012
  ...withMetadata(this.metadata),
994
1013
  component,
995
1014
  elysia: registerSchema(this.paramsSchema, this.querySchema, undefined),
1015
+ head: this.headFunction,
996
1016
  page: component,
997
1017
  requestLoader: this.requestLoaderFunction,
998
1018
  schemas: { params: this.paramsSchema, query: this.querySchema }
@@ -1004,6 +1024,7 @@ class SchemaChain {
1004
1024
  ...withMetadata(this.metadata),
1005
1025
  component,
1006
1026
  elysia: registerLayout(this.paramsSchema, this.querySchema, undefined),
1027
+ head: this.headFunction,
1007
1028
  layout: component,
1008
1029
  requestLoader: this.requestLoaderFunction,
1009
1030
  schemas: { params: this.paramsSchema, query: this.querySchema }
@@ -1040,10 +1061,7 @@ class LoadedSchema {
1040
1061
  loader: this.loaderFunction,
1041
1062
  page: component,
1042
1063
  requestLoader: this.requestLoaderFunction,
1043
- schemas: { params: this.paramsSchema, query: this.querySchema },
1044
- useLoaderData: () => {
1045
- return;
1046
- }
1064
+ schemas: { params: this.paramsSchema, query: this.querySchema }
1047
1065
  };
1048
1066
  }
1049
1067
  layout(component) {
@@ -1056,10 +1074,7 @@ class LoadedSchema {
1056
1074
  layout: component,
1057
1075
  loader: this.loaderFunction,
1058
1076
  requestLoader: this.requestLoaderFunction,
1059
- schemas: { params: this.paramsSchema, query: this.querySchema },
1060
- useLoaderData: () => {
1061
- return;
1062
- }
1077
+ schemas: { params: this.paramsSchema, query: this.querySchema }
1063
1078
  };
1064
1079
  }
1065
1080
  }
@@ -1329,6 +1344,9 @@ class AutoInvalidateRegistry {
1329
1344
  }
1330
1345
  return [...paths];
1331
1346
  }
1347
+ tagsForPath(path) {
1348
+ return [...this.pathToTags.get(path) ?? []];
1349
+ }
1332
1350
  unregisterPath(urlPath, owner) {
1333
1351
  if (owner === undefined) {
1334
1352
  this.pathOwners.delete(urlPath);
@@ -1365,7 +1383,7 @@ var init_registry = __esm(() => {
1365
1383
  // src/server/dev/graph.ts
1366
1384
  import { randomUUID } from "crypto";
1367
1385
  import { readFileSync, statSync } from "fs";
1368
- import { dirname as dirname2, extname, resolve as resolve2 } from "path";
1386
+ import { dirname as dirname2, extname, isAbsolute as isAbsolute2, resolve as resolve2 } from "path";
1369
1387
  function normalizeModulePath(path) {
1370
1388
  return path.replaceAll("\\", "/");
1371
1389
  }
@@ -1378,7 +1396,7 @@ function resolveDevSourceImports(source, path, loader) {
1378
1396
  const isSourceExtension = [".js", ".jsx", ".ts", ".tsx"].includes(extension);
1379
1397
  const absolute = imported.path.startsWith(".") && extension && !isSourceExtension ? resolve2(dirname2(path), imported.path) : Bun.resolveSync(imported.path, dirname2(path));
1380
1398
  const resolved = normalizeModulePath(absolute);
1381
- if (!resolved.includes("/node_modules/")) {
1399
+ if (isAbsolute2(resolved) && !resolved.includes("/node_modules/")) {
1382
1400
  imports.push(resolved);
1383
1401
  }
1384
1402
  } catch {}
@@ -1524,6 +1542,19 @@ class DevGraph {
1524
1542
  const normalizedTo = normalizeModulePath(to);
1525
1543
  return this.importChain(from, normalizedTo).includes(normalizedTo);
1526
1544
  }
1545
+ sourceDependencies(from) {
1546
+ const pending = [normalizeModulePath(from)];
1547
+ const visited = new Set;
1548
+ while (pending.length > 0) {
1549
+ const path = pending.pop();
1550
+ if (path === undefined || visited.has(path)) {
1551
+ continue;
1552
+ }
1553
+ visited.add(path);
1554
+ pending.push(...this.#dependencies.get(path) ?? []);
1555
+ }
1556
+ return [...visited];
1557
+ }
1527
1558
  clearSourceErrors(path) {
1528
1559
  const modulePath = normalizeModulePath(path);
1529
1560
  for (const [message, positions] of this.#sourceErrors) {
@@ -1761,7 +1792,14 @@ function matchesPath(urlPath, path, type) {
1761
1792
  }
1762
1793
  function createRouteCache(options) {
1763
1794
  const store = new Map;
1795
+ const generations = new Map;
1764
1796
  const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
1797
+ const invalidateGenerations = (key) => {
1798
+ for (const generation of generations.get(key) ?? []) {
1799
+ generation.valid = false;
1800
+ }
1801
+ generations.delete(key);
1802
+ };
1765
1803
  const evictOldest = () => {
1766
1804
  if (options.maxSize === undefined || store.size <= options.maxSize) {
1767
1805
  return;
@@ -1772,6 +1810,7 @@ function createRouteCache(options) {
1772
1810
  }
1773
1811
  };
1774
1812
  const deleteEntry = (key) => {
1813
+ invalidateGenerations(key);
1775
1814
  const entry = store.get(key);
1776
1815
  if (entry === undefined) {
1777
1816
  return false;
@@ -1781,7 +1820,20 @@ function createRouteCache(options) {
1781
1820
  return true;
1782
1821
  };
1783
1822
  return {
1823
+ captureGeneration(key) {
1824
+ const generation = { valid: true };
1825
+ let pending = generations.get(key);
1826
+ if (pending === undefined) {
1827
+ pending = new Set;
1828
+ generations.set(key, pending);
1829
+ }
1830
+ pending.add(generation);
1831
+ return generation;
1832
+ },
1784
1833
  clear() {
1834
+ for (const key of generations.keys()) {
1835
+ invalidateGenerations(key);
1836
+ }
1785
1837
  for (const key of [...store.keys()]) {
1786
1838
  deleteEntry(key);
1787
1839
  }
@@ -1807,14 +1859,15 @@ function createRouteCache(options) {
1807
1859
  invalidatePath(path, type) {
1808
1860
  let deleted = false;
1809
1861
  const purgedPaths = [];
1810
- for (const key of [...store.keys()]) {
1862
+ for (const key of new Set([...store.keys(), ...generations.keys()])) {
1811
1863
  const urlPath = pathFromKey(key);
1812
1864
  if (urlPath === null || !matchesPath(urlPath, path, type)) {
1813
1865
  continue;
1814
1866
  }
1815
- deleteEntry(key);
1816
- deleted = true;
1817
- purgedPaths.push(urlPath);
1867
+ if (deleteEntry(key)) {
1868
+ deleted = true;
1869
+ purgedPaths.push(urlPath);
1870
+ }
1818
1871
  }
1819
1872
  return { deleted, purgedPaths: [...new Set(purgedPaths)] };
1820
1873
  },
@@ -1822,6 +1875,13 @@ function createRouteCache(options) {
1822
1875
  return store.keys();
1823
1876
  },
1824
1877
  name: options.name,
1878
+ releaseGeneration(key, generation) {
1879
+ const pending = generations.get(key);
1880
+ pending?.delete(generation);
1881
+ if (pending?.size === 0) {
1882
+ generations.delete(key);
1883
+ }
1884
+ },
1825
1885
  set(key, entry) {
1826
1886
  const previous = store.get(key);
1827
1887
  if (previous !== undefined) {
@@ -2265,7 +2325,7 @@ var init_instrumentation = __esm(() => {
2265
2325
  init_request_context();
2266
2326
  });
2267
2327
 
2268
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
2328
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
2269
2329
  function elapsedMs(startTime) {
2270
2330
  return Math.max(0, Date.now() - startTime);
2271
2331
  }
@@ -2406,7 +2466,7 @@ var init_utils = __esm(() => {
2406
2466
  _isoDate = /* @__PURE__ */ new Date;
2407
2467
  });
2408
2468
 
2409
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
2469
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
2410
2470
  function normalizeRedactPathPattern(pattern) {
2411
2471
  if (!pattern.includes("*") && !pattern.includes("."))
2412
2472
  return `**.${pattern}`;
@@ -2715,7 +2775,7 @@ var init_redact_C7FmdhwI = __esm(() => {
2715
2775
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
2716
2776
  });
2717
2777
 
2718
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
2778
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
2719
2779
  function logPluginError(name, hook, err) {
2720
2780
  console.error(`[evlog/${name}] ${hook} failed:`, err);
2721
2781
  }
@@ -2885,7 +2945,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
2885
2945
  globalConfig = getRegistry().config;
2886
2946
  });
2887
2947
 
2888
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
2948
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
2889
2949
  function pushTreeSpacer(children) {
2890
2950
  children.push(PRETTY_ERROR_TREE_SPACER);
2891
2951
  }
@@ -3186,7 +3246,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
3186
3246
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
3187
3247
  });
3188
3248
 
3189
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
3249
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
3190
3250
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
3191
3251
  const compact = partial.compact ?? (inDev && pretty);
3192
3252
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -3239,7 +3299,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
3239
3299
  };
3240
3300
  });
3241
3301
 
3242
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
3302
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
3243
3303
  function hasWideEventPublisher() {
3244
3304
  return publisher !== null;
3245
3305
  }
@@ -3255,7 +3315,7 @@ function publishWideEvent(event) {
3255
3315
  var publisher = null;
3256
3316
  var init_wideEventChannel_BUDW48oP = () => {};
3257
3317
 
3258
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
3318
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
3259
3319
  function isEvlogError(error) {
3260
3320
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
3261
3321
  }
@@ -3264,7 +3324,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
3264
3324
  evlogErrorBrand = Symbol.for("evlog.error.brand");
3265
3325
  });
3266
3326
 
3267
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
3327
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
3268
3328
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
3269
3329
  var init_error = __esm(() => {
3270
3330
  init_utils();
@@ -3373,7 +3433,7 @@ var init_error = __esm(() => {
3373
3433
  });
3374
3434
  });
3375
3435
 
3376
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
3436
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
3377
3437
  function extractSafeHeaders(headers) {
3378
3438
  const raw = {};
3379
3439
  headers.forEach((value, key) => {
@@ -3394,7 +3454,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
3394
3454
  init_utils();
3395
3455
  });
3396
3456
 
3397
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
3457
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
3398
3458
  function writePrettyStdout(text) {
3399
3459
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
3400
3460
  }
@@ -4316,12 +4376,12 @@ var init_audit_C8euLMvu = __esm(() => {
4316
4376
  initLogger(__EVLOG_CONFIG__);
4317
4377
  });
4318
4378
 
4319
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
4379
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
4320
4380
  var init_dist = __esm(() => {
4321
4381
  init_audit_C8euLMvu();
4322
4382
  });
4323
4383
 
4324
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
4384
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
4325
4385
  function shouldDeferEmitForResponse(response) {
4326
4386
  if (!response.body)
4327
4387
  return false;
@@ -4401,7 +4461,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
4401
4461
  }
4402
4462
  var init_streamResponse_OlirMA5P = () => {};
4403
4463
 
4404
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
4464
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
4405
4465
  function extractErrorStatus(error) {
4406
4466
  if (error === null || typeof error !== "object")
4407
4467
  return 500;
@@ -4411,7 +4471,7 @@ function extractErrorStatus(error) {
4411
4471
  }
4412
4472
  var init_errors_CL8dDgIi = () => {};
4413
4473
 
4414
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
4474
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
4415
4475
  function shouldLog(path, include, exclude) {
4416
4476
  if (exclude && exclude.length > 0) {
4417
4477
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -4439,7 +4499,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
4439
4499
  init_utils();
4440
4500
  });
4441
4501
 
4442
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
4502
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
4443
4503
  function resolveMiddlewarePluginRunner(options) {
4444
4504
  const global2 = getGlobalPluginRunner();
4445
4505
  const local = options.plugins;
@@ -4634,7 +4694,7 @@ var init_middleware_fam3VyaL = __esm(() => {
4634
4694
  runnerCache = /* @__PURE__ */ new WeakMap;
4635
4695
  });
4636
4696
 
4637
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
4697
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
4638
4698
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
4639
4699
  const log = parent;
4640
4700
  log.fork = (label, fn) => {
@@ -4737,7 +4797,7 @@ var init_integration_CGD18W8r = __esm(() => {
4737
4797
  init_middleware_fam3VyaL();
4738
4798
  });
4739
4799
 
4740
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
4800
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
4741
4801
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
4742
4802
  function createLoggerStorage(contextHint, id = contextHint) {
4743
4803
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -4756,7 +4816,7 @@ var init_storage = __esm(() => {
4756
4816
  init_globalRegistry_Bh3bIGwA();
4757
4817
  });
4758
4818
 
4759
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
4819
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
4760
4820
  var init_toolkit = __esm(() => {
4761
4821
  init_streamResponse_OlirMA5P();
4762
4822
  init_integration_CGD18W8r();
@@ -4936,23 +4996,10 @@ function deleteISRCache(key) {
4936
4996
  return instanceIsrCache().cache.delete(key);
4937
4997
  }
4938
4998
  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;
4999
+ return instanceIsrCache().cache.captureGeneration(key);
4948
5000
  }
4949
5001
  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
- }
5002
+ instanceIsrCache().cache.releaseGeneration(key, generation);
4956
5003
  }
4957
5004
  function setISRCacheIfGenerationUnchanged(key, entry, generation) {
4958
5005
  releaseISRCacheGeneration(key, generation);
@@ -4971,22 +5018,10 @@ var init_isr = __esm(() => {
4971
5018
  init_isr_ssg();
4972
5019
  init_registry2();
4973
5020
  instanceIsrCache = instanceSlot((instance) => {
4974
- const generations = new Map;
4975
5021
  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
- });
5022
+ const cache = createHtmlRouteCache("isr");
4988
5023
  registerCacheInvalidator(cache, instance);
4989
- return { cache, generations, pendingRevalidations };
5024
+ return { cache, pendingRevalidations };
4990
5025
  });
4991
5026
  isrCache = createStoreView(() => instanceIsrCache().cache.store);
4992
5027
  });
@@ -5605,33 +5640,26 @@ function parseChangeQuery(request) {
5605
5640
  }
5606
5641
  return { after, limit };
5607
5642
  }
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
5643
  function createSyncChangesPlugin(options) {
5620
5644
  const syncPath = options.path ?? defaultSyncPath;
5621
5645
  const runtime = resolveSyncRuntime(syncRuntimeOptions(options));
5622
- return new Elysia6({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async ({ request, set }) => {
5646
+ return new Elysia6({ name: `furin-sync-changes-${syncPath}` }).get(`${syncPath}/changes`, async (context) => {
5647
+ const { request, set } = context;
5623
5648
  set.headers["cache-control"] = "no-store";
5624
5649
  const query = parseChangeQuery(request);
5625
5650
  if ("error" in query) {
5626
5651
  return query.error;
5627
5652
  }
5628
- const page = await runtime.adapter.readChanges(query);
5653
+ const principal = await options.principal(context);
5654
+ if (principal.length === 0) {
5655
+ return new Response("Unauthorized", { status: 401 });
5656
+ }
5657
+ const cursor = await runtime.adapter.currentCursor();
5629
5658
  return {
5630
- ...page,
5631
- changes: page.changes.map((change) => ({
5632
- cursor: change.cursor,
5633
- invalidations: clientInvalidations(change)
5634
- }))
5659
+ changes: [],
5660
+ cursor,
5661
+ hasMore: false,
5662
+ reset: query.after !== undefined && query.after !== cursor
5635
5663
  };
5636
5664
  });
5637
5665
  }
@@ -6483,7 +6511,7 @@ var init_symbolicate = __esm(() => {
6483
6511
  // src/server/dev/diagnostics.ts
6484
6512
  import { randomUUID as randomUUID2 } from "crypto";
6485
6513
  import { realpathSync } from "fs";
6486
- import { isAbsolute as isAbsolute2, relative as relative4 } from "path";
6514
+ import { isAbsolute as isAbsolute3, relative as relative4 } from "path";
6487
6515
  import { fileURLToPath } from "url";
6488
6516
  function messageOf(error) {
6489
6517
  return error instanceof Error ? error.message : String(error);
@@ -6553,7 +6581,7 @@ function explicitLocation(error, entryPath) {
6553
6581
  }
6554
6582
  return {
6555
6583
  column: position.column,
6556
- file: typeof position.file === "string" && (isAbsolute2(position.file) || position.file.startsWith("file://")) ? sourceFilePath(position.file) : entryPath,
6584
+ file: typeof position.file === "string" && (isAbsolute3(position.file) || position.file.startsWith("file://")) ? sourceFilePath(position.file) : entryPath,
6557
6585
  line: position.line
6558
6586
  };
6559
6587
  }
@@ -6972,6 +7000,7 @@ function adaptDefinedPage(route, parent) {
6972
7000
  params: route.schemas?.params,
6973
7001
  parent,
6974
7002
  query: route.schemas?.query,
7003
+ remountDeps: route.remountDeps,
6975
7004
  requestLoader: route.requestLoader
6976
7005
  },
6977
7006
  component,
@@ -7144,9 +7173,6 @@ async function scanRootLayout(pagesDir) {
7144
7173
  route: rootRoute
7145
7174
  };
7146
7175
  }
7147
- function routePatternKey(pattern) {
7148
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
7149
- }
7150
7176
  function isConventionFileName(name) {
7151
7177
  return CONVENTION_FILE_NAMES.includes(name);
7152
7178
  }
@@ -7195,7 +7221,7 @@ async function scanPageFiles(pagesDir, root) {
7195
7221
  const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
7196
7222
  devRoute.notFound = notFound;
7197
7223
  devRoute.error = errorComponent;
7198
- devRoute.segmentBoundaries = segmentBoundaries;
7224
+ devRoute.segmentBoundaries = alignSegmentBoundaryDepths(segmentBoundaries, devRoute.routeChain);
7199
7225
  routes.push(devRoute);
7200
7226
  continue;
7201
7227
  }
@@ -7215,7 +7241,7 @@ async function scanPageFiles(pagesDir, root) {
7215
7241
  path: absolutePath,
7216
7242
  pattern,
7217
7243
  routeChain,
7218
- segmentBoundaries,
7244
+ segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
7219
7245
  tags: collectRouteTags(routeChain, page)
7220
7246
  });
7221
7247
  }
@@ -7253,6 +7279,21 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
7253
7279
  }
7254
7280
  return parent;
7255
7281
  }
7282
+ function alignSegmentBoundaryDepths(boundaries, routeChain) {
7283
+ return boundaries.map((boundary) => {
7284
+ let depth = 0;
7285
+ for (const [index, entry] of routeChain.entries()) {
7286
+ if (!entry.sourcePath) {
7287
+ continue;
7288
+ }
7289
+ const directory = entry.sourcePath.slice(0, entry.sourcePath.lastIndexOf("/"));
7290
+ if (boundary.path === directory || boundary.path.startsWith(`${directory}/`)) {
7291
+ depth = index;
7292
+ }
7293
+ }
7294
+ return { ...boundary, depth };
7295
+ });
7296
+ }
7256
7297
  async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
7257
7298
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
7258
7299
  const dirs = [pagesDir];
@@ -7353,14 +7394,13 @@ async function collectPageFilePaths(dir) {
7353
7394
  }
7354
7395
  return files;
7355
7396
  }
7356
- var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, DYNAMIC_ROUTE_SEGMENT_RE, DIR_SCAN_CONCURRENCY = 8;
7397
+ var CONVENTION_FILE_NAMES, SOURCE_MODULE_EXTENSIONS, DIR_SCAN_CONCURRENCY = 8;
7357
7398
  var init_discovery = __esm(() => {
7358
7399
  init_internal();
7359
7400
  init_patterns();
7360
7401
  init_source_version();
7361
7402
  CONVENTION_FILE_NAMES = ["not-found", "error"];
7362
7403
  SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
7363
- DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
7364
7404
  });
7365
7405
 
7366
7406
  // src/server/dev/transform-failure.ts
@@ -10202,6 +10242,87 @@ function hasShadowingDeclaration(name, ancestors) {
10202
10242
  return ancestors.some((scope) => functionScopeHasName(scope, name) || scope.type === "CatchClause" && bindingPatternHasName(scope.param, name) || blockScopeHasName(scope, name) || loopScopeHasName(scope, name) || switchScopeHasName(scope, name));
10203
10243
  }
10204
10244
 
10245
+ // src/plugin/transform-client-module.ts
10246
+ import { realpathSync as realpathSync2 } from "fs";
10247
+ import { dirname as dirname4 } from "path";
10248
+ function clientModuleKey(modulePath) {
10249
+ const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
10250
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
10251
+ }
10252
+ function collectClientModuleBindings(program) {
10253
+ const bindings = new Set;
10254
+ for (const statement of program.body) {
10255
+ if (statement.type !== "ImportDeclaration") {
10256
+ continue;
10257
+ }
10258
+ const declaration = statement;
10259
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
10260
+ continue;
10261
+ }
10262
+ for (const specifier of declaration.specifiers) {
10263
+ const imported = specifier.imported;
10264
+ const local = specifier.local;
10265
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
10266
+ bindings.add(local.name);
10267
+ }
10268
+ }
10269
+ }
10270
+ return bindings;
10271
+ }
10272
+ function dynamicImportSpecifier(loader) {
10273
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
10274
+ return null;
10275
+ }
10276
+ const body = loader.body;
10277
+ const source = body.type === "ImportExpression" ? body.source : null;
10278
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
10279
+ }
10280
+ function transformClientModules(source, filename, environment) {
10281
+ if (!source.includes("clientModule")) {
10282
+ return source;
10283
+ }
10284
+ const { program } = parseSource(source, detectLangFromPath(filename));
10285
+ const bindings = collectClientModuleBindings(program);
10286
+ if (bindings.size === 0) {
10287
+ return source;
10288
+ }
10289
+ const transformed = new MagicString(source);
10290
+ walk(program, {
10291
+ CallExpression(node, context) {
10292
+ const call = node;
10293
+ const [loader, ...rest] = call.arguments;
10294
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
10295
+ return;
10296
+ }
10297
+ const unwrapped = unwrapTSExpression(loader);
10298
+ const specifier = dynamicImportSpecifier(unwrapped);
10299
+ if (specifier === null) {
10300
+ return;
10301
+ }
10302
+ let key;
10303
+ try {
10304
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname4(filename))));
10305
+ } catch (error) {
10306
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
10307
+ }
10308
+ if (environment === "client") {
10309
+ transformed.appendLeft(loader.end, `, ${key}`);
10310
+ } else {
10311
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
10312
+ }
10313
+ }
10314
+ });
10315
+ return transformed.toString();
10316
+ }
10317
+ var FURIN_CLIENT_MODULES, SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
10318
+ var init_transform_client_module = __esm(() => {
10319
+ init_dist2();
10320
+ init_dist3();
10321
+ init_lang_detect();
10322
+ init_parser();
10323
+ FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
10324
+ });
10325
+
10205
10326
  // src/plugin/transform-isomorphic.ts
10206
10327
  function importedName(specifier) {
10207
10328
  const { imported } = specifier;
@@ -10422,11 +10543,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
10422
10543
  }
10423
10544
  });
10424
10545
  }
10425
- function transformIsomorphicFunctions(source, filename, environment) {
10546
+ function transformIsomorphicFunctions(input, filename, environment) {
10426
10547
  const lang = detectLangFromPath(filename);
10427
10548
  if (lang === "dts") {
10428
- return { code: source, map: null, transformed: false };
10549
+ return { code: input, map: null, transformed: false };
10429
10550
  }
10551
+ const source = transformClientModules(input, filename, environment);
10552
+ const clientModulesTransformed = source !== input;
10430
10553
  const { program, diagnostics } = parseSource(source, lang);
10431
10554
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
10432
10555
  if (firstError) {
@@ -10438,7 +10561,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
10438
10561
  assertNoSplitChains(source, filename, program, builders);
10439
10562
  const candidates = collectCandidates(source, filename, program, bindings);
10440
10563
  if (candidates.length === 0) {
10441
- return { code: source, map: null, transformed: false };
10564
+ return { code: source, map: null, transformed: clientModulesTransformed };
10442
10565
  }
10443
10566
  const transformed = new MagicString(source);
10444
10567
  for (const candidate of candidates) {
@@ -10459,6 +10582,7 @@ var init_transform_isomorphic = __esm(() => {
10459
10582
  init_lang_detect();
10460
10583
  init_parser();
10461
10584
  init_dead_code_elimination();
10585
+ init_transform_client_module();
10462
10586
  FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
10463
10587
  });
10464
10588
 
@@ -10568,7 +10692,7 @@ var init_error2 = __esm(() => {
10568
10692
  });
10569
10693
 
10570
10694
  // src/server/dev/rewrite-module-specifiers.ts
10571
- import { dirname as dirname4, resolve as resolve5 } from "path";
10695
+ import { dirname as dirname5, resolve as resolve5 } from "path";
10572
10696
  function sourcePosition2(source, byteOffset) {
10573
10697
  const bytes = new TextEncoder().encode(source);
10574
10698
  const prefix = new TextDecoder().decode(bytes.slice(0, byteOffset));
@@ -10603,7 +10727,7 @@ function rewriteModuleSpecifiers(input) {
10603
10727
  Reflect.set(error, "position", sourcePosition2(input.code, parseError.start));
10604
10728
  throw error;
10605
10729
  }
10606
- const directory = dirname4(input.filePath);
10730
+ const directory = dirname5(input.filePath);
10607
10731
  const output = new MagicString(input.code);
10608
10732
  walkAST(program, (node) => {
10609
10733
  const literal = relativeSpecifier(node);
@@ -10633,7 +10757,7 @@ var init_rewrite_module_specifiers = __esm(() => {
10633
10757
 
10634
10758
  // src/server/dev-page-plugin.ts
10635
10759
  import { statSync as statSync3 } from "fs";
10636
- import { dirname as dirname5, isAbsolute as isAbsolute3, resolve as resolve6 } from "path";
10760
+ import { dirname as dirname6, isAbsolute as isAbsolute4, resolve as resolve6 } from "path";
10637
10761
  import { fileURLToPath as fileURLToPath3 } from "url";
10638
10762
  function toImportSpecifier(filePath) {
10639
10763
  return filePath.replaceAll("\\", "/");
@@ -10693,36 +10817,26 @@ function rewriteRelativeImportsWithVersion(source, filePath, versioned) {
10693
10817
  versioned
10694
10818
  });
10695
10819
  }
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;
10820
+ function rewriteBareImports(transpiled, dir) {
10821
+ const output = new MagicString(transpiled);
10822
+ walkAST(parseSource(transpiled, "js").program, (node) => {
10823
+ if (node.type !== "ImportDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "ExportAllDeclaration" && node.type !== "ImportExpression") {
10824
+ return;
10712
10825
  }
10713
- if (SINGLETON_PATHS.has(spec)) {
10714
- continue;
10826
+ const literal = node.source;
10827
+ const specifier = literal?.value;
10828
+ if (literal?.type !== "Literal" || typeof specifier !== "string" || specifier.startsWith(".") || isAbsolute4(specifier) || specifier.startsWith("file:") || SINGLETON_PATHS.has(specifier)) {
10829
+ return;
10715
10830
  }
10716
10831
  let resolved;
10717
10832
  try {
10718
- resolved = toImportSpecifier(Bun.resolveSync(spec, dir));
10833
+ resolved = toImportSpecifier(Bun.resolveSync(specifier, dir));
10719
10834
  } catch {
10720
- continue;
10835
+ return;
10721
10836
  }
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;
10837
+ output.update(literal.start, literal.end, JSON.stringify(resolved));
10838
+ });
10839
+ return output.toString();
10726
10840
  }
10727
10841
  function getSourceLoader(filePath) {
10728
10842
  if (filePath.endsWith(".tsx")) {
@@ -10739,6 +10853,44 @@ function getSourceLoader(filePath) {
10739
10853
  }
10740
10854
  return null;
10741
10855
  }
10856
+ function restoreImportAttributes(source, transpiled, loader) {
10857
+ if (!IMPORT_ATTRIBUTES_RE.test(source)) {
10858
+ return transpiled;
10859
+ }
10860
+ const declarations = parseSource(source, loader).program.body;
10861
+ const output = new MagicString(transpiled);
10862
+ const emitted = parseSource(transpiled, "js").program.body;
10863
+ const matched = new Set;
10864
+ for (const declaration of declarations) {
10865
+ if (declaration.importKind === "type" || declaration.exportKind === "type") {
10866
+ continue;
10867
+ }
10868
+ const specifiers = declaration.specifiers;
10869
+ if (specifiers?.length && specifiers.every((specifier) => specifier.importKind === "type" || specifier.exportKind === "type")) {
10870
+ continue;
10871
+ }
10872
+ const sourcePath = declaration.source?.value;
10873
+ if (typeof sourcePath !== "string") {
10874
+ continue;
10875
+ }
10876
+ const target = emitted.find((node) => !matched.has(node) && node.type === declaration.type && node.source?.value === sourcePath);
10877
+ if (!target) {
10878
+ continue;
10879
+ }
10880
+ matched.add(target);
10881
+ const attributes = declaration.attributes;
10882
+ if (!attributes?.length || target.attributes?.length) {
10883
+ continue;
10884
+ }
10885
+ const [first] = attributes;
10886
+ const last = attributes.at(-1);
10887
+ const imported = target.source;
10888
+ if (first && last && imported) {
10889
+ output.appendLeft(imported.end, ` with { ${source.slice(first.start, last.end)} }`);
10890
+ }
10891
+ }
10892
+ return output.toString();
10893
+ }
10742
10894
  function shouldSkipWorkspaceTransform(filePath) {
10743
10895
  const normalized = filePath.replace(/\\/g, "/");
10744
10896
  return normalized.includes("/.furin/");
@@ -10746,7 +10898,7 @@ function shouldSkipWorkspaceTransform(filePath) {
10746
10898
  function recordDevImports(source, filePath) {
10747
10899
  const { imports } = resolveDevSourceImports(source, filePath, getSourceLoader(filePath) ?? "tsx");
10748
10900
  for (const path of imports) {
10749
- if (!isAbsolute3(path) || getSourceLoader(path)) {
10901
+ if (!isAbsolute4(path) || getSourceLoader(path)) {
10750
10902
  continue;
10751
10903
  }
10752
10904
  const stats = statSync3(path, { bigint: true, throwIfNoEntry: false });
@@ -10813,10 +10965,10 @@ function transformDevSource(raw, filePath, options) {
10813
10965
  const serverSource = split?.contract ?? isomorphicSource;
10814
10966
  const sourceForTranspile = options.rewriteRelativeImports ? rewriteRelativeImportsWithVersion(serverSource, filePath, true) : serverSource;
10815
10967
  const transpiler = new Bun.Transpiler({ loader });
10816
- const transpiled = transpiler.transformSync(sourceForTranspile, loader);
10968
+ const transpiled = restoreImportAttributes(sourceForTranspile, transpiler.transformSync(sourceForTranspile, loader), loader);
10817
10969
  let result = transpiled;
10818
10970
  if (options.rewriteBareImports) {
10819
- result = rewriteBareImports(serverSource, result, dirname5(filePath));
10971
+ result = rewriteBareImports(result, dirname6(filePath));
10820
10972
  }
10821
10973
  result = rewriteSingletonImports(result);
10822
10974
  return injectJsxHelperImports(result);
@@ -10925,10 +11077,13 @@ function registerDevPagePlugin() {
10925
11077
  }
10926
11078
  });
10927
11079
  }
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;
11080
+ 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
11081
  var init_dev_page_plugin = __esm(() => {
11082
+ init_dist2();
10930
11083
  init_transform_dev_page();
10931
11084
  init_transform_isomorphic();
11085
+ init_parser();
11086
+ init_ast_walk();
10932
11087
  init_dev_loader();
10933
11088
  init_error2();
10934
11089
  init_graph();
@@ -10942,6 +11097,7 @@ var init_dev_page_plugin = __esm(() => {
10942
11097
  T_PARAM_RE = /&t=(\d+)/;
10943
11098
  STRIP_FURIN_SERVER_RE = /\?furin-server.*$/;
10944
11099
  STRIP_T_PARAM_RE = /\?t=\d+$/;
11100
+ IMPORT_ATTRIBUTES_RE = /\b(?:with|assert)\s*\{/;
10945
11101
  pluginSourceStamps = new Map;
10946
11102
  SINGLETON_PKGS = [
10947
11103
  "react",
@@ -10964,11 +11120,11 @@ import {
10964
11120
  existsSync as existsSync4,
10965
11121
  readdirSync,
10966
11122
  readFileSync as readFileSync4,
10967
- realpathSync as realpathSync2,
11123
+ realpathSync as realpathSync3,
10968
11124
  statSync as statSync4,
10969
11125
  watch
10970
11126
  } 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";
11127
+ 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
11128
  import { Elysia as Elysia12 } from "elysia";
10973
11129
  function instanceKey(instance) {
10974
11130
  return `${resolve7(instance.pagesDir)}\x00${instance.prefix}`;
@@ -10977,7 +11133,8 @@ function routeModuleSpecifier(instance) {
10977
11133
  return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
10978
11134
  }
10979
11135
  function scanRouteFiles(directory, directorySegments, files) {
10980
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
11136
+ const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
11137
+ for (const entry of entries) {
10981
11138
  if (entry.isDirectory()) {
10982
11139
  if (entry.name.startsWith("_")) {
10983
11140
  continue;
@@ -11010,9 +11167,6 @@ function scanRouteFiles(directory, directorySegments, files) {
11010
11167
  function segmentPath(segment) {
11011
11168
  return routeSegmentToPattern(segment);
11012
11169
  }
11013
- function routePath(segments) {
11014
- return segments.length === 0 ? "/" : `/${segments.map(segmentPath).join("/")}`;
11015
- }
11016
11170
  function routeId(instanceId, path) {
11017
11171
  const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
11018
11172
  return `_route_${instanceId}_${encodedPath}`;
@@ -11041,14 +11195,22 @@ function buildRouteTree(pagesDir, instanceId) {
11041
11195
  return node;
11042
11196
  };
11043
11197
  const root = ensureNode([]);
11198
+ const seenPatterns = new Map;
11044
11199
  for (const file of scannedFiles) {
11045
11200
  const node = ensureNode(file.directorySegments);
11046
11201
  if (file.base === "_route") {
11047
- const path = `${routePath(file.directorySegments)}#layout`;
11202
+ const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
11048
11203
  node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
11049
11204
  continue;
11050
11205
  }
11051
- const path = file.base === "index" ? routePath(file.directorySegments) : routePath([...file.directorySegments, file.base]);
11206
+ const path = filePathToPattern(relative7(pagesDir, file.sourcePath));
11207
+ const patternKey = routePatternKey(path);
11208
+ const relativePath = relative7(pagesDir, file.sourcePath).replaceAll("\\", "/");
11209
+ const previousPath = seenPatterns.get(patternKey);
11210
+ if (previousPath !== undefined) {
11211
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
11212
+ }
11213
+ seenPatterns.set(patternKey, relativePath);
11052
11214
  const route = { id: routeId(instanceId, path), path, sourcePath: file.sourcePath };
11053
11215
  if (file.base === "index") {
11054
11216
  node.indexRoute = route;
@@ -11239,7 +11401,7 @@ function replaceSourceWatchers(state) {
11239
11401
  const directories = new Set;
11240
11402
  for (const path of routeDependencyPaths(state.instance)) {
11241
11403
  if (!(path === pagesDir || path.startsWith(`${pagesDir}${sep2}`))) {
11242
- directories.add(dirname6(path));
11404
+ directories.add(dirname7(path));
11243
11405
  }
11244
11406
  }
11245
11407
  const watchDirectory = (directory, recursive) => {
@@ -11368,19 +11530,19 @@ function routeModuleCache() {
11368
11530
  return cache;
11369
11531
  }
11370
11532
  function findPackageRoot(sourcePath) {
11371
- const fallback = dirname6(sourcePath);
11533
+ const fallback = dirname7(sourcePath);
11372
11534
  let directory = fallback;
11373
- while (dirname6(directory) !== directory) {
11535
+ while (dirname7(directory) !== directory) {
11374
11536
  if (existsSync4(join3(directory, "package.json"))) {
11375
11537
  return directory;
11376
11538
  }
11377
- directory = dirname6(directory);
11539
+ directory = dirname7(directory);
11378
11540
  }
11379
11541
  return existsSync4(join3(directory, "package.json")) ? directory : fallback;
11380
11542
  }
11381
11543
  function isWithinDirectory(path, directory) {
11382
11544
  const relativePath = relative7(directory, path);
11383
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute4(relativePath));
11545
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute5(relativePath));
11384
11546
  }
11385
11547
  function isFurinPackageImport(specifier) {
11386
11548
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -11397,8 +11559,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
11397
11559
  continue;
11398
11560
  }
11399
11561
  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")) {
11562
+ const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname7(dependencyPath)));
11563
+ if (isAbsolute5(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative7(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
11402
11564
  resolvedImports.push(resolvedImport);
11403
11565
  }
11404
11566
  } catch {}
@@ -11406,7 +11568,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
11406
11568
  return resolvedImports;
11407
11569
  }
11408
11570
  function collectRouteModuleDependencies(sourcePath) {
11409
- const packageRoot = realpathSync2.native(findPackageRoot(sourcePath));
11571
+ const packageRoot = realpathSync3.native(findPackageRoot(sourcePath));
11410
11572
  const pending = [sourcePath];
11411
11573
  const visited = new Set;
11412
11574
  const dependencies = [];
@@ -11447,7 +11609,7 @@ async function composableRouteApps(route) {
11447
11609
  };
11448
11610
  }
11449
11611
  async function composeRuntimeNode(node) {
11450
- const prefix = node.name ? `/${segmentPath(node.name)}` : "";
11612
+ const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
11451
11613
  const { fileRoutes } = node;
11452
11614
  const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
11453
11615
  node.layout ? composableRouteApps(node.layout) : undefined,
@@ -12393,12 +12555,19 @@ function compareRouteProperties(left, right) {
12393
12555
  return leftProperty < rightProperty ? -1 : 1;
12394
12556
  }
12395
12557
  function routeMapDeclaration(entries) {
12396
- const body = entries.toSorted(compareRouteProperties).map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12558
+ const sorted = entries.toSorted(compareRouteProperties);
12559
+ const body = sorted.map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12560
+ `);
12561
+ const patterns = sorted.map((entry) => ` ${JSON.stringify(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
12397
12562
  `);
12398
12563
  return `declare module "@teyik0/furin/routes" {
12399
12564
  interface RouteMap {
12400
12565
  ${body}
12401
12566
  }
12567
+
12568
+ interface RoutePatternMap {
12569
+ ${patterns}
12570
+ }
12402
12571
  }`;
12403
12572
  }
12404
12573
 
@@ -12451,6 +12620,7 @@ var init_route_types = () => {};
12451
12620
  import { existsSync as existsSync7, mkdirSync, readFileSync as readFileSync7, writeFileSync as writeFileSync2 } from "fs";
12452
12621
  import { join as join6 } from "path";
12453
12622
  function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
12623
+ const rootDirectory = rootLayout.replaceAll("\\", "/").split("/").slice(0, -1).join("/");
12454
12624
  const getBoundaryIdent = (idents, filePath) => {
12455
12625
  if (!filePath) {
12456
12626
  return;
@@ -12491,6 +12661,9 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
12491
12661
  if (notFoundIdent) {
12492
12662
  parts.push(`notFound: ${notFoundIdent}.default`);
12493
12663
  }
12664
+ if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
12665
+ parts.push("isRoot: false");
12666
+ }
12494
12667
  boundaryLiterals.push(`{ ${parts.join(", ")} }`);
12495
12668
  }
12496
12669
  const lazyImports = [
@@ -12506,7 +12679,7 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
12506
12679
  }).join(" ");
12507
12680
  const boundaryResult = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
12508
12681
  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} }; })`;
12682
+ 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
12683
  const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
12511
12684
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
12512
12685
  }
@@ -12740,6 +12913,12 @@ if (__deferred && __deferred._chunks) {
12740
12913
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
12741
12914
  } as any);
12742
12915
  } else {
12916
+ // A removed active route has no match in the new development manifest.
12917
+ // Reload its document so the server can render the current 404 response.
12918
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
12919
+ window.location.reload();
12920
+ return;
12921
+ }
12743
12922
  // No match and no 404 signal \u2014 either the client bundle is out of sync
12744
12923
  // with the server (stale deploy) or the server returned something we
12745
12924
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -12816,11 +12995,14 @@ if (__deferred && __deferred._chunks) {
12816
12995
  });
12817
12996
  `;
12818
12997
  }
12819
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
12998
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot, serverSourceVersion) {
12820
12999
  if (!existsSync7(outDir)) {
12821
13000
  mkdirSync(outDir, { recursive: true });
12822
13001
  }
12823
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
13002
+ const serverVersion = serverSourceVersion === undefined ? "" : `
13003
+ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};
13004
+ `;
13005
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
12824
13006
  const hydratePath = join6(outDir, "_hydrate.tsx");
12825
13007
  const existingHydrate = existsSync7(hydratePath) ? readFileSync7(hydratePath, "utf8") : "";
12826
13008
  let changed = false;
@@ -12848,45 +13030,439 @@ var init_hydrate = __esm(() => {
12848
13030
  init_route_types();
12849
13031
  });
12850
13032
 
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";
13033
+ // src/plugin/hmr-dependencies.ts
13034
+ import { readFileSync as readFileSync8 } from "fs";
13035
+ import { dirname as dirname8, isAbsolute as isAbsolute6, resolve as resolve9 } from "path";
13036
+ function hmrDependencySignature(imports, filename) {
13037
+ const routePath = resolve9(filename);
13038
+ const visited = new Set;
13039
+ const hash = new Bun.CryptoHasher("sha256");
13040
+ const visit = (specifier, importer) => {
13041
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
13042
+ return true;
13043
+ }
13044
+ const path = Bun.resolveSync(specifier, dirname8(importer));
13045
+ if (path === routePath) {
13046
+ return false;
13047
+ }
13048
+ hash.update(JSON.stringify([specifier, path]));
13049
+ if (!isAbsolute6(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
13050
+ return true;
13051
+ }
13052
+ visited.add(path);
13053
+ const source = readFileSync8(path, "utf8");
13054
+ hash.update(source);
13055
+ if (SCRIPT_FILE.test(path)) {
13056
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
13057
+ for (const dependency of transpiler.scanImports(source)) {
13058
+ if (!visit(dependency.path, path)) {
13059
+ return false;
13060
+ }
13061
+ }
13062
+ }
13063
+ return true;
13064
+ };
13065
+ try {
13066
+ for (const specifier of imports) {
13067
+ if (!visit(specifier, routePath)) {
13068
+ return;
13069
+ }
13070
+ }
13071
+ return hash.digest("hex");
13072
+ } catch {}
13073
+ }
13074
+ var SCRIPT_FILE;
13075
+ var init_hmr_dependencies = __esm(() => {
13076
+ init_lang_detect();
13077
+ SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
13078
+ });
12858
13079
 
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)) {
13080
+ // src/plugin/transform-client.ts
13081
+ function isFurinRouteModule(source) {
13082
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
13083
+ }
13084
+ function importedName2(specifier) {
13085
+ const { imported } = specifier;
13086
+ if (!imported || typeof imported !== "object") {
12868
13087
  return null;
12869
13088
  }
12870
- return assetPath;
13089
+ const node = imported;
13090
+ if (node.type === "Identifier" && typeof node.name === "string") {
13091
+ return node.name;
13092
+ }
13093
+ if (node.type === "Literal" && typeof node.value === "string") {
13094
+ return node.value;
13095
+ }
13096
+ return null;
12871
13097
  }
12872
- async function loadEmbeddedAsset(directory, requestPath) {
12873
- const assetPath = resolveEmbeddedAssetPath(directory, requestPath);
12874
- if (assetPath === null) {
13098
+ function localName2(specifier) {
13099
+ const { local } = specifier;
13100
+ if (!local || typeof local !== "object") {
12875
13101
  return null;
12876
13102
  }
12877
- const asset = Bun.file(assetPath);
12878
- return await asset.exists() ? asset : null;
13103
+ const node = local;
13104
+ return node.type === "Identifier" && typeof node.name === "string" ? node.name : null;
12879
13105
  }
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");
13106
+ function collectDefineRouteBindings(program) {
13107
+ const bindings = new Set;
13108
+ for (const statement of program.body) {
13109
+ if (statement.type !== "ImportDeclaration") {
13110
+ continue;
13111
+ }
13112
+ const declaration = statement;
13113
+ if (declaration.importKind === "type") {
13114
+ continue;
13115
+ }
13116
+ const source = declaration.source.value;
13117
+ if (!isFurinRouteModule(source)) {
13118
+ continue;
13119
+ }
13120
+ for (const specifier of declaration.specifiers) {
13121
+ if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") {
13122
+ continue;
12887
13123
  }
12888
- set.headers["cache-control"] = "public, max-age=31536000, immutable";
12889
- return asset;
13124
+ const imported = importedName2(specifier);
13125
+ if (imported !== "defineRoute" && imported !== "defineRootRoute") {
13126
+ continue;
13127
+ }
13128
+ const local = localName2(specifier);
13129
+ if (local) {
13130
+ bindings.add(local);
13131
+ }
13132
+ }
13133
+ }
13134
+ return bindings;
13135
+ }
13136
+ function asAstNode2(node) {
13137
+ if (!node || typeof node !== "object" || !("type" in node)) {
13138
+ return null;
13139
+ }
13140
+ return unwrapTSExpression(node);
13141
+ }
13142
+ function chainRootIsDefineRoute(node, bindings, ancestors) {
13143
+ let current = asAstNode2(node);
13144
+ while (current) {
13145
+ if (current.type === "MemberExpression") {
13146
+ current = asAstNode2(current.object);
13147
+ continue;
13148
+ }
13149
+ if (current.type === "CallExpression") {
13150
+ current = asAstNode2(current.callee);
13151
+ continue;
13152
+ }
13153
+ return current.type === "Identifier" && typeof current.name === "string" && bindings.has(current.name) && !hasShadowingDeclaration(current.name, ancestors);
13154
+ }
13155
+ return false;
13156
+ }
13157
+ function collectBindingNames(pattern, names) {
13158
+ const node = asAstNode2(pattern);
13159
+ if (!node) {
13160
+ return;
13161
+ }
13162
+ if (node.type === "Identifier" && typeof node.name === "string") {
13163
+ names.push(node.name);
13164
+ return;
13165
+ }
13166
+ if (node.type === "AssignmentPattern") {
13167
+ collectBindingNames(node.left, names);
13168
+ return;
13169
+ }
13170
+ if (node.type === "RestElement") {
13171
+ collectBindingNames(node.argument, names);
13172
+ return;
13173
+ }
13174
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
13175
+ for (const element of node.elements) {
13176
+ collectBindingNames(element, names);
13177
+ }
13178
+ return;
13179
+ }
13180
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
13181
+ for (const property of node.properties) {
13182
+ const propertyNode = asAstNode2(property);
13183
+ collectBindingNames(propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument, names);
13184
+ }
13185
+ }
13186
+ }
13187
+ function collectDeclarationBindings(declaration, declarations) {
13188
+ if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
13189
+ const identifier = asAstNode2(declaration.id);
13190
+ if (identifier?.type === "Identifier" && typeof identifier.name === "string") {
13191
+ declarations.set(identifier.name, declaration);
13192
+ }
13193
+ return;
13194
+ }
13195
+ if (declaration?.type !== "VariableDeclaration" || !Array.isArray(declaration.declarations)) {
13196
+ return;
13197
+ }
13198
+ for (const item of declaration.declarations) {
13199
+ const names = [];
13200
+ collectBindingNames(item.id, names);
13201
+ for (const name of names) {
13202
+ declarations.set(name, item);
13203
+ }
13204
+ }
13205
+ }
13206
+ function collectModuleBindings(program) {
13207
+ const declarations = new Map;
13208
+ const imports = new Map;
13209
+ for (const statement of program.body) {
13210
+ if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
13211
+ for (const specifier of statement.specifiers) {
13212
+ const local = localName2(specifier);
13213
+ if (local) {
13214
+ imports.set(local, statement);
13215
+ }
13216
+ }
13217
+ continue;
13218
+ }
13219
+ const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? asAstNode2(statement.declaration) : statement;
13220
+ collectDeclarationBindings(declaration, declarations);
13221
+ }
13222
+ return { declarations, imports };
13223
+ }
13224
+ function isBindingIdentifier(identifier, pattern) {
13225
+ const node = asAstNode2(pattern);
13226
+ if (!node) {
13227
+ return false;
13228
+ }
13229
+ if (node.type === "Identifier") {
13230
+ return node.start === identifier.start && node.end === identifier.end;
13231
+ }
13232
+ if (node.type === "AssignmentPattern") {
13233
+ return isBindingIdentifier(identifier, node.left);
13234
+ }
13235
+ if (node.type === "RestElement") {
13236
+ return isBindingIdentifier(identifier, node.argument);
13237
+ }
13238
+ if (node.type === "ArrayPattern" && Array.isArray(node.elements)) {
13239
+ return node.elements.some((element) => isBindingIdentifier(identifier, element));
13240
+ }
13241
+ if (node.type === "ObjectPattern" && Array.isArray(node.properties)) {
13242
+ return node.properties.some((property) => {
13243
+ const propertyNode = asAstNode2(property);
13244
+ return isBindingIdentifier(identifier, propertyNode?.type === "Property" ? propertyNode.value : propertyNode?.argument);
13245
+ });
13246
+ }
13247
+ return false;
13248
+ }
13249
+ function nodeContains(container, node) {
13250
+ if (Array.isArray(container)) {
13251
+ return container.some((entry) => nodeContains(entry, node));
13252
+ }
13253
+ const containerNode = asAstNode2(container);
13254
+ return Boolean(containerNode && containerNode.start <= node.start && node.end <= containerNode.end);
13255
+ }
13256
+ function isTypePosition(node, ancestors) {
13257
+ return ancestors.some((ancestor) => {
13258
+ if (!ancestor.type.startsWith("TS")) {
13259
+ return false;
13260
+ }
13261
+ const runtimeChildren = TYPESCRIPT_RUNTIME_WRAPPERS.get(ancestor.type);
13262
+ if (runtimeChildren) {
13263
+ return !runtimeChildren.some((key) => nodeContains(ancestor[key], node));
13264
+ }
13265
+ return true;
13266
+ });
13267
+ }
13268
+ function isNonReferenceKey(node, parent) {
13269
+ 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));
13270
+ }
13271
+ function isReferenceIdentifier(node, ancestors) {
13272
+ if (isTypePosition(node, ancestors) || isNonReferenceKey(node, ancestors.at(-1))) {
13273
+ return false;
13274
+ }
13275
+ for (const ancestor of ancestors) {
13276
+ 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)) {
13277
+ return false;
13278
+ }
13279
+ }
13280
+ return true;
13281
+ }
13282
+ function walkWithAncestors(value, ancestors, visitor) {
13283
+ if (Array.isArray(value)) {
13284
+ for (const entry of value) {
13285
+ walkWithAncestors(entry, ancestors, visitor);
13286
+ }
13287
+ return;
13288
+ }
13289
+ const node = asAstNode2(value);
13290
+ if (!node) {
13291
+ return;
13292
+ }
13293
+ visitor(node, ancestors);
13294
+ const nextAncestors = [...ancestors, node];
13295
+ for (const [key, child] of Object.entries(node)) {
13296
+ if (key !== "type" && key !== "start" && key !== "end" && key !== "comments") {
13297
+ walkWithAncestors(child, nextAncestors, visitor);
13298
+ }
13299
+ }
13300
+ }
13301
+ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
13302
+ const parent = ancestors.at(-1);
13303
+ 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);
13304
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
13305
+ return;
13306
+ }
13307
+ const declaration = state.moduleBindings.declarations.get(child.name);
13308
+ if (!declaration) {
13309
+ const imported = state.moduleBindings.imports.get(child.name);
13310
+ if (trackImports && imported) {
13311
+ state.imports.add(imported);
13312
+ }
13313
+ return;
13314
+ }
13315
+ const alreadyTracked = state.dependencies.has(declaration.start);
13316
+ if (!alreadyTracked) {
13317
+ state.dependencies.set(declaration.start, declaration);
13318
+ }
13319
+ if (trackImports) {
13320
+ if (state.importTrackedDependencies.has(declaration.start)) {
13321
+ return;
13322
+ }
13323
+ state.importTrackedDependencies.add(declaration.start);
13324
+ } else if (alreadyTracked) {
13325
+ return;
13326
+ }
13327
+ collectDependencies(declaration, trackImports, state);
13328
+ }
13329
+ function collectDependencies(node, trackImports, state) {
13330
+ walkWithAncestors(node, [], (child, ancestors) => {
13331
+ collectDependencyIdentifier(child, ancestors, trackImports, state);
13332
+ if (trackImports && child.type === "ImportExpression") {
13333
+ const specifier = asAstNode2(child.source)?.value;
13334
+ if (typeof specifier === "string") {
13335
+ state.dynamicImports.add(specifier);
13336
+ }
13337
+ }
13338
+ });
13339
+ }
13340
+ function createHmrDataSignature(code, program, bindings, filename) {
13341
+ const serverStages = [];
13342
+ const dependencyState = {
13343
+ dependencies: new Map,
13344
+ dynamicImports: new Set,
13345
+ imports: new Set,
13346
+ importTrackedDependencies: new Set,
13347
+ moduleBindings: collectModuleBindings(program)
13348
+ };
13349
+ walk(program, {
13350
+ CallExpression(call, context) {
13351
+ const callee = asAstNode2(call.callee);
13352
+ if (callee?.type !== "MemberExpression" || callee.computed === true || !callee.property || typeof callee.property !== "object") {
13353
+ return;
13354
+ }
13355
+ const property = callee.property;
13356
+ if (property.type !== "Identifier" || typeof property.name !== "string" || !SERVER_ONLY_METHODS.has(property.name) || !chainRootIsDefineRoute(callee.object, bindings, context.ancestors())) {
13357
+ return;
13358
+ }
13359
+ const object = asAstNode2(callee.object);
13360
+ if (!object) {
13361
+ return;
13362
+ }
13363
+ serverStages.push({
13364
+ source: code.slice(object.end, call.end),
13365
+ start: call.start
13366
+ });
13367
+ if (Array.isArray(call.arguments)) {
13368
+ for (const argument of call.arguments) {
13369
+ const argumentNode = asAstNode2(argument);
13370
+ if (argumentNode) {
13371
+ collectDependencies(argumentNode, property.name !== "config", dependencyState);
13372
+ }
13373
+ }
13374
+ }
13375
+ }
13376
+ });
13377
+ const dataSource = [
13378
+ ...serverStages,
13379
+ ...[...dependencyState.imports].map((imported) => ({
13380
+ source: code.slice(imported.start, imported.end),
13381
+ start: imported.start
13382
+ })),
13383
+ ...[...dependencyState.dependencies.values()].map((dependency) => ({
13384
+ source: code.slice(dependency.start, dependency.end),
13385
+ start: dependency.start
13386
+ }))
13387
+ ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
13388
+ `);
13389
+ const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
13390
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
13391
+ return hash;
13392
+ }
13393
+ const dependencies = hmrDependencySignature(new Set([
13394
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
13395
+ ...dependencyState.dynamicImports
13396
+ ]), filename);
13397
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
13398
+ }
13399
+ function getHmrDataSignature(code, filename) {
13400
+ const { diagnostics, program } = parseSource(code, detectLangFromPath(filename));
13401
+ const error = diagnostics.find((diagnostic) => diagnostic.severity === "error");
13402
+ if (error) {
13403
+ throw new Error(`Failed to parse ${filename}: ${error.message}`);
13404
+ }
13405
+ return createHmrDataSignature(code, program, collectDefineRouteBindings(program), filename);
13406
+ }
13407
+ var FURIN_CLIENT_MODULES2, FURIN_SERVER_MODULES, REACT_COMPONENT_WRAPPERS, SERVER_ONLY_METHODS, TYPESCRIPT_RUNTIME_WRAPPERS;
13408
+ var init_transform_client = __esm(() => {
13409
+ init_dist3();
13410
+ init_lang_detect();
13411
+ init_parser();
13412
+ init_hmr_dependencies();
13413
+ FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
13414
+ FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
13415
+ REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
13416
+ SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
13417
+ TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
13418
+ ["TSAsExpression", ["expression"]],
13419
+ ["TSInstantiationExpression", ["expression"]],
13420
+ ["TSNonNullExpression", ["expression"]],
13421
+ ["TSParameterProperty", ["decorators", "parameter"]],
13422
+ ["TSSatisfiesExpression", ["expression"]],
13423
+ ["TSTypeAssertion", ["expression"]]
13424
+ ]);
13425
+ });
13426
+
13427
+ // src/furin.ts
13428
+ init_define_route();
13429
+ import { existsSync as existsSync8, readFileSync as readFileSync9, writeFileSync as writeFileSync3 } from "fs";
13430
+ import { basename as basename2, delimiter, dirname as dirname9, join as join7, resolve as resolve10 } from "path";
13431
+ import { fileURLToPath as fileURLToPath4 } from "url";
13432
+ import { staticPlugin as staticPlugin2 } from "@elysia/static";
13433
+ import { Elysia as Elysia13, file as file2, NotFound, problem as problem2 } from "elysia";
13434
+
13435
+ // src/server/assets/production.ts
13436
+ import { existsSync } from "fs";
13437
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "path";
13438
+ import { staticPlugin } from "@elysia/static";
13439
+ import { Elysia as Elysia2, file } from "elysia";
13440
+ function resolveEmbeddedAssetPath(directory, requestPath) {
13441
+ const assetPath = resolve(directory, requestPath);
13442
+ const pathFromDirectory = relative(directory, assetPath);
13443
+ if (pathFromDirectory === "" || pathFromDirectory === ".." || pathFromDirectory.startsWith(`..${sep}`) || isAbsolute(pathFromDirectory)) {
13444
+ return null;
13445
+ }
13446
+ return assetPath;
13447
+ }
13448
+ async function loadEmbeddedAsset(directory, requestPath) {
13449
+ const assetPath = resolveEmbeddedAssetPath(directory, requestPath);
13450
+ if (assetPath === null) {
13451
+ return null;
13452
+ }
13453
+ const asset = Bun.file(assetPath);
13454
+ return await asset.exists() ? asset : null;
13455
+ }
13456
+ function createEmbeddedAssetsPlugin(embedded) {
13457
+ const { clientDir, publicDir } = embedded;
13458
+ if (!publicDir) {
13459
+ return new Elysia2().get("/_client/*", async ({ params, set, status }) => {
13460
+ const asset = await loadEmbeddedAsset(clientDir, params["*"]);
13461
+ if (asset === null) {
13462
+ return status("Not Found");
13463
+ }
13464
+ set.headers["cache-control"] = "public, max-age=31536000, immutable";
13465
+ return asset;
12890
13466
  });
12891
13467
  }
12892
13468
  return new Elysia2().get("/favicon.ico", async ({ status }) => {
@@ -15044,283 +15620,400 @@ function fromCrossJSON(source, options) {
15044
15620
  depthLimit: options.depthLimit
15045
15621
  }), source);
15046
15622
  }
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";
15623
+
15624
+ // src/shared/sync-query.ts
15625
+ function serializeQueryHeader(identity) {
15626
+ return JSON.stringify(identity).replace(/[^\u0020-\u007e]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
15627
+ }
15628
+ function mergeQuerySeeds(target, incoming) {
15629
+ for (const seed of incoming) {
15630
+ const index = target.findIndex((existing) => existing.url === seed.url);
15631
+ const previous = target[index];
15632
+ const bindings = [...seed.bindings ?? []];
15633
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
15634
+ for (const binding of previous.bindings ?? []) {
15635
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
15636
+ bindings.push(binding);
15637
+ }
15638
+ }
15639
+ }
15640
+ const merged = { ...seed, bindings };
15641
+ if (index < 0) {
15642
+ target.push(merged);
15643
+ } else {
15644
+ target[index] = merged;
15053
15645
  }
15054
15646
  }
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
15647
  }
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;
15648
+ function queryTagsFromData(data) {
15649
+ return (data.__furinQueries ?? []).map((seed) => queryTag(seed.identity));
15080
15650
  }
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}`;
15651
+ var PREFIX = "__furin.query:";
15652
+ function queryTag(identity) {
15653
+ for (const [key, value] of Object.entries(identity.scope)) {
15654
+ if (value === undefined) {
15655
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
15088
15656
  }
15089
15657
  }
15090
- if (hash) {
15091
- url += `#${hash}`;
15092
- }
15093
- return url;
15658
+ return PREFIX + JSON.stringify([
15659
+ identity.id,
15660
+ Object.entries(identity.scope).sort(([a], [b]) => {
15661
+ if (a === b) {
15662
+ return 0;
15663
+ }
15664
+ return a < b ? -1 : 1;
15665
+ })
15666
+ ]);
15094
15667
  }
15095
- function normalizeHref(href) {
15096
- const url = new URL(href, "http://localhost");
15097
- let { pathname } = url;
15098
- if (pathname !== "/") {
15099
- pathname = pathname.replace(/\/+$/g, "");
15668
+ function queryFromTag(tag) {
15669
+ if (!tag.startsWith(PREFIX)) {
15670
+ return;
15100
15671
  }
15101
- return pathname + url.search + url.hash;
15672
+ try {
15673
+ const value = JSON.parse(tag.slice(PREFIX.length));
15674
+ 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"))) {
15675
+ return;
15676
+ }
15677
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
15678
+ } catch {}
15102
15679
  }
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;
15680
+ function queryUrl(url, origin) {
15681
+ const parsed = new URL(url, origin);
15682
+ parsed.searchParams.sort();
15683
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
15108
15684
  }
15109
15685
 
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);
15686
+ // src/client/query-store.ts
15687
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
15688
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
15689
+ var environmentGlobal = globalThis;
15690
+ function setServerQueryEnvironment(read) {
15691
+ environmentGlobal[SERVER_ENVIRONMENT] = read;
15692
+ }
15693
+ function currentQueryEnvironment() {
15694
+ return environmentGlobal[SERVER_ENVIRONMENT]?.();
15695
+ }
15696
+ class QueryStore {
15697
+ entries = new Map;
15698
+ listeners = new Set;
15699
+ revisionValue = 0;
15700
+ projections = new Set;
15701
+ session;
15702
+ epoch = 0;
15703
+ origin;
15704
+ constructor(origin) {
15705
+ this.origin = origin;
15706
+ }
15707
+ key(url) {
15708
+ const absolute = new URL(url, this.origin).href;
15709
+ return queryUrl(absolute, undefined);
15710
+ }
15711
+ entry(url) {
15712
+ const key = this.key(url);
15713
+ let entry = this.entries.get(key);
15714
+ if (!entry) {
15715
+ entry = {
15716
+ base: undefined,
15717
+ listeners: new Set,
15718
+ snapshot: { data: undefined, error: null, isFetching: false },
15719
+ stale: true,
15720
+ version: 0
15721
+ };
15722
+ this.entries.set(key, entry);
15723
+ }
15724
+ return entry;
15131
15725
  }
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);
15726
+ publish(entry) {
15727
+ let data = entry.base;
15728
+ for (const projection of this.projections) {
15729
+ const transform = projection.transforms.get(entry);
15730
+ if (transform && data !== undefined) {
15731
+ data = transform(data);
15732
+ }
15733
+ }
15734
+ entry.snapshot = { ...entry.snapshot, data };
15735
+ for (const listener of entry.listeners) {
15736
+ listener();
15737
+ }
15738
+ this.revisionValue += 1;
15739
+ for (const listener of this.listeners) {
15740
+ listener();
15741
+ }
15137
15742
  }
15138
- if ("tagName" in meta) {
15139
- const { tagName, ...attributes } = meta;
15140
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
15743
+ revision = () => this.revisionValue;
15744
+ subscribeAll = (listener) => {
15745
+ this.listeners.add(listener);
15746
+ return () => this.listeners.delete(listener);
15747
+ };
15748
+ observe(url, result, epoch, version) {
15749
+ const existing = this.entries.get(this.key(url));
15750
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
15751
+ return;
15752
+ }
15753
+ const header = result.response?.headers.get("x-furin-query");
15754
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
15755
+ if (identity) {
15756
+ this.setSession(identity.session);
15757
+ }
15758
+ const entry = this.entry(url);
15759
+ entry.base = result.data;
15760
+ entry.version += 1;
15761
+ entry.identity = identity;
15762
+ entry.local = result.local ?? result.response?.url === "";
15763
+ entry.stale = false;
15764
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
15765
+ for (const projection of this.projections) {
15766
+ if (!projection.pending) {
15767
+ projection.transforms.delete(entry);
15768
+ if (projection.transforms.size === 0) {
15769
+ this.projections.delete(projection);
15770
+ projection.onRemove?.();
15771
+ }
15772
+ }
15773
+ }
15774
+ this.publish(entry);
15775
+ if (this.entries.size > 100) {
15776
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
15777
+ if (oldest) {
15778
+ this.entries.delete(oldest[0]);
15779
+ }
15780
+ }
15141
15781
  }
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.");
15782
+ setSession(session) {
15783
+ if (this.session !== undefined && this.session !== session) {
15784
+ this.epoch += 1;
15785
+ for (const projection of this.projections) {
15786
+ projection.onRemove?.();
15787
+ }
15788
+ this.projections.clear();
15789
+ for (const entry of this.entries.values()) {
15790
+ entry.base = undefined;
15791
+ entry.identity = undefined;
15792
+ entry.stale = true;
15793
+ entry.version += 1;
15794
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
15795
+ this.publish(entry);
15796
+ }
15797
+ }
15798
+ this.session = session;
15148
15799
  }
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.");
15800
+ generation() {
15801
+ return this.epoch;
15202
15802
  }
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");
15803
+ version(url) {
15804
+ return this.entry(url).version;
15272
15805
  }
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(() => {});
15806
+ snapshot(url) {
15807
+ return this.entry(url).snapshot;
15808
+ }
15809
+ subscribe(url, listener) {
15810
+ const entry = this.entry(url);
15811
+ entry.listeners.add(listener);
15812
+ return () => entry.listeners.delete(listener);
15813
+ }
15814
+ bind(url, load, client) {
15815
+ const entry = this.entry(url);
15816
+ if (client && entry.client && client !== entry.client) {
15817
+ entry.base = undefined;
15818
+ entry.identity = undefined;
15819
+ entry.stale = true;
15820
+ entry.version += 1;
15821
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
15822
+ for (const projection of this.projections) {
15823
+ projection.transforms.delete(entry);
15824
+ }
15283
15825
  }
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 };
15826
+ entry.client = client ?? entry.client;
15827
+ entry.load = load;
15292
15828
  }
15293
- static getDerivedStateFromProps(props, state) {
15294
- if (props.resolve !== state.resolve) {
15295
- return { error: undefined, hasError: false, resolve: props.resolve };
15829
+ pending(entry) {
15830
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
15831
+ }
15832
+ fetch(url) {
15833
+ const entry = this.entry(url);
15834
+ if (entry.promise) {
15835
+ return entry.promise;
15296
15836
  }
15297
- return null;
15837
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
15838
+ return Promise.resolve();
15839
+ }
15840
+ const { version } = entry;
15841
+ const { epoch } = this;
15842
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
15843
+ this.publish(entry);
15844
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
15845
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
15846
+ return;
15847
+ }
15848
+ if (result.error === null) {
15849
+ this.observe(url, result, epoch);
15850
+ } else {
15851
+ entry.snapshot = { ...entry.snapshot, error: result.error };
15852
+ }
15853
+ }).catch((error) => {
15854
+ if (epoch === this.epoch && version === entry.version) {
15855
+ entry.snapshot = { ...entry.snapshot, error };
15856
+ }
15857
+ }).finally(() => {
15858
+ entry.promise = undefined;
15859
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
15860
+ this.publish(entry);
15861
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
15862
+ this.fetch(url);
15863
+ }
15864
+ });
15865
+ return entry.promise;
15298
15866
  }
15299
- static getDerivedStateFromError(error) {
15300
- return { error, hasError: true };
15867
+ invalidate(identities) {
15868
+ const tags = new Set(identities.map(queryTag));
15869
+ let affected = false;
15870
+ for (const [url, entry] of this.entries) {
15871
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
15872
+ affected = true;
15873
+ this.invalidateEntry(url, entry);
15874
+ }
15875
+ }
15876
+ return affected;
15301
15877
  }
15302
- render() {
15303
- const { hasError, error } = this.state;
15304
- const { children, errorElement } = this.props;
15305
- if (hasError) {
15306
- if (errorElement === undefined) {
15307
- throw error;
15878
+ invalidateEntry(url, entry) {
15879
+ entry.stale = true;
15880
+ entry.version += 1;
15881
+ if (entry.listeners.size > 0) {
15882
+ this.fetch(url);
15883
+ }
15884
+ }
15885
+ invalidateAll() {
15886
+ for (const [url, entry] of this.entries) {
15887
+ this.invalidateEntry(url, entry);
15888
+ }
15889
+ }
15890
+ begin() {
15891
+ return { pending: true, transforms: new Map };
15892
+ }
15893
+ update(projection, url, transform) {
15894
+ const entry = this.entries.get(this.key(url));
15895
+ if (!entry || entry.base === undefined) {
15896
+ return;
15897
+ }
15898
+ const previous = projection.transforms.get(entry);
15899
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
15900
+ entry.version += 1;
15901
+ this.projections.add(projection);
15902
+ this.publish(entry);
15903
+ }
15904
+ finish(projection, outcome) {
15905
+ projection.pending = false;
15906
+ const entries = [...projection.transforms.keys()];
15907
+ if (outcome === "error") {
15908
+ this.projections.delete(projection);
15909
+ projection.onRemove?.();
15910
+ }
15911
+ for (const entry of entries) {
15912
+ this.publish(entry);
15913
+ if (outcome !== "error") {
15914
+ entry.stale = true;
15915
+ }
15916
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
15917
+ if (url && entry.stale) {
15918
+ this.fetch(url);
15308
15919
  }
15309
- return createElement2(AsyncErrorContext.Provider, { value: error }, errorElement);
15310
15920
  }
15311
- return children;
15921
+ }
15922
+ dehydrate() {
15923
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
15924
+ }
15925
+ seedUrl(seed, localOrigin) {
15926
+ const original = new URL(seed.url, this.origin);
15927
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
15928
+ }
15929
+ captureHydration() {
15930
+ const { epoch } = this;
15931
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
15932
+ return (seeds, localOrigin) => {
15933
+ if (epoch === this.epoch) {
15934
+ this.hydrate(seeds.filter((seed) => {
15935
+ const url = this.seedUrl(seed, localOrigin);
15936
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
15937
+ }), localOrigin);
15938
+ }
15939
+ };
15940
+ }
15941
+ hydrate(seeds, localOrigin) {
15942
+ for (const seed of seeds) {
15943
+ const url = this.seedUrl(seed, localOrigin);
15944
+ this.observe(url, {
15945
+ data: seed.data,
15946
+ error: null,
15947
+ identity: seed.identity,
15948
+ local: seed.local ?? false
15949
+ }, this.epoch);
15950
+ }
15312
15951
  }
15313
15952
  }
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 }));
15953
+ // src/client/router/link-utils.ts
15954
+ function navigationHrefPolicy(href, currentOrigin) {
15955
+ for (let index = 0;index < href.length; index += 1) {
15956
+ const code = href.charCodeAt(index);
15957
+ if (code <= 31 || code === 127) {
15958
+ return "blocked";
15959
+ }
15960
+ }
15961
+ let url;
15962
+ try {
15963
+ url = new URL(href, currentOrigin ?? "http://localhost");
15964
+ } catch {
15965
+ return "blocked";
15966
+ }
15967
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
15968
+ return "blocked";
15969
+ }
15970
+ if (currentOrigin === undefined) {
15971
+ return href.startsWith("http://") || href.startsWith("https://") || href.startsWith("//") ? "external" : "internal";
15972
+ }
15973
+ return url.origin === currentOrigin ? "internal" : "external";
15317
15974
  }
15318
- function AwaitInner({ resolve, children }) {
15319
- const value = use(resolve);
15320
- return createElement2(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
15975
+ function applyLinkParams(to, params) {
15976
+ if (!params) {
15977
+ return to;
15978
+ }
15979
+ let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
15980
+ const wildcard = params["*"];
15981
+ if (wildcard !== undefined && url.includes("/*")) {
15982
+ const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
15983
+ url = url.replace("/*", () => `/${encodedWildcard}`);
15984
+ }
15985
+ return url;
15986
+ }
15987
+ function buildHref(to, search, hash, searchDefaults) {
15988
+ let url = to;
15989
+ if (search && Object.keys(search).length > 0) {
15990
+ const params = buildSearchParams(search, searchDefaults);
15991
+ const qs = params.toString();
15992
+ if (qs) {
15993
+ url += `?${qs}`;
15994
+ }
15995
+ }
15996
+ if (hash) {
15997
+ url += `#${hash}`;
15998
+ }
15999
+ return url;
16000
+ }
16001
+ function normalizeHref(href) {
16002
+ const url = new URL(href, "http://localhost");
16003
+ let { pathname } = url;
16004
+ if (pathname !== "/") {
16005
+ pathname = pathname.replace(/\/+$/g, "");
16006
+ }
16007
+ return pathname + url.search + url.hash;
16008
+ }
16009
+ function toLogical(physicalPathname, basePath) {
16010
+ if (basePath && physicalPathname.startsWith(basePath) && (physicalPathname.length === basePath.length || physicalPathname[basePath.length] === "/")) {
16011
+ return physicalPathname.slice(basePath.length) || "/";
16012
+ }
16013
+ return physicalPathname;
15321
16014
  }
15322
16015
 
15323
- // src/client.ts
16016
+ // src/shared/defer.ts
15324
16017
  var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
15325
16018
  function defer(data) {
15326
16019
  if (Object.hasOwn(data, DEFERRED_BRAND)) {
@@ -15332,6 +16025,96 @@ function isDeferred(value) {
15332
16025
  return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
15333
16026
  }
15334
16027
 
16028
+ // src/shared/query-bindings.ts
16029
+ function isContainer(value) {
16030
+ if (!value || typeof value !== "object") {
16031
+ return false;
16032
+ }
16033
+ const prototype = Object.getPrototypeOf(value);
16034
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
16035
+ }
16036
+ function bindQueryData(data, seeds) {
16037
+ return seeds.map((seed) => {
16038
+ const sources = new WeakMap;
16039
+ const index = (value, path) => {
16040
+ if (!isContainer(value) || sources.has(value)) {
16041
+ return;
16042
+ }
16043
+ sources.set(value, path);
16044
+ if (!Array.isArray(value)) {
16045
+ for (const [key, child] of Object.entries(value)) {
16046
+ index(child, [...path, key]);
16047
+ }
16048
+ }
16049
+ };
16050
+ index(seed.data, []);
16051
+ const bindings = [];
16052
+ const visiting = new WeakSet;
16053
+ const visit = (value, target) => {
16054
+ if (!isContainer(value) || visiting.has(value)) {
16055
+ return;
16056
+ }
16057
+ const source = sources.get(value);
16058
+ if (source) {
16059
+ bindings.push({ source, target });
16060
+ return;
16061
+ }
16062
+ visiting.add(value);
16063
+ for (const [key, child] of Object.entries(value)) {
16064
+ visit(child, [...target, key]);
16065
+ }
16066
+ visiting.delete(value);
16067
+ };
16068
+ visit(data, []);
16069
+ return { ...seed, bindings };
16070
+ });
16071
+ }
16072
+ function replace(value, path, next) {
16073
+ const [key, ...rest] = path;
16074
+ if (key === undefined) {
16075
+ return next;
16076
+ }
16077
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
16078
+ return value;
16079
+ }
16080
+ const child = replace(value[key], rest, next);
16081
+ if (child === value[key]) {
16082
+ return value;
16083
+ }
16084
+ const copy = Array.isArray(value) ? [...value] : { ...value };
16085
+ Object.defineProperty(copy, key, {
16086
+ configurable: true,
16087
+ enumerable: true,
16088
+ value: child,
16089
+ writable: true
16090
+ });
16091
+ return copy;
16092
+ }
16093
+ function isDeferredTarget(data, target) {
16094
+ const [key] = target;
16095
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
16096
+ }
16097
+ function projectQueryData(data, seeds, read) {
16098
+ let projected = data;
16099
+ for (const seed of seeds) {
16100
+ const snapshot = read(seed);
16101
+ if (snapshot === undefined) {
16102
+ continue;
16103
+ }
16104
+ for (const binding of seed.bindings ?? []) {
16105
+ if (isDeferredTarget(data, binding.target)) {
16106
+ continue;
16107
+ }
16108
+ let value = snapshot;
16109
+ for (const key of binding.source) {
16110
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
16111
+ }
16112
+ projected = replace(projected, binding.target, value);
16113
+ }
16114
+ }
16115
+ return projected;
16116
+ }
16117
+
15335
16118
  // src/server/render/mixed-cache.ts
15336
16119
  init_registry();
15337
16120
 
@@ -15352,6 +16135,9 @@ init_registry2();
15352
16135
  init_context_logger();
15353
16136
  init_instance();
15354
16137
  init_source_version();
16138
+ function capturedQueryTags() {
16139
+ return currentQueryEnvironment()?.store.dehydrate().map((seed) => queryTag(seed.identity)) ?? [];
16140
+ }
15355
16141
  var mixedCacheKey = Symbol("furin-mixed-loader-cache");
15356
16142
  function cachePathWithSearch(key) {
15357
16143
  const separator = key.indexOf("|");
@@ -15404,7 +16190,11 @@ async function readCachedSegment(entry, revalidate, parentData) {
15404
16190
  return;
15405
16191
  }
15406
16192
  }
15407
- return fromCrossJSON(snapshot.data, {});
16193
+ const environment = currentQueryEnvironment();
16194
+ environment?.store.hydrate(snapshot.queries ?? []);
16195
+ environment?.onRead();
16196
+ const data = fromCrossJSON(snapshot.data, {});
16197
+ return projectQueryData(data, snapshot.queries ?? [], (seed) => seed.data);
15408
16198
  } catch {
15409
16199
  getLogger().warn("Mixed loader cache entry is invalid; loading fresh data");
15410
16200
  }
@@ -15417,7 +16207,8 @@ async function createSegmentSnapshot(data, parentData, parentFieldsRead) {
15417
16207
  })));
15418
16208
  return JSON.stringify({
15419
16209
  data: await toCrossJSONAsync(data),
15420
- dependencies
16210
+ dependencies,
16211
+ queries: bindQueryData(data, currentQueryEnvironment()?.store.dehydrate() ?? []).filter((seed) => (seed.bindings?.length ?? 0) > 0)
15421
16212
  });
15422
16213
  }
15423
16214
  async function acquireSharedSegment(shared, identity) {
@@ -15444,6 +16235,10 @@ async function readSharedSegment(shared, identity, revalidate, parentData) {
15444
16235
  }
15445
16236
  }
15446
16237
  async function commitSharedSegment(shared, identity, lease, cached, revalidate) {
16238
+ const identityTags = new Set(identity.tags);
16239
+ if (capturedQueryTags().some((tag) => !identityTags.has(tag))) {
16240
+ return;
16241
+ }
15447
16242
  try {
15448
16243
  await shared.commit({
15449
16244
  entry: {
@@ -15471,6 +16266,7 @@ function storeLocalSegment(state, generation, key, path, tags, cached) {
15471
16266
  }
15472
16267
  async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, parentFieldsRead, run) {
15473
16268
  const instance = currentInstance();
16269
+ const declaredTags = route.tags ?? [];
15474
16270
  const mode = segment.mode ?? route.mode;
15475
16271
  const revalidate = mode === "isr" ? segment.revalidate ?? 60 : Number.POSITIVE_INFINITY;
15476
16272
  const requestUrl = new URL(ctx.request.url);
@@ -15491,7 +16287,12 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
15491
16287
  mode: mode === "isr" ? "isr" : "ssg",
15492
16288
  path,
15493
16289
  scope: instance.prefix,
15494
- tags: route.tags ?? []
16290
+ tags: [
16291
+ ...new Set([
16292
+ ...declaredTags,
16293
+ ...getAutoInvalidateRegistry().tagsForPath(`${path}${requestUrl.search}`)
16294
+ ])
16295
+ ]
15495
16296
  };
15496
16297
  const stored = shared === undefined ? undefined : await readSharedSegment(shared, identity, revalidate, parentData);
15497
16298
  if (stored !== undefined) {
@@ -15507,7 +16308,7 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
15507
16308
  cachedAt: Date.now(),
15508
16309
  payload: await createSegmentSnapshot(data, parentData, parentFieldsRead)
15509
16310
  };
15510
- storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, route.tags, cached);
16311
+ storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, [...declaredTags, ...capturedQueryTags()], cached);
15511
16312
  if (shared !== undefined && lease !== null) {
15512
16313
  await commitSharedSegment(shared, identity, lease, cached, revalidate);
15513
16314
  }
@@ -15832,6 +16633,70 @@ function isNotFoundError(err) {
15832
16633
  init_context_logger();
15833
16634
  init_instrumentation();
15834
16635
  init_patterns();
16636
+
16637
+ // src/server/sync/query-context.ts
16638
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
16639
+ init_registry();
16640
+ init_instance();
16641
+ var QUERY_CONTEXT = Symbol.for("furin.query.server-context.v1");
16642
+ var contextGlobal = globalThis;
16643
+ var contexts = contextGlobal[QUERY_CONTEXT] ??= new AsyncLocalStorage6;
16644
+ setServerQueryEnvironment(() => contexts.getStore());
16645
+ var trackedQueryPaths = instanceSlot(() => new Set);
16646
+ var deferredQueries = new WeakMap;
16647
+ function deferredQuerySeeds(promise) {
16648
+ return deferredQueries.get(promise);
16649
+ }
16650
+ function captureQueryReads(ctx, run, owner) {
16651
+ const { origin } = new URL(ctx.request.url);
16652
+ const store = new QueryStore(origin);
16653
+ const registry = getAutoInvalidateRegistry();
16654
+ const trackedPaths = trackedQueryPaths();
16655
+ const requestUrl = new URL(ctx.request.url);
16656
+ const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
16657
+ const onRead = () => {
16658
+ const seeds = store.dehydrate();
16659
+ registry.registerLoaderTags(path, seeds.map((seed) => queryTag(seed.identity)), owner ?? "eden-queries");
16660
+ trackedPaths.delete(path);
16661
+ if (seeds.length > 0) {
16662
+ trackedPaths.add(path);
16663
+ }
16664
+ if (trackedPaths.size > 1000) {
16665
+ const oldest = trackedPaths.values().next().value;
16666
+ if (oldest !== undefined) {
16667
+ trackedPaths.delete(oldest);
16668
+ registry.unregisterPath(oldest, "eden-queries");
16669
+ registry.unregisterPath(oldest, "eden-request-queries");
16670
+ }
16671
+ }
16672
+ };
16673
+ return contexts.run({ origin, store, onRead }, async () => {
16674
+ const result = { ...await run() };
16675
+ const seeds = store.dehydrate();
16676
+ if (result.type === "data" && seeds.length > 0) {
16677
+ const captured = [...result.syncData.__furinQueries ?? []];
16678
+ mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
16679
+ result.syncData = { ...result.syncData, __furinQueries: captured };
16680
+ }
16681
+ if (result.type === "data" && result.deferredPromises) {
16682
+ for (const [key, promise] of Object.entries(result.deferredPromises)) {
16683
+ promise.then((value) => {
16684
+ const completed = store.dehydrate();
16685
+ if (completed.length > 0) {
16686
+ const captured = deferredQueries.get(promise) ?? [];
16687
+ mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
16688
+ deferredQueries.set(promise, captured);
16689
+ }
16690
+ }).catch(() => {
16691
+ return;
16692
+ });
16693
+ }
16694
+ }
16695
+ return result;
16696
+ });
16697
+ }
16698
+
16699
+ // src/server/render/loaders.ts
15835
16700
  var REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
15836
16701
  var FURIN_RESERVED_KEY_PREFIX = "__furin";
15837
16702
  var ROUTE_CTX_RESERVED_KEYS = new Set([
@@ -15854,6 +16719,12 @@ function assertPublicLoaderKey(key) {
15854
16719
  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
16720
  }
15856
16721
  }
16722
+ function assertRequestLoaderKey(key, ctx) {
16723
+ assertPublicLoaderKey(key);
16724
+ if (key === "log" || Object.hasOwn(ctx, key) || key in ctx && !Object.hasOwn(Object.prototype, key)) {
16725
+ throw new Error(`[furin] requestLoader data key "${key}" is reserved: it is overwritten by the SSR loader context. Rename this field to avoid conflicts.`);
16726
+ }
16727
+ }
15857
16728
  function isHttpRedirect(res) {
15858
16729
  return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
15859
16730
  }
@@ -15868,7 +16739,7 @@ async function readResponseMessage(res) {
15868
16739
  return res.statusText;
15869
16740
  }
15870
16741
  }
15871
- function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
16742
+ function createLoaderCtx(ctx, accumulatedParentPromise, inheritedRequestFields, onParentFieldAccess) {
15872
16743
  const cache = new Map;
15873
16744
  return new Proxy(ctx, {
15874
16745
  get(target, prop) {
@@ -15881,6 +16752,9 @@ function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
15881
16752
  if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
15882
16753
  return target[prop];
15883
16754
  }
16755
+ if (inheritedRequestFields && Object.hasOwn(inheritedRequestFields, prop)) {
16756
+ return inheritedRequestFields[prop];
16757
+ }
15884
16758
  onParentFieldAccess?.(prop);
15885
16759
  let entry = cache.get(prop);
15886
16760
  if (!entry) {
@@ -15993,6 +16867,8 @@ function runRequestLoaderFields(route, ctx) {
15993
16867
  if (declarations?.length !== route.routeChain.length) {
15994
16868
  throw new Error(`[furin] Missing per-loader request field metadata for ${route.pattern}.`);
15995
16869
  }
16870
+ const declaredKeys = declarations.map((keys) => new Set(keys));
16871
+ const requestKeys = new Set(route.requestKeys);
15996
16872
  const requestContext = createRequestLoaderContext(ctx);
15997
16873
  const results = loaderIndexes.map((index) => {
15998
16874
  const loader = route.routeChain[index]?.requestLoader;
@@ -16003,8 +16879,8 @@ function runRequestLoaderFields(route, ctx) {
16003
16879
  const result = observeLoader(() => invocation, `request:${index}`, ctx.path).then((value) => {
16004
16880
  const data = value;
16005
16881
  for (const key of Object.keys(data)) {
16006
- assertPublicLoaderKey(key);
16007
- if (!declarations[index]?.includes(key)) {
16882
+ assertRequestLoaderKey(key, ctx);
16883
+ if (!declaredKeys[index]?.has(key)) {
16008
16884
  throw new Error(`[furin] requestLoader in ${route.pattern} returned undeclared field "${key}".`);
16009
16885
  }
16010
16886
  }
@@ -16013,27 +16889,36 @@ function runRequestLoaderFields(route, ctx) {
16013
16889
  result.catch(() => {});
16014
16890
  return { index, result };
16015
16891
  });
16016
- const fields = {};
16892
+ let fields = {};
16893
+ const fieldsByLoader = route.routeChain.map((_, boundaryIndex) => {
16894
+ fields = { ...fields };
16895
+ for (const key of declarations[boundaryIndex] ?? []) {
16896
+ if (!requestKeys.has(key)) {
16897
+ continue;
16898
+ }
16899
+ const candidates = results.filter(({ index }) => index <= boundaryIndex && declaredKeys[index]?.has(key));
16900
+ fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
16901
+ for (let index = values.length - 1;index >= 0; index -= 1) {
16902
+ const data = values[index];
16903
+ if (data && Object.hasOwn(data, key)) {
16904
+ return data[key];
16905
+ }
16906
+ }
16907
+ });
16908
+ fields[key].catch(() => {});
16909
+ }
16910
+ return fields;
16911
+ });
16017
16912
  for (const key of route.requestKeys) {
16018
- const candidates = results.filter(({ index }) => declarations[index]?.includes(key));
16019
- if (candidates.length === 0) {
16913
+ if (!Object.hasOwn(fields, key)) {
16020
16914
  throw new Error(`[furin] No requestLoader declares field "${key}" in ${route.pattern}.`);
16021
16915
  }
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
16916
  }
16032
16917
  const noFieldCompletion = Promise.all(results.filter(({ index }) => declarations[index]?.length === 0).map(({ result }) => result)).then(() => {
16033
16918
  return;
16034
16919
  });
16035
16920
  noFieldCompletion.catch(() => {});
16036
- return { fields, noFieldCompletion };
16921
+ return { fields, fieldsByLoader, noFieldCompletion };
16037
16922
  }
16038
16923
  function requestFieldPromises(route, fields, syncData, publicDeferred) {
16039
16924
  for (const key of Object.keys(fields)) {
@@ -16043,19 +16928,21 @@ function requestFieldPromises(route, fields, syncData, publicDeferred) {
16043
16928
  }
16044
16929
  return fields;
16045
16930
  }
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)
16931
+ function withRequestLoaderData(route, ctx, publicResult) {
16932
+ return captureQueryReads(ctx, async () => {
16933
+ const requestFields = runRequestLoaderFields(route, ctx);
16934
+ if (requestFields === undefined) {
16935
+ throw new Error("[furin] internal invariant: requestLoader data requested for a route without requestLoader");
16057
16936
  }
16058
- };
16937
+ await requestFields.noFieldCompletion;
16938
+ return {
16939
+ ...publicResult,
16940
+ deferredPromises: {
16941
+ ...publicResult.deferredPromises ?? {},
16942
+ ...requestFieldPromises(route, requestFields.fields, publicResult.syncData, publicResult.deferredPromises)
16943
+ }
16944
+ };
16945
+ }, "eden-request-queries");
16059
16946
  }
16060
16947
  function mergeLoaderResults(results) {
16061
16948
  const allSync = {};
@@ -16128,6 +17015,15 @@ async function normalizeLoaderError(err, headers) {
16128
17015
  const message = body || "Something went wrong";
16129
17016
  return { error: err, headers, message, status, type: "error" };
16130
17017
  }
17018
+ 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") {
17019
+ let message = "Something went wrong";
17020
+ if ("detail" in err.value && typeof err.value.detail === "string") {
17021
+ message = err.value.detail;
17022
+ } else if ("title" in err.value && typeof err.value.title === "string") {
17023
+ message = err.value.title;
17024
+ }
17025
+ return { error: err, headers, message, status: err.status, type: "error" };
17026
+ }
16131
17027
  if (isFurinRscRenderError(err)) {
16132
17028
  getLogger().error(err);
16133
17029
  return {
@@ -16156,10 +17052,10 @@ function mergeParentData(parent, own, path) {
16156
17052
  }
16157
17053
  return { ...parent, ...own };
16158
17054
  }
16159
- function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, ctxRecord, publicCtxRecord, mixed) {
17055
+ function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, inheritedRequestFields, ctxRecord, publicCtxRecord, mixed) {
16160
17056
  const publicSegment = mixed && (segment.mode ?? route.mode) !== "ssr";
16161
17057
  const parentFieldsRead = new Set;
16162
- const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
17058
+ const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? undefined : inheritedRequestFields, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
16163
17059
  return observeLoader(() => {
16164
17060
  const run = async () => await segment.loader?.(loaderCtx) ?? {};
16165
17061
  return publicSegment ? cacheMixedPublicLoader(route, ctx, segment, index, publicParent, parentFieldsRead, run) : run();
@@ -16174,13 +17070,13 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
16174
17070
  let accumulatedParentPromise = Promise.resolve({});
16175
17071
  let publicParentPromise = Promise.resolve({});
16176
17072
  let loaderIndex = 0;
16177
- for (const r of route.routeChain) {
17073
+ for (const [routeIndex, r] of route.routeChain.entries()) {
16178
17074
  const parentAccum = accumulatedParentPromise;
16179
17075
  const publicParent = publicParentPromise;
16180
17076
  const privateSegment = mixed && (r.mode ?? route.mode) === "ssr";
16181
17077
  if (r.loader) {
16182
17078
  const index = loaderIndex;
16183
- const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, ctxRecord, publicCtxRecord, mixed);
17079
+ const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, requestFields?.fieldsByLoader[routeIndex - 1], ctxRecord, publicCtxRecord, mixed);
16184
17080
  loaderIndex += 1;
16185
17081
  loaderMap.set(r, loaderPromise);
16186
17082
  accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => mergeParentData(acc, own, ctx.path));
@@ -16194,7 +17090,7 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
16194
17090
  }
16195
17091
  }
16196
17092
  }
16197
- const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
17093
+ const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, requestFields?.fields, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
16198
17094
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
16199
17095
  await requestFields?.noFieldCompletion;
16200
17096
  const headers = {};
@@ -16237,10 +17133,10 @@ function createPublicLoaderContext(ctx) {
16237
17133
  return publicContext;
16238
17134
  }
16239
17135
  function runLoaders(route, ctx) {
16240
- return runLoadersInternal(route, ctx, true, false);
17136
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, false));
16241
17137
  }
16242
17138
  function runPublicLoaders(route, ctx) {
16243
- return runLoadersInternal(route, ctx, false, false);
17139
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, false));
16244
17140
  }
16245
17141
  function hasSsrLoaderAncestor(route) {
16246
17142
  return route.routeChain.some((entry) => entry.mode === "ssr" && entry.loader !== undefined);
@@ -16250,13 +17146,13 @@ function hasMixedLoaderModes(route) {
16250
17146
  return route.routeChain.some((entry) => entry.loader !== undefined && entry.mode !== undefined && (entry.mode !== route.mode || entry.mode === "isr" && (entry.revalidate ?? 60) !== pageRevalidate));
16251
17147
  }
16252
17148
  function runMixedLoaders(route, ctx) {
16253
- return runLoadersInternal(route, ctx, true, true);
17149
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, true));
16254
17150
  }
16255
17151
  function runRouteLoaders(route, ctx) {
16256
17152
  return hasMixedLoaderModes(route) ? runMixedLoaders(route, ctx) : runLoaders(route, ctx);
16257
17153
  }
16258
17154
  function runSegmentPublicLoaders(route, ctx) {
16259
- return runLoadersInternal(route, ctx, false, true);
17155
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, true));
16260
17156
  }
16261
17157
  function hasRequestLoader(route) {
16262
17158
  return route.routeChain.some((entry) => entry.requestLoader !== undefined);
@@ -16270,9 +17166,9 @@ import { prerender } from "react-dom/static.edge";
16270
17166
  import {
16271
17167
  Children,
16272
17168
  cloneElement,
16273
- createElement as createElement3,
17169
+ createElement,
16274
17170
  isValidElement,
16275
- use as use2
17171
+ use
16276
17172
  } from "react";
16277
17173
 
16278
17174
  // src/rsc/client-codec.ts
@@ -16292,7 +17188,7 @@ var RSC_SOURCE = Symbol.for("furin.rsc.source");
16292
17188
 
16293
17189
  // src/rsc/shared.tsx
16294
17190
  function RscNode({ state }) {
16295
- return use2(state.tree);
17191
+ return use(state.tree);
16296
17192
  }
16297
17193
  function decodeFlightBytes(bytes) {
16298
17194
  return decodeFlight(new ReadableStream({
@@ -16303,7 +17199,7 @@ function decodeFlightBytes(bytes) {
16303
17199
  }));
16304
17200
  }
16305
17201
  function createRenderableSource(state) {
16306
- const element = createElement3(RscNode, { state });
17202
+ const element = createElement(RscNode, { state });
16307
17203
  return new Proxy(element, {
16308
17204
  get(target, property, receiver) {
16309
17205
  if (property === RSC_SOURCE) {
@@ -16560,6 +17456,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
16560
17456
  const { frame } = envelope;
16561
17457
  if (frame.type === "data") {
16562
17458
  dataValue = fromCrossJSON(frame.value, {});
17459
+ if (frame.deferredKeys.length > 0 && dataValue && typeof dataValue === "object") {
17460
+ const data = dataValue;
17461
+ data.__furinQueries ??= [];
17462
+ }
16563
17463
  for (const key of frame.deferredKeys) {
16564
17464
  deferredPromises[key] = new Promise((resolve, reject) => {
16565
17465
  resolvers.set(key, { reject, resolve });
@@ -16594,6 +17494,10 @@ async function parseRouteFrameLines(firstLine, readLine) {
16594
17494
  } else if (frame.type === "rsc-error") {
16595
17495
  throw new Error(`[furin] RSC stream failed (${frame.digest})`);
16596
17496
  } else if (frame.type === "defer-resolve") {
17497
+ if (frame.queries && dataValue && typeof dataValue === "object") {
17498
+ const data = dataValue;
17499
+ mergeQuerySeeds(data.__furinQueries ??= [], fromCrossJSON(frame.queries, {}));
17500
+ }
16597
17501
  const value = fromCrossJSON(frame.value, {});
16598
17502
  const ids = new Set;
16599
17503
  collectRscDescriptorIds(value, ids);
@@ -16625,42 +17529,219 @@ async function parseRouteFrameLines(firstLine, readLine) {
16625
17529
  if (data === null || typeof data !== "object" || Array.isArray(data)) {
16626
17530
  throw new Error("[furin] route data frame must decode to an object");
16627
17531
  }
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
- };
17532
+ const completion = (async () => {
17533
+ for (;; ) {
17534
+ const line = await readLine();
17535
+ if (line === undefined) {
17536
+ break;
17537
+ }
17538
+ processLine(line);
17539
+ }
17540
+ if (pending.size > 0) {
17541
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
17542
+ }
17543
+ if (deferredRscValues.size > 0) {
17544
+ throw new Error("[furin] route frame stream ended before an RSC source completed");
17545
+ }
17546
+ for (const [key, resolver] of resolvers) {
17547
+ resolver.reject(new Error(`[furin] deferred stream closed before "${key}" was resolved`));
17548
+ }
17549
+ resolvers.clear();
17550
+ })().catch((error) => {
17551
+ rejectPending(error);
17552
+ throw error;
17553
+ });
17554
+ return {
17555
+ abort: rejectPending,
17556
+ completion,
17557
+ deferredPromises,
17558
+ syncData: data
17559
+ };
17560
+ }
17561
+
17562
+ // src/server/render/ppr-document.ts
17563
+ init_context_logger();
17564
+ init_instance();
17565
+
17566
+ // src/server/render/document.tsx
17567
+ import { createElement as createElement3 } from "react";
17568
+
17569
+ // src/client/document.tsx
17570
+ import { createContext, createElement as createElement2, useContext } from "react";
17571
+ import { preloadModule } from "react-dom";
17572
+ import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
17573
+ var DocumentContext = createContext(null);
17574
+ function serializeJson(value) {
17575
+ return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
17576
+ }
17577
+ function DocumentProvider({
17578
+ children,
17579
+ value
17580
+ }) {
17581
+ return /* @__PURE__ */ jsxDEV(DocumentContext.Provider, {
17582
+ value,
17583
+ children
17584
+ }, undefined, false, undefined, this);
17585
+ }
17586
+ function renderMeta(meta, key) {
17587
+ if ("title" in meta) {
17588
+ return /* @__PURE__ */ jsxDEV("title", {
17589
+ children: meta.title
17590
+ }, key, false, undefined, this);
17591
+ }
17592
+ if ("script:ld+json" in meta) {
17593
+ return /* @__PURE__ */ jsxDEV("script", {
17594
+ dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
17595
+ type: "application/ld+json"
17596
+ }, key, false, undefined, this);
17597
+ }
17598
+ if ("tagName" in meta) {
17599
+ const { tagName, ...attributes } = meta;
17600
+ return createElement2(tagName, { ...attributes, key });
17601
+ }
17602
+ return createElement2("meta", { ...meta, key });
17603
+ }
17604
+ function HeadContent() {
17605
+ const state = useContext(DocumentContext);
17606
+ if (state === null) {
17607
+ throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
17608
+ }
17609
+ for (const href of state.assets.modulePreloads ?? []) {
17610
+ preloadModule(href, { as: "script", nonce: state.nonce });
17611
+ }
17612
+ const occurrences = new Map;
17613
+ const descriptorKey = (descriptor) => {
17614
+ const identity = JSON.stringify(descriptor);
17615
+ const occurrence = occurrences.get(identity) ?? 0;
17616
+ occurrences.set(identity, occurrence + 1);
17617
+ return `${identity}:${occurrence}`;
17618
+ };
17619
+ return /* @__PURE__ */ jsxDEV(Fragment, {
17620
+ children: [
17621
+ state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17622
+ dangerouslySetInnerHTML: { __html: state.assets.extensionErrorFilterScript },
17623
+ "data-furin-extension-error-filter": "",
17624
+ nonce: state.nonce
17625
+ }, undefined, false, undefined, this),
17626
+ /* @__PURE__ */ jsxDEV("meta", {
17627
+ charSet: "utf-8",
17628
+ "data-furin-head": ""
17629
+ }, undefined, false, undefined, this),
17630
+ /* @__PURE__ */ jsxDEV("meta", {
17631
+ content: "width=device-width, initial-scale=1.0",
17632
+ name: "viewport"
17633
+ }, undefined, false, undefined, this),
17634
+ state.assets.buildId ? /* @__PURE__ */ jsxDEV("meta", {
17635
+ content: state.assets.buildId,
17636
+ name: "furin-build-id"
17637
+ }, undefined, false, undefined, this) : null,
17638
+ state.assets.staticMode ? /* @__PURE__ */ jsxDEV("meta", {
17639
+ content: "static",
17640
+ name: "furin-mode"
17641
+ }, undefined, false, undefined, this) : null,
17642
+ state.assets.faviconHref ? /* @__PURE__ */ jsxDEV("link", {
17643
+ href: state.assets.faviconHref,
17644
+ rel: "icon"
17645
+ }, undefined, false, undefined, this) : null,
17646
+ state.assets.stylesheets.map((href) => /* @__PURE__ */ jsxDEV("link", {
17647
+ crossOrigin: "",
17648
+ href,
17649
+ rel: "stylesheet"
17650
+ }, href, false, undefined, this)),
17651
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
17652
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV("link", {
17653
+ ...link
17654
+ }, descriptorKey(link), false, undefined, this)),
17655
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV("script", {
17656
+ ...attributes,
17657
+ nonce: state.nonce ?? attributes.nonce,
17658
+ children
17659
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
17660
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV("style", {
17661
+ dangerouslySetInnerHTML: { __html: children },
17662
+ nonce: state.nonce,
17663
+ type
17664
+ }, descriptorKey({ children, type }), false, undefined, this))
17665
+ ]
17666
+ }, undefined, true, undefined, this);
17667
+ }
17668
+ function Scripts() {
17669
+ const state = useContext(DocumentContext);
17670
+ if (state === null) {
17671
+ throw new Error("[furin] <Scripts /> must be rendered inside the root layout.");
17672
+ }
17673
+ return /* @__PURE__ */ jsxDEV(Fragment, {
17674
+ children: [
17675
+ state.syncJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17676
+ dangerouslySetInnerHTML: { __html: state.syncJson },
17677
+ id: "__FURIN_SYNC__",
17678
+ type: "application/json"
17679
+ }, undefined, false, undefined, this),
17680
+ state.dataJson === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17681
+ dangerouslySetInnerHTML: { __html: state.dataJson },
17682
+ id: "__FURIN_DATA__",
17683
+ type: "application/json"
17684
+ }, undefined, false, undefined, this),
17685
+ state.routeFrames === undefined ? null : /* @__PURE__ */ jsxDEV("template", {
17686
+ dangerouslySetInnerHTML: {
17687
+ __html: state.routeFrames.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
17688
+ },
17689
+ "data-furin-document-state": "",
17690
+ id: "__FURIN_ROUTE_FRAMES__"
17691
+ }, undefined, false, undefined, this),
17692
+ /* @__PURE__ */ jsxDEV("script", {
17693
+ dangerouslySetInnerHTML: { __html: serializeJson(state.head ?? {}) },
17694
+ "data-furin-scripts": "",
17695
+ id: "__FURIN_HEAD__",
17696
+ type: "application/json"
17697
+ }, undefined, false, undefined, this),
17698
+ state.assets.frameworkModules.map((src) => /* @__PURE__ */ jsxDEV("script", {
17699
+ crossOrigin: "",
17700
+ "data-furin-framework-module": "",
17701
+ nonce: state.nonce,
17702
+ src,
17703
+ type: "module"
17704
+ }, src, false, undefined, this)),
17705
+ state.assets.entryModule === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
17706
+ crossOrigin: "",
17707
+ "data-furin-entry": "",
17708
+ nonce: state.nonce,
17709
+ src: state.assets.entryModule,
17710
+ type: "module"
17711
+ }, undefined, false, undefined, this)
17712
+ ]
17713
+ }, undefined, true, undefined, this);
17714
+ }
17715
+ function FurinDocumentFallback({ children }) {
17716
+ return /* @__PURE__ */ jsxDEV("html", {
17717
+ lang: "en",
17718
+ children: [
17719
+ /* @__PURE__ */ jsxDEV("head", {
17720
+ children: /* @__PURE__ */ jsxDEV(HeadContent, {}, undefined, false, undefined, this)
17721
+ }, undefined, false, undefined, this),
17722
+ /* @__PURE__ */ jsxDEV("body", {
17723
+ children: [
17724
+ children,
17725
+ /* @__PURE__ */ jsxDEV(Scripts, {}, undefined, false, undefined, this)
17726
+ ]
17727
+ }, undefined, true, undefined, this)
17728
+ ]
17729
+ }, undefined, true, undefined, this);
16656
17730
  }
16657
17731
 
16658
- // src/server/render/ppr-document.ts
16659
- init_context_logger();
16660
- init_instance();
17732
+ // src/client/query.tsx
17733
+ import {
17734
+ createContext as createContext2,
17735
+ useCallback,
17736
+ useContext as useContext2,
17737
+ useEffect,
17738
+ useSyncExternalStore
17739
+ } from "react";
17740
+ var QUERY_CONTEXT2 = Symbol.for("furin.query.context.v1");
17741
+ var contextGlobal2 = globalThis;
17742
+ var QueryStoreContext = contextGlobal2[QUERY_CONTEXT2] ??= createContext2(null);
16661
17743
 
16662
17744
  // src/server/render/document.tsx
16663
- import { createElement as createElement4 } from "react";
16664
17745
  init_instance();
16665
17746
  init_config();
16666
17747
  function withDocumentState(element, assets, head, data, nonce) {
@@ -16679,7 +17760,9 @@ function withDocumentState(element, assets, head, data, nonce) {
16679
17760
  routeFrames,
16680
17761
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
16681
17762
  };
16682
- return createElement4(DocumentProvider, { value: state }, element);
17763
+ const queries = new QueryStore(undefined);
17764
+ queries.hydrate(data?.__furinQueries ?? []);
17765
+ return createElement3(DocumentProvider, { value: state }, createElement3(QueryStoreContext.Provider, { value: queries }, element));
16683
17766
  }
16684
17767
 
16685
17768
  // src/server/render/ppr-document.ts
@@ -16687,10 +17770,9 @@ init_ppr_request();
16687
17770
 
16688
17771
  // src/server/render/ssr.ts
16689
17772
  import { createElement as createElement7 } from "react";
16690
- import { renderToReadableStream } from "react-dom/server";
16691
17773
 
16692
17774
  // src/client/router/context.ts
16693
- import { createContext as createContext3, useContext as useContext2 } from "react";
17775
+ import { createContext as createContext3, useCallback as useCallback2, useContext as useContext3, useMemo } from "react";
16694
17776
  var RouterContext = createContext3(null);
16695
17777
  var CLIENT_FALLBACK_ROUTER = {
16696
17778
  basePath: "",
@@ -16715,15 +17797,15 @@ var CLIENT_FALLBACK_ROUTER = {
16715
17797
  search: {},
16716
17798
  searchRoutes: []
16717
17799
  };
16718
- function useRouter() {
16719
- const ctx = useContext2(RouterContext);
17800
+ function useRouterContext() {
17801
+ const ctx = useContext3(RouterContext);
16720
17802
  return ctx ?? CLIENT_FALLBACK_ROUTER;
16721
17803
  }
16722
17804
 
16723
17805
  // src/client/router/search-store.ts
16724
17806
  import { createContext as createContext4 } from "react";
16725
17807
  function searchSnapshotChanged(a, b) {
16726
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
17808
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
16727
17809
  }
16728
17810
  function createSearchStore(initialSnapshot) {
16729
17811
  let snapshot = initialSnapshot;
@@ -16760,6 +17842,7 @@ function createSearchStore(initialSnapshot) {
16760
17842
  function searchSnapshotFromRouterContext(context) {
16761
17843
  return {
16762
17844
  currentHref: context.currentHref,
17845
+ currentPattern: context.currentPattern,
16763
17846
  navigate: context.navigate,
16764
17847
  search: context.search,
16765
17848
  searchRoutes: context.searchRoutes
@@ -16767,6 +17850,7 @@ function searchSnapshotFromRouterContext(context) {
16767
17850
  }
16768
17851
  var FALLBACK_SEARCH_STORE = createSearchStore({
16769
17852
  currentHref: "/",
17853
+ currentPattern: undefined,
16770
17854
  navigate: (href, _opts) => {
16771
17855
  if (typeof window !== "undefined") {
16772
17856
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -16834,12 +17918,14 @@ function serializeCompactJsonLine(value) {
16834
17918
  // src/server/render/ssr.ts
16835
17919
  init_context_logger();
16836
17920
  init_instance();
17921
+ init_schema_merge();
17922
+ init_schemas();
16837
17923
 
16838
17924
  // src/server/render/element.tsx
16839
17925
  import { createElement as createElement6 } from "react";
16840
17926
 
16841
17927
  // src/client/boundaries.tsx
16842
- import { Component as Component2, Fragment as Fragment2 } from "react";
17928
+ import { Component, Fragment as Fragment2 } from "react";
16843
17929
 
16844
17930
  // src/shared/error.ts
16845
17931
  function getPublicErrorMessage(error) {
@@ -16851,7 +17937,57 @@ function getPublicErrorMessage(error) {
16851
17937
  }
16852
17938
 
16853
17939
  // src/client/link.tsx
16854
- import { createElement as createElement5, useCallback, useEffect, useRef } from "react";
17940
+ import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef } from "react";
17941
+
17942
+ // src/shared/page-key.ts
17943
+ function identityValue(value) {
17944
+ return Object.is(value, -0) ? "-0" : String(value);
17945
+ }
17946
+ function pageKey(pattern, data, remountDeps) {
17947
+ const { params, query } = data;
17948
+ if (remountDeps) {
17949
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
17950
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
17951
+ }
17952
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
17953
+ if (left < right) {
17954
+ return -1;
17955
+ }
17956
+ return left > right ? 1 : 0;
17957
+ });
17958
+ return JSON.stringify([
17959
+ pattern,
17960
+ entries.map(([name, value]) => [
17961
+ name,
17962
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
17963
+ ])
17964
+ ]);
17965
+ }
17966
+
17967
+ // src/client/route-api.tsx
17968
+ import { createContext as createContext5, createElement as createElement4, useContext as useContext4 } from "react";
17969
+ var RESERVED_RENDER_KEYS = new Set([
17970
+ "catch",
17971
+ "children",
17972
+ "finally",
17973
+ "key",
17974
+ "ref",
17975
+ "then",
17976
+ "toJSON"
17977
+ ]);
17978
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
17979
+ var contextGlobal3 = globalThis;
17980
+ var RouteContext = contextGlobal3[ROUTE_CONTEXT] ??= createContext5(null);
17981
+ function withRouteSnapshot(element, pattern, props) {
17982
+ const {
17983
+ params,
17984
+ path: _path,
17985
+ query: _query,
17986
+ ...data
17987
+ } = props;
17988
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
17989
+ return createElement4(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
17990
+ }
16855
17991
 
16856
17992
  // src/client/server-error.ts
16857
17993
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
@@ -16918,7 +18054,7 @@ function LinkInteractive({
16918
18054
  href: _href,
16919
18055
  ...anchorProps
16920
18056
  }) {
16921
- const router2 = useRouter();
18057
+ const router2 = useRouterContext();
16922
18058
  const anchorRef = useRef(null);
16923
18059
  const intentTimerRef = useRef(null);
16924
18060
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -16926,15 +18062,15 @@ function LinkInteractive({
16926
18062
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
16927
18063
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
16928
18064
  const { prefetch } = router2;
16929
- const triggerPrefetch = useCallback(() => {
18065
+ const triggerPrefetch = useCallback3(() => {
16930
18066
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
16931
18067
  }, [prefetch, logicalHref, effectiveStaleTime]);
16932
- useEffect(() => {
18068
+ useEffect2(() => {
16933
18069
  if (effectivePreload === "render") {
16934
18070
  triggerPrefetch();
16935
18071
  }
16936
18072
  }, [effectivePreload, triggerPrefetch]);
16937
- useEffect(() => {
18073
+ useEffect2(() => {
16938
18074
  if (effectivePreload !== "viewport" || !anchorRef.current) {
16939
18075
  return;
16940
18076
  }
@@ -16947,7 +18083,7 @@ function LinkInteractive({
16947
18083
  observer.observe(anchorRef.current);
16948
18084
  return () => observer.disconnect();
16949
18085
  }, [effectivePreload, triggerPrefetch]);
16950
- useEffect(() => () => {
18086
+ useEffect2(() => () => {
16951
18087
  if (intentTimerRef.current !== null) {
16952
18088
  clearTimeout(intentTimerRef.current);
16953
18089
  intentTimerRef.current = null;
@@ -17370,7 +18506,7 @@ function normalizeCaughtError(error) {
17370
18506
  return normalized;
17371
18507
  }
17372
18508
 
17373
- class FurinErrorBoundary extends Component2 {
18509
+ class FurinErrorBoundary extends Component {
17374
18510
  state = {
17375
18511
  digest: null,
17376
18512
  epoch: 0,
@@ -17420,7 +18556,7 @@ class FurinErrorBoundary extends Component2 {
17420
18556
  }
17421
18557
  }
17422
18558
 
17423
- class FurinNotFoundBoundary extends Component2 {
18559
+ class FurinNotFoundBoundary extends Component {
17424
18560
  state = { epoch: 0, error: null };
17425
18561
  static getDerivedStateFromError(error) {
17426
18562
  return { error };
@@ -17473,26 +18609,35 @@ function wrapSegmentBoundaries(inner, segment, options) {
17473
18609
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
17474
18610
  function buildElement(route, data, rootLayout) {
17475
18611
  const Component = route.page.component;
17476
- let element = createElement6(Component, data);
18612
+ let element = createElement6(Component, {
18613
+ ...data,
18614
+ key: pageKey(route.pattern, data, route.page._route.remountDeps)
18615
+ });
17477
18616
  const byDepth = new Map;
17478
18617
  const legacyRoute = route;
17479
18618
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
17480
- byDepth.set(segment.depth, segment);
18619
+ const boundaries = byDepth.get(segment.depth) ?? [];
18620
+ boundaries.unshift(segment);
18621
+ byDepth.set(segment.depth, boundaries);
17481
18622
  }
17482
18623
  for (let i = route.routeChain.length - 1;i >= 1; i -= 1) {
17483
- element = wrapSegmentBoundaries(element, byDepth.get(i), undefined);
18624
+ for (const segment of byDepth.get(i) ?? []) {
18625
+ element = wrapSegmentBoundaries(element, segment, undefined);
18626
+ }
17484
18627
  const routeEntry = route.routeChain[i];
17485
18628
  if (routeEntry?.layout) {
17486
18629
  const Layout = routeEntry.layout;
17487
18630
  element = createElement6(Layout, data, element);
17488
18631
  }
17489
18632
  }
17490
- element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
18633
+ for (const segment of byDepth.get(0) ?? []) {
18634
+ element = wrapSegmentBoundaries(element, segment, undefined);
18635
+ }
17491
18636
  if (rootLayout.layout) {
17492
18637
  const RootLayoutComponent = rootLayout.layout;
17493
18638
  element = createElement6(RootLayoutComponent, data, element);
17494
18639
  }
17495
- return element;
18640
+ return withRouteSnapshot(element, route.pattern, data);
17496
18641
  }
17497
18642
  function wrapRootLayout(element, data, rootLayout) {
17498
18643
  if (!rootLayout.layout) {
@@ -17539,14 +18684,41 @@ function buildErrorElement(component, error, digest, messageOverride, status) {
17539
18684
  }, undefined, false, undefined, this);
17540
18685
  }
17541
18686
 
18687
+ // src/server/render/react-stream.ts
18688
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "async_hooks";
18689
+ import { renderToReadableStream as renderReactStream } from "react-dom/server";
18690
+
18691
+ // src/client/client-module.ts
18692
+ import { preloadModule as preloadModule2 } from "react-dom";
18693
+ var resolveModuleHrefs = () => [];
18694
+ var resolveNonce = () => {
18695
+ return;
18696
+ };
18697
+ function setClientModuleNonceResolver(resolver) {
18698
+ resolveNonce = resolver;
18699
+ }
18700
+ function setClientModuleHrefResolver(resolver) {
18701
+ resolveModuleHrefs = resolver;
18702
+ }
18703
+
18704
+ // src/server/render/react-stream.ts
18705
+ var renderNonces = new AsyncLocalStorage7;
18706
+ setClientModuleNonceResolver(() => renderNonces.getStore());
18707
+ function renderToReadableStream(element, options) {
18708
+ const nonce = options?.nonce;
18709
+ return renderNonces.run(typeof nonce === "string" ? nonce : nonce?.script, () => renderReactStream(element, options));
18710
+ }
18711
+
17542
18712
  // src/server/render/route-frame-transport.ts
17543
18713
  async function serializeDeferredRouteFrame(key, promise, idPrefix) {
17544
18714
  try {
17545
18715
  const { rscFrames, value } = serializeRouteFrameValue(await promise, idPrefix);
18716
+ const queries = deferredQuerySeeds(promise);
17546
18717
  return serializeRouteFrame({
17547
18718
  key,
17548
18719
  type: "defer-resolve",
17549
- value
18720
+ value,
18721
+ ...queries && { queries: toCrossJSON(queries) }
17550
18722
  }) + rscFrames;
17551
18723
  } catch (error) {
17552
18724
  return serializeRouteFrame({
@@ -17576,16 +18748,17 @@ function createDeferredRouteFrameStream(syncData, deferredPromises) {
17576
18748
  });
17577
18749
  }
17578
18750
  // src/server/render/template.ts
18751
+ import { readFileSync as readFileSync3 } from "fs";
17579
18752
  init_plugin2();
17580
18753
  init_instrumentation();
17581
18754
  init_instance();
17582
- import { readFileSync as readFileSync3 } from "fs";
17583
18755
  var instanceTemplateState = instanceSlot(() => ({
17584
18756
  devAssets: null,
17585
18757
  devCache: null,
17586
18758
  prodAssets: null,
17587
18759
  prodContent: null,
17588
- prodPath: null
18760
+ prodPath: null,
18761
+ prodPreload: null
17589
18762
  }));
17590
18763
  var DEV_TEMPLATE_TTL_MS = 1000;
17591
18764
  var TAG_ATTRIBUTE_PATTERN = /([A-Za-z][\w:-]*)="([^"]*)"/g;
@@ -17726,6 +18899,13 @@ function readDocumentAssets(state) {
17726
18899
  state.prodAssets = documentAssetsFromTemplate(template);
17727
18900
  return state.prodAssets;
17728
18901
  }
18902
+ function setProductionPreloadManifest(manifest, instance) {
18903
+ instanceTemplateState(instance).prodPreload = manifest;
18904
+ }
18905
+ function getProductionPreloadManifest() {
18906
+ return instanceTemplateState().prodPreload ?? instanceTemplateState(defaultInstanceBucket()).prodPreload;
18907
+ }
18908
+ setClientModuleHrefResolver((key) => getProductionPreloadManifest()?.modules[key] ?? []);
17729
18909
 
17730
18910
  // src/server/render/ssr.ts
17731
18911
  function withSSRRouterContext(element, contextValue) {
@@ -17801,7 +18981,8 @@ async function renderElementWithShellFallback(element, errorComponent, ssrContex
17801
18981
  }
17802
18982
  }
17803
18983
  function assertDeferredModeAllowed(route, deferredPromises) {
17804
- const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !route.requestKeys?.includes(key));
18984
+ const requestKeys = new Set(route.requestKeys);
18985
+ const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !requestKeys.has(key));
17805
18986
  if (deferredKeys.length > 0 && route.mode !== "ssr" && !hasSsrLoaderAncestor(route)) {
17806
18987
  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
18988
  }
@@ -17836,6 +19017,10 @@ function resolveDocumentAssets(ctx) {
17836
19017
  }
17837
19018
  return documentAssetsFromTemplate(generateIndexHtml());
17838
19019
  }
19020
+ function withRouteModulePreloads(assets, pattern) {
19021
+ const modulePreloads = getProductionPreloadManifest()?.routes[pattern];
19022
+ return modulePreloads ? { ...assets, modulePreloads } : assets;
19023
+ }
17839
19024
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
17840
19025
  const loaderStart = Date.now();
17841
19026
  const loaderResult = precomputedLoaderResult ?? await runRouteLoaders(route, ctx);
@@ -17843,7 +19028,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17843
19028
  if (loaderResult.type === "redirect") {
17844
19029
  return loaderResult.response;
17845
19030
  }
17846
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
19031
+ if (throwOnFailure && loaderResult.type === "error") {
17847
19032
  throw loaderResult.error;
17848
19033
  }
17849
19034
  const isNotFound = loaderResult.type === "not-found";
@@ -17854,7 +19039,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17854
19039
  assertDeferredModeAllowed(route, deferredPromises);
17855
19040
  const { headers } = loaderResult;
17856
19041
  const componentProps = deferredPromises === undefined ? syncData : { ...syncData, ...deferredPromises };
17857
- const assets = await resolveDocumentAssets(ctx);
19042
+ const assets = withRouteModulePreloads(await resolveDocumentAssets(ctx), route.pattern);
17858
19043
  const errorComponent = route.error ?? root.error;
17859
19044
  let element;
17860
19045
  let headData;
@@ -17882,6 +19067,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
17882
19067
  const ssrContext = {
17883
19068
  basePath: resolvedBasePath,
17884
19069
  currentHref: currentHrefFromContext(ctx, resolvedBasePath),
19070
+ currentPattern: route.pattern,
17885
19071
  defaultPreload: "intent",
17886
19072
  defaultPreloadDelay: 50,
17887
19073
  defaultPreloadStaleTime: 30000,
@@ -17937,9 +19123,30 @@ async function renderBufferedResult(prepared, route, root) {
17937
19123
  headers,
17938
19124
  html,
17939
19125
  ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
19126
+ queryTags: queryTagsFromData(syncData),
17940
19127
  status: prepared.status
17941
19128
  };
17942
19129
  }
19130
+ async function normalizePrerenderContext(route, ctx) {
19131
+ const parsedParams = await parseRouteParams(ctx.params, mergeRouteSchemas(route.routeChain, "params"));
19132
+ if (!parsedParams.ok) {
19133
+ throw new Error(`[furin] Invalid prerender params for "${route.pattern}".`, {
19134
+ cause: parsedParams.errors
19135
+ });
19136
+ }
19137
+ ctx.params = parsedParams.params;
19138
+ const querySchema = mergeRouteSchemas(route.routeChain, "query");
19139
+ if (querySchema === undefined) {
19140
+ return;
19141
+ }
19142
+ const parsedQuery = await parseRouteQuery(new URL(ctx.request.url), querySchema);
19143
+ if (!parsedQuery.ok) {
19144
+ throw new Error(`[furin] Invalid prerender query for "${route.pattern}".`, {
19145
+ cause: parsedQuery.errors
19146
+ });
19147
+ }
19148
+ ctx.query = parsedQuery.query;
19149
+ }
17943
19150
  function renderForPath(route, params, root, origin, mode, basePath, searchRoutes, search, requestContext) {
17944
19151
  return runInSyntheticRenderScope(async () => {
17945
19152
  const resolvedPath = resolvePath(route.pattern, params);
@@ -17965,6 +19172,9 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
17965
19172
  request: new Request(requestUrl),
17966
19173
  set: { headers: {} }
17967
19174
  };
19175
+ if (requestContext === undefined) {
19176
+ await normalizePrerenderContext(route, ctx);
19177
+ }
17968
19178
  const loaderResult = await (hasMixedLoaderModes(route) ? runSegmentPublicLoaders(route, ctx) : runPublicLoaders(route, ctx));
17969
19179
  const prepared = await prepareRender(route, ctx, root, basePath, true, loaderResult, searchRoutes);
17970
19180
  if (prepared instanceof Response) {
@@ -18323,7 +19533,7 @@ async function prerenderPprDocument(route, ctx, root, buildId, searchRoutes, bas
18323
19533
  prefix,
18324
19534
  version: 1
18325
19535
  },
18326
- tags: route.tags
19536
+ tags: [...route.tags ?? [], ...queryTagsFromData(result.syncData)]
18327
19537
  };
18328
19538
  }
18329
19539
  async function resumePprDocument(route, ctx, root, artifact, searchRoutes) {
@@ -18493,6 +19703,10 @@ async function renderSharedPpr(input, identity, lease, revalidate) {
18493
19703
  if (lease === null || !isPprArtifact(result)) {
18494
19704
  return result;
18495
19705
  }
19706
+ const identityTags = new Set(identity.tags);
19707
+ if ((result.tags ?? []).some((tag) => !identityTags.has(tag))) {
19708
+ return result;
19709
+ }
18496
19710
  try {
18497
19711
  await input.pageCache.commit({
18498
19712
  entry: {
@@ -18550,7 +19764,12 @@ async function getSharedPprArtifact(input) {
18550
19764
  mode: "ppr",
18551
19765
  path: input.resolvedPath,
18552
19766
  scope: prefix,
18553
- tags: input.route.tags ?? []
19767
+ tags: [
19768
+ ...new Set([
19769
+ ...input.route.tags ?? [],
19770
+ ...getAutoInvalidateRegistry().tagsForPath(input.cacheKey.slice(input.cacheKey.indexOf(":") + 1))
19771
+ ])
19772
+ ]
18554
19773
  };
18555
19774
  const revalidate = resolveDocumentRevalidate(input.route) ?? 60;
18556
19775
  const lookup = await lookupSharedPpr(input, identity);
@@ -18624,17 +19843,22 @@ async function getPprArtifact(route, ctx, root, buildId, searchRoutes) {
18624
19843
  }
18625
19844
  const pprRoutes = getPprRoutes();
18626
19845
  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)) {
19846
+ if (cached?.artifact.state.buildId !== buildId) {
19847
+ const generation = pprRoutes.captureGeneration(cacheKey);
19848
+ try {
19849
+ const result = await prerenderPprDocument(route, ctx, root, buildId, searchRoutes, undefined);
19850
+ if (!(isPprArtifact(result) && generation.valid)) {
19851
+ return result;
19852
+ }
19853
+ pprRoutes.set(cacheKey, {
19854
+ artifact: result,
19855
+ revalidate: resolveDocumentRevalidate(route) ?? 60
19856
+ });
19857
+ autoInvalidateRegistry.registerLoaderTags(resolvedPath, result.tags, "render:ppr-public-shell");
18630
19858
  return result;
19859
+ } finally {
19860
+ pprRoutes.releaseGeneration(cacheKey, generation);
18631
19861
  }
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
19862
  }
18639
19863
  if (documentMode !== "isr" || Date.now() - cached.artifact.cachedAt < cached.revalidate * 1000) {
18640
19864
  return cached.artifact;
@@ -18679,6 +19903,9 @@ var instanceSsgCache = instanceSlot((instance) => {
18679
19903
  registerCacheInvalidator(cache, instance);
18680
19904
  return cache;
18681
19905
  });
19906
+ function ssgRouteCache(instance) {
19907
+ return instanceSsgCache(instance);
19908
+ }
18682
19909
  var ssgCache = createStoreView(() => instanceSsgCache().store);
18683
19910
  function getSSGCache(key) {
18684
19911
  return instanceSsgCache().get(key);
@@ -18806,7 +20033,6 @@ function initializeFurinLogger(config) {
18806
20033
 
18807
20034
  // src/server/render/not-found.ts
18808
20035
  import { createElement as createElement8 } from "react";
18809
- import { renderToReadableStream as renderToReadableStream2 } from "react-dom/server";
18810
20036
  init_context_logger();
18811
20037
  init_instance();
18812
20038
  init_schemas();
@@ -18862,10 +20088,11 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18862
20088
  render: "not-found"
18863
20089
  }
18864
20090
  });
18865
- const data = { __furinStatus: 404 };
20091
+ const rootData = { params: {}, path: logicalPath, query };
20092
+ const data = { ...rootData, __furinStatus: 404 };
18866
20093
  let reactStream;
18867
20094
  try {
18868
- reactStream = await renderToReadableStream2(withDocumentState(withSSRRouterContext(wrapRootLayout(buildNotFoundElement(root.notFound, notFoundError), { params: {}, path: logicalPath, query }, root.route), notFoundContext), assets, undefined, data, nonce), { nonce });
20095
+ reactStream = await renderToReadableStream(withDocumentState(withSSRRouterContext(wrapRootLayout(buildNotFoundElement(root.notFound, notFoundError), rootData, root.route), notFoundContext), assets, undefined, data, nonce), { nonce });
18869
20096
  } catch (renderError) {
18870
20097
  getLogger().set({
18871
20098
  furin: {
@@ -18874,7 +20101,7 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18874
20101
  render: "not-found"
18875
20102
  }
18876
20103
  });
18877
- reactStream = await renderToReadableStream2(withDocumentState(createElement8(FurinDocumentFallback, null, withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)), assets, undefined, data, nonce), { nonce });
20104
+ reactStream = await renderToReadableStream(withDocumentState(createElement8(FurinDocumentFallback, null, withSSRRouterContext(buildNotFoundElement(undefined, notFoundError), notFoundContext)), assets, undefined, data, nonce), { nonce });
18878
20105
  }
18879
20106
  await reactStream.allReady;
18880
20107
  const html = await streamToString(reactStream);
@@ -18883,7 +20110,9 @@ async function renderRootNotFound(root, request, listenerOrigin) {
18883
20110
  status: 404
18884
20111
  });
18885
20112
  }
20113
+
18886
20114
  // src/server/render/ssg.ts
20115
+ init_registry();
18887
20116
  init_context_logger();
18888
20117
  init_instance();
18889
20118
  init_patterns();
@@ -19011,26 +20240,38 @@ async function prerenderRoute(route, params, root, origin, mode, basePath, searc
19011
20240
  html: renderResult.html,
19012
20241
  ndjson: renderResult.ndjson,
19013
20242
  status: renderResult.status,
19014
- tags: route.tags
20243
+ tags: [...route.tags ?? [], ...renderResult.queryTags ?? []]
19015
20244
  };
19016
20245
  }
19017
- async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
20246
+ async function prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes) {
19018
20247
  const resolvedPath = resolvePath(route.pattern, params);
19019
20248
  const cached = getSSGCache(resolvedPath);
19020
20249
  if (cached) {
19021
20250
  if (cached.tags === route.tags) {
19022
- return cached;
19023
- }
19024
- const taggedEntry = { ...cached, tags: route.tags };
20251
+ return { cacheStored: true, entry: cached };
20252
+ }
20253
+ const taggedEntry = {
20254
+ ...cached,
20255
+ tags: [
20256
+ ...route.tags ?? [],
20257
+ ...(cached.tags ?? []).filter((tag) => queryFromTag(tag) !== undefined)
20258
+ ]
20259
+ };
19025
20260
  setSSGCache(resolvedPath, taggedEntry);
19026
- return taggedEntry;
20261
+ return { cacheStored: true, entry: taggedEntry };
19027
20262
  }
19028
- const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
19029
- if (entry instanceof Response) {
19030
- return entry;
20263
+ const cache = ssgRouteCache();
20264
+ const generation = cache.captureGeneration(resolvedPath);
20265
+ try {
20266
+ const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
20267
+ if (entry instanceof Response || entry.status !== 200 || !generation.valid) {
20268
+ return { cacheStored: false, entry };
20269
+ }
20270
+ setSSGCache(resolvedPath, entry);
20271
+ return { cacheStored: true, entry };
20272
+ } finally {
20273
+ cache.releaseGeneration(resolvedPath, generation);
19031
20274
  }
19032
- setSSGCache(resolvedPath, entry);
19033
- return entry;
19034
20275
  }
19035
20276
  function parseSharedSsgEntry(payload) {
19036
20277
  const value = JSON.parse(payload);
@@ -19042,7 +20283,11 @@ function parseSharedSsgEntry(payload) {
19042
20283
  async function renderAndStoreSharedSsg(input, lease) {
19043
20284
  try {
19044
20285
  const entry = await input.renderFresh();
19045
- if (entry instanceof Response || lease === null) {
20286
+ if (entry instanceof Response || entry.status !== 200 || lease === null) {
20287
+ return { cacheStored: false, entry };
20288
+ }
20289
+ const identityTags = new Set(input.identity.tags);
20290
+ if ((entry.tags ?? []).some((tag) => !identityTags.has(tag))) {
19046
20291
  return { cacheStored: false, entry };
19047
20292
  }
19048
20293
  let cacheStored = false;
@@ -19104,10 +20349,7 @@ async function resolveSharedSsg(input) {
19104
20349
  async function prerenderRuntimeSSG(route, params, root, origin, buildId, searchRoutes) {
19105
20350
  const pageCache = getPageCacheAdapter();
19106
20351
  if (pageCache === undefined) {
19107
- return {
19108
- cacheStored: true,
19109
- entry: await prerenderSSG(route, params, root, origin, undefined, searchRoutes)
19110
- };
20352
+ return prerenderLocalSSG(route, params, root, origin, undefined, searchRoutes);
19111
20353
  }
19112
20354
  const resolvedPath = resolvePath(route.pattern, params);
19113
20355
  const identity = {
@@ -19116,10 +20358,12 @@ async function prerenderRuntimeSSG(route, params, root, origin, buildId, searchR
19116
20358
  mode: "ssg",
19117
20359
  path: resolvedPath,
19118
20360
  scope: currentInstance().prefix,
19119
- tags: route.tags ?? []
20361
+ tags: [
20362
+ ...new Set([...route.tags ?? [], ...getAutoInvalidateRegistry().tagsForPath(resolvedPath)])
20363
+ ]
19120
20364
  };
19121
20365
  const renderFresh = () => prerenderRoute(route, params, root, origin, "ssg", undefined, searchRoutes);
19122
- return resolveSharedSsg({ identity, pageCache, renderFresh });
20366
+ return await resolveSharedSsg({ identity, pageCache, renderFresh });
19123
20367
  }
19124
20368
  function logSsgError(furin, error) {
19125
20369
  const logger = createLogger({});
@@ -19488,7 +20732,8 @@ function computeRouteDependencies(pagePath, rootPath) {
19488
20732
  }
19489
20733
  }
19490
20734
  }
19491
- return deps;
20735
+ const graph = devGraph(undefined);
20736
+ return [...new Set(deps.flatMap((path) => graph.sourceDependencies(path)))].filter(existsSync3);
19492
20737
  }
19493
20738
 
19494
20739
  // src/furin.ts
@@ -19745,9 +20990,11 @@ async function renderISRCacheMiss(input) {
19745
20990
  route: input.route.pattern
19746
20991
  }
19747
20992
  });
19748
- const cacheStored = await storeRenderedISR(input, html, generatedAt);
20993
+ const discoveredTags = queryTagsFromData(syncData);
20994
+ const identityTags = new Set(input.pageCacheIdentity.tags);
20995
+ const cacheStored = input.pageCache !== undefined && discoveredTags.some((tag) => !identityTags.has(tag)) ? false : await storeRenderedISR(input, html, generatedAt);
19749
20996
  if (cacheStored && input.pageCache === undefined) {
19750
- autoInvalidateRegistry.registerLoaderTags(input.cacheKey, input.route.tags, "render:isr-html");
20997
+ autoInvalidateRegistry.registerLoaderTags(input.cacheKey, [...input.route.tags ?? [], ...discoveredTags], "render:isr-html");
19751
20998
  }
19752
20999
  for (const [key, value] of Object.entries(headers)) {
19753
21000
  input.ctx.set.headers[key] = value;
@@ -19776,7 +21023,9 @@ async function handleISR(route, ctx, root, buildId, searchRoutes) {
19776
21023
  mode: "isr",
19777
21024
  path: resolvedPath,
19778
21025
  scope: currentInstance().prefix,
19779
- tags: route.tags ?? []
21026
+ tags: [
21027
+ ...new Set([...route.tags ?? [], ...getAutoInvalidateRegistry().tagsForPath(cacheKey)])
21028
+ ]
19780
21029
  };
19781
21030
  const lookup = await lookupISRCache(pageCache, pageCacheIdentity, cacheKey, externalPrerender, revalidate);
19782
21031
  const { cached, sharedAvailable: initialSharedAvailable } = lookup;
@@ -19880,33 +21129,11 @@ function logRevalidationSkipped(route, reason, status) {
19880
21129
  logger.emit();
19881
21130
  }
19882
21131
  async function handleBackgroundRevalidationError(input, error) {
19883
- const logger = createLogger({});
19884
21132
  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();
21133
+ await invalidateBackgroundNotFound(input);
19908
21134
  return;
19909
21135
  }
21136
+ const logger = createLogger({});
19910
21137
  logger.set({
19911
21138
  furin: {
19912
21139
  cache: "revalidation_failed",
@@ -19917,6 +21144,35 @@ async function handleBackgroundRevalidationError(input, error) {
19917
21144
  logger.error(error instanceof Error ? error : new Error(String(error)));
19918
21145
  logger.emit();
19919
21146
  }
21147
+ async function invalidateBackgroundNotFound(input) {
21148
+ if (input.sharedCache === undefined && !input.cacheGeneration?.valid) {
21149
+ return;
21150
+ }
21151
+ const logger = createLogger({});
21152
+ if (input.sharedCache === undefined) {
21153
+ deleteISRCache(input.cacheKey);
21154
+ } else {
21155
+ try {
21156
+ await input.sharedCache.adapter.invalidate({
21157
+ kind: "path",
21158
+ path: input.sharedCache.identity.path,
21159
+ scope: input.sharedCache.identity.scope,
21160
+ type: "page"
21161
+ });
21162
+ } catch {
21163
+ logger.warn("ISR shared page cache invalidation failed after not-found revalidation");
21164
+ }
21165
+ }
21166
+ logger.set({
21167
+ furin: {
21168
+ cache: "revalidation_invalidated",
21169
+ reason: "not_found",
21170
+ render: "isr",
21171
+ route: input.route.pattern
21172
+ }
21173
+ });
21174
+ logger.emit();
21175
+ }
19920
21176
  async function releaseBackgroundRevalidation(input, lease) {
19921
21177
  if (input.sharedCache !== undefined && lease !== null) {
19922
21178
  try {
@@ -19946,18 +21202,30 @@ async function performBackgroundRevalidation(input) {
19946
21202
  if (result instanceof Response) {
19947
21203
  return;
19948
21204
  }
21205
+ if (result.status === 404) {
21206
+ await invalidateBackgroundNotFound(input);
21207
+ return;
21208
+ }
19949
21209
  if (result.status !== 200) {
19950
21210
  logRevalidationSkipped(input.route, "non_200_render", result.status);
19951
21211
  return;
19952
21212
  }
19953
21213
  if (input.sharedCache !== undefined && lease !== null) {
21214
+ const { identity } = input.sharedCache;
21215
+ const identityTags = new Set(identity.tags);
21216
+ if ((result.queryTags ?? []).some((tag) => !identityTags.has(tag))) {
21217
+ return;
21218
+ }
19954
21219
  await input.sharedCache.adapter.commit({
19955
21220
  entry: { cachedAt: Date.now(), payload: result.html, revalidate: input.revalidate },
19956
21221
  identity: input.sharedCache.identity,
19957
21222
  lease
19958
21223
  });
19959
21224
  } else if (input.cacheGeneration !== undefined) {
19960
- setISRCacheIfGenerationUnchanged(input.cacheKey, { generatedAt: Date.now(), html: result.html, revalidate: input.revalidate }, input.cacheGeneration);
21225
+ const stored = setISRCacheIfGenerationUnchanged(input.cacheKey, { generatedAt: Date.now(), html: result.html, revalidate: input.revalidate }, input.cacheGeneration);
21226
+ if (stored) {
21227
+ autoInvalidateRegistry.registerLoaderTags(input.cacheKey, [...input.route.tags ?? [], ...result.queryTags ?? []], "render:isr-html");
21228
+ }
19961
21229
  }
19962
21230
  } catch (error) {
19963
21231
  await handleBackgroundRevalidationError(input, error);
@@ -20000,14 +21268,10 @@ async function runDataEndpointLoaders(route, ctx, root, searchRoutes) {
20000
21268
  }
20001
21269
  async function serializeLoaderDataResponse(result, route, requestUrl, routeContext) {
20002
21270
  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
- });
21271
+ const { prefix } = currentInstance();
21272
+ const pageUrl = new URL(requestUrl);
21273
+ pageUrl.pathname = physicalPath(prefix, pageUrl.pathname);
21274
+ return serializeNavigationRedirect(result.response, pageUrl, prefix);
20011
21275
  }
20012
21276
  if (result.type === "not-found") {
20013
21277
  const serialized = await toCrossJSONAsync({
@@ -20052,11 +21316,19 @@ async function serializeGuardRedirect(response, request) {
20052
21316
  const rawPath = requestUrl.searchParams.get("path");
20053
21317
  const logicalPath = rawPath ? parseDataEndpointPath(rawPath) : undefined;
20054
21318
  const pageUrl = logicalPath ? new URL(prefix + logicalPath.pathname + logicalPath.url.search, requestUrl) : requestUrl;
21319
+ return await serializeNavigationRedirect(response, pageUrl, prefix);
21320
+ }
21321
+ async function serializeNavigationRedirect(response, pageUrl, prefix) {
21322
+ const location = response.headers.get("location");
21323
+ if (!location) {
21324
+ return response;
21325
+ }
20055
21326
  const target = new URL(location, pageUrl);
20056
21327
  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;
21328
+ const href = target.origin === pageUrl.origin && withinMount ? (target.pathname.slice(prefix.length) || "/") + target.search + target.hash : target.href;
20058
21329
  const serialized = await toCrossJSONAsync({ __furinRedirect: href });
20059
21330
  const headers = new Headers(response.headers);
21331
+ headers.delete("content-length");
20060
21332
  headers.delete("location");
20061
21333
  headers.set("content-type", "application/x-ndjson");
20062
21334
  headers.set("cache-control", "private, no-store");
@@ -20120,14 +21392,15 @@ async function handleSSGRequest(route, ctx, root, buildId, searchRoutes) {
20120
21392
  if (entry instanceof Response) {
20121
21393
  return entry;
20122
21394
  }
21395
+ ctx.set.status = entry.status;
20123
21396
  const resolvedPath = resolvePath(route.pattern, params);
20124
21397
  const etag = buildId ? `"${buildId}:${entry.cachedAt}"` : null;
20125
- if (etag && ctx.request.headers.get("if-none-match") === etag) {
21398
+ if (entry.status === 200 && etag && ctx.request.headers.get("if-none-match") === etag) {
20126
21399
  ctx.set.status = 304;
20127
21400
  return;
20128
21401
  }
20129
21402
  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";
21403
+ ctx.set.headers["cache-control"] = cacheStored && entry.status === 200 ? "public, max-age=0, must-revalidate, s-maxage=31536000" : "no-store";
20131
21404
  if (etag) {
20132
21405
  ctx.set.headers.etag = etag;
20133
21406
  }
@@ -20181,6 +21454,87 @@ function withResolvedHead(route, syncData) {
20181
21454
  init_schema_merge();
20182
21455
  init_schemas();
20183
21456
  init_config();
21457
+
21458
+ // src/server/sync/validation.ts
21459
+ import { createContext as createContext7 } from "elysia/context";
21460
+
21461
+ // src/server/sync/mutation-handler.ts
21462
+ import { createContext as createContext6 } from "elysia/context";
21463
+ var mutationBeginnings = new WeakMap;
21464
+ var installedApplications = new WeakSet;
21465
+ var installedContexts = new WeakSet;
21466
+ function prepareMutationHandler(context, begin) {
21467
+ if (!installedContexts.has(context.constructor)) {
21468
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation routes.");
21469
+ }
21470
+ mutationBeginnings.set(context.request, begin);
21471
+ }
21472
+ function installMutationHandlers(app) {
21473
+ if (installedApplications.has(app)) {
21474
+ return;
21475
+ }
21476
+ installedApplications.add(app);
21477
+ app.decorate("_furinMutationHandlers", true);
21478
+ app.wrap((fetch2) => {
21479
+ installedContexts.add(createContext6(app));
21480
+ return fetch2;
21481
+ });
21482
+ const compileHandler = app.handler.bind(app);
21483
+ app.handler = (index, immediate, route, aliases, table) => {
21484
+ const nativeRoute = route ?? (table ? [
21485
+ table.method[index],
21486
+ table.path[index],
21487
+ table.handler[index],
21488
+ table.owner[index],
21489
+ table.localHook[index],
21490
+ table.appHook[index],
21491
+ table.inheritedChain[index],
21492
+ table.macroScope?.get(index)
21493
+ ] : app["~routes"][index]);
21494
+ if (!nativeRoute || ["GET", "HEAD", "OPTIONS", "WS"].includes(nativeRoute[0])) {
21495
+ return compileHandler(index, immediate, route, aliases, table);
21496
+ }
21497
+ const [method, path, handle, owner, hooks, chain, inherited, macroScope] = nativeRoute;
21498
+ const wrapped = async (context) => {
21499
+ const begin = mutationBeginnings.get(context.request);
21500
+ mutationBeginnings.delete(context.request);
21501
+ const response = await begin?.();
21502
+ if (response !== undefined) {
21503
+ return response;
21504
+ }
21505
+ return typeof handle === "function" ? handle(context) : handle;
21506
+ };
21507
+ return compileHandler(index, immediate, [method, path, wrapped, owner, hooks, chain, inherited, macroScope], aliases, table);
21508
+ };
21509
+ }
21510
+
21511
+ // src/server/sync/validation.ts
21512
+ var applications = new WeakMap;
21513
+ var boundApplications = new WeakSet;
21514
+ function bindSyncValidation(app) {
21515
+ installMutationHandlers(app);
21516
+ if (boundApplications.has(app)) {
21517
+ return;
21518
+ }
21519
+ boundApplications.add(app);
21520
+ app.decorate("_furinSyncValidation", true);
21521
+ app.wrap((fetch2) => {
21522
+ applications.set(createContext7(app), app);
21523
+ return fetch2;
21524
+ });
21525
+ app.setup((root) => {
21526
+ applications.set(createContext7(root), root);
21527
+ });
21528
+ }
21529
+ function syncValidationApp(context) {
21530
+ const app = applications.get(context.constructor);
21531
+ if (!app) {
21532
+ throw new Error("[furin] Install furinSync on the final Elysia application, or mount furin({ sync }), before using mutation().");
21533
+ }
21534
+ return app;
21535
+ }
21536
+
21537
+ // src/furin.ts
20184
21538
  init_define_route();
20185
21539
 
20186
21540
  // src/isomorphic.ts
@@ -20298,6 +21652,7 @@ async function invalidateTagsForInstance(instance, tagList) {
20298
21652
  let deleted = false;
20299
21653
  const purgedPaths = new Set;
20300
21654
  const logicalPurgedPaths = new Set;
21655
+ const sharedInvalidations = [];
20301
21656
  const pageCache = getPageCacheAdapter(instance);
20302
21657
  const sharedResult = pageCache === undefined ? undefined : await pageCache.invalidate({
20303
21658
  kind: "tags",
@@ -20311,9 +21666,19 @@ async function invalidateTagsForInstance(instance, tagList) {
20311
21666
  ...getAutoInvalidateRegistry(instance).pathsForTags(tagList),
20312
21667
  ...sharedResult?.paths ?? []
20313
21668
  ]);
21669
+ const tags = new Set(tagList);
20314
21670
  for (const path of taggedPaths) {
20315
21671
  const logicalPath = pathWithoutSearch(path);
21672
+ const registered = getAutoInvalidateRegistry(instance).tagsForPath(path).some((tag) => tags.has(tag));
20316
21673
  const result = revalidatePathForInstance(instance, logicalPath, "page", false);
21674
+ if (pageCache !== undefined && registered) {
21675
+ sharedInvalidations.push(pageCache.invalidate({
21676
+ kind: "path",
21677
+ scope: instance.prefix,
21678
+ path: logicalPath,
21679
+ type: "page"
21680
+ }));
21681
+ }
20317
21682
  deleted = result.deleted || deleted;
20318
21683
  purgedPaths.add(physicalPath(instance.prefix, logicalPath));
20319
21684
  logicalPurgedPaths.add(logicalPath);
@@ -20322,6 +21687,8 @@ async function invalidateTagsForInstance(instance, tagList) {
20322
21687
  logicalPurgedPaths.add(purged);
20323
21688
  }
20324
21689
  }
21690
+ const pathResults = await Promise.all(sharedInvalidations);
21691
+ deleted = pathResults.some((result) => result.invalidated) || deleted;
20325
21692
  if (IS_DEV) {
20326
21693
  withInstance(instance, () => {
20327
21694
  const request = currentInstrumentationRequest();
@@ -20385,41 +21752,41 @@ function furinInvalidate() {
20385
21752
  });
20386
21753
  }
20387
21754
  // src/server/sync/plugin.ts
20388
- import { Elysia as Elysia11 } from "elysia";
21755
+ import { Elysia as Elysia11, ElysiaStatus as ElysiaStatus3 } from "elysia";
20389
21756
  init_context_logger();
20390
21757
 
20391
- // src/server/sync/fingerprint.ts
20392
- function compareCodePoints(left, right) {
20393
- if (left === right) {
20394
- return 0;
21758
+ // src/server/sync/atomic.ts
21759
+ import { ElysiaStatus as ElysiaStatus2, StatusMap as StatusMap2, Validator as Validator2 } from "elysia";
21760
+ init_context_logger();
21761
+
21762
+ // src/server/sync/queries.ts
21763
+ function resolveSyncInvalidations(input, context, value) {
21764
+ if (input === undefined) {
21765
+ return;
20395
21766
  }
20396
- return left < right ? -1 : 1;
21767
+ const selected = typeof input === "function" ? input(Object.assign(Object.create(Object.getPrototypeOf(context)), context, {
21768
+ responseValue: value
21769
+ })) : input;
21770
+ const rules = Array.isArray(selected) ? selected : [selected];
21771
+ return rules.map((rule) => ("id" in rule) ? { tags: [queryTag(rule)] } : rule);
20397
21772
  }
20398
- function canonicalize(value) {
20399
- if (Array.isArray(value)) {
20400
- return value.map(canonicalize);
21773
+ function appendQueryInvalidations(input, context) {
21774
+ if (input === undefined) {
21775
+ return;
21776
+ }
21777
+ const queries = [];
21778
+ for (const rule of Array.isArray(input) ? input : [input]) {
21779
+ for (const tag of rule.tags ?? []) {
21780
+ const identity = queryFromTag(tag);
21781
+ if (identity) {
21782
+ queries.push(identity);
21783
+ }
21784
+ }
20401
21785
  }
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)]));
21786
+ if (queries.length > 0) {
21787
+ context.set.headers["x-furin-queries"] = serializeQueryHeader(queries);
21788
+ context.set.headers["x-furin-sync"] = "1";
20404
21789
  }
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
21790
  }
20424
21791
 
20425
21792
  // src/server/sync/response.ts
@@ -20560,6 +21927,15 @@ async function storeResponse(responseValue, set) {
20560
21927
  const headers = new Headers([...clone.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase())));
20561
21928
  return storedResponseResult(headers, body, clone.status);
20562
21929
  }
21930
+ return storeResponseSync(responseValue, set);
21931
+ }
21932
+ function storeResponseSync(responseValue, set) {
21933
+ if (responseValue instanceof Response) {
21934
+ if (responseValue.body !== null) {
21935
+ return unreplayable();
21936
+ }
21937
+ return storedResponseResult(new Headers([...responseValue.headers.entries()].filter(([name]) => !NON_REPLAYABLE_HEADERS.has(name.toLowerCase()))), new Uint8Array, responseValue.status);
21938
+ }
20563
21939
  const headers = responseHeaders(set.headers);
20564
21940
  const statusResponse = unwrapStatusResponse(responseValue);
20565
21941
  const value = statusResponse?.value ?? responseValue;
@@ -20590,34 +21966,166 @@ function replayResponse(stored) {
20590
21966
  });
20591
21967
  }
20592
21968
 
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;
21969
+ // src/server/sync/atomic.ts
21970
+ var TRAILING_SLASH_PATTERN = /\/$/;
21971
+
21972
+ class RejectedMutation {
21973
+ value;
21974
+ constructor(value) {
21975
+ this.value = value;
21976
+ }
20599
21977
  }
20600
- function invalidationInputFromSync(input) {
20601
- if (input && typeof input === "object" && "invalidate" in input) {
20602
- return input.invalidate;
21978
+ function responseStatus(context, value) {
21979
+ if (value instanceof Response && value.status !== 200) {
21980
+ return value.status;
20603
21981
  }
20604
- return input;
21982
+ if (value instanceof ElysiaStatus2) {
21983
+ return value.status;
21984
+ }
21985
+ if (typeof context.set.status === "string") {
21986
+ return StatusMap2[context.set.status];
21987
+ }
21988
+ return context.set.status ?? 200;
20605
21989
  }
20606
- function isMutationMethod(method) {
20607
- return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
21990
+ function withStatus(original, value) {
21991
+ return original instanceof ElysiaStatus2 ? new ElysiaStatus2(original.status, value, original.headers) : value;
20608
21992
  }
20609
- function getIdempotencyKey(ctx) {
20610
- const fromCtxHeaders = ctx.headers["idempotency-key"];
20611
- if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
20612
- return fromCtxHeaders;
21993
+ function validateResult(execution, value) {
21994
+ if (value instanceof Error) {
21995
+ throw value;
20613
21996
  }
20614
- const fromRequest = ctx.request.headers.get("Idempotency-Key");
20615
- return fromRequest || undefined;
21997
+ if (value instanceof Response) {
21998
+ return value;
21999
+ }
22000
+ const { app, context, adapter } = execution;
22001
+ const registeredPath = context.route ?? context.path;
22002
+ const strictPath = app["~config"]?.strictPath === true;
22003
+ const [match] = app.routes.toReversed().filter((entry) => entry.method === context.request.method || entry.method === "*").map((candidate) => {
22004
+ const paths = [candidate.path, encodeURI(candidate.path)];
22005
+ const exact = paths.includes(registeredPath);
22006
+ const loose = !strictPath && paths.some((path) => path.replace(TRAILING_SLASH_PATTERN, "") === registeredPath.replace(TRAILING_SLASH_PATTERN, ""));
22007
+ return { route: candidate, priority: exact ? 2 : Number(loose) };
22008
+ }).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);
22009
+ if (!match) {
22010
+ throw new Error("[furin] Could not resolve the effective mutation route for response validation.");
22011
+ }
22012
+ const { route } = match;
22013
+ const validators = Validator2.response(route?.hooks.response, {
22014
+ models: app["~ext"]?.models,
22015
+ normalize: app["~config"]?.normalize,
22016
+ sanitize: app["~config"]?.sanitize,
22017
+ schemas: route?.hooks.schemas?.flatMap((schema) => schema.response ? [schema.response] : [])
22018
+ });
22019
+ const validator = validators?.[responseStatus(context, value)];
22020
+ if (!validator) {
22021
+ return value;
22022
+ }
22023
+ const body = value instanceof ElysiaStatus2 ? value.response : value;
22024
+ const encoder = validator;
22025
+ const encoded = validator.mayReturnPromise ? validator.From?.(body, "response", adapter.transactionMode !== "sync") : encoder.EncodeFrom?.(body, "response");
22026
+ if (!(encoded instanceof Promise)) {
22027
+ return withStatus(value, encoded);
22028
+ }
22029
+ if (adapter.transactionMode === "sync") {
22030
+ throw new Error("[furin] Bun SQLite mutations require synchronous response validation.");
22031
+ }
22032
+ return encoded.then((result) => withStatus(value, result));
22033
+ }
22034
+ function prepare(execution, value, original) {
22035
+ const { context } = execution;
22036
+ const status = responseStatus(context, value);
22037
+ if (status < 200 || status >= 400) {
22038
+ throw new RejectedMutation(original);
22039
+ }
22040
+ const invalidate = resolveSyncInvalidations(execution.invalidate, context, original);
22041
+ execution.resolvedInvalidate = invalidate;
22042
+ appendQueryInvalidations(invalidate, context);
22043
+ const invalidations = [
22044
+ ...normalizedInvalidations(invalidate),
22045
+ ...pendingPathInvalidations(peekPendingInvalidations())
22046
+ ];
22047
+ if (invalidations.length > 0) {
22048
+ context.set.headers["x-furin-sync"] = "1";
22049
+ }
22050
+ const paths = invalidations.filter((entry) => entry.kind === "path").map((entry) => entry.type === "layout" ? `${entry.path}:layout` : entry.path);
22051
+ if (paths.length > 0) {
22052
+ context.set.headers["x-furin-revalidate"] = paths.join(",");
22053
+ }
22054
+ const finish = (stored) => {
22055
+ if (stored.kind === "unreplayable") {
22056
+ throw new Error("[furin] Atomic mutation responses must be bounded JSON, text or bodyless responses.");
22057
+ }
22058
+ let { headers } = context.set;
22059
+ if (value instanceof ElysiaStatus2) {
22060
+ headers = { ...headers, ...value.headers };
22061
+ } else if (value instanceof Response) {
22062
+ headers = { ...headers, ...Object.fromEntries(value.headers) };
22063
+ }
22064
+ return {
22065
+ invalidations,
22066
+ response: mergeStoredResponseHeaders({ ...stored.response, status }, headers),
22067
+ value: original
22068
+ };
22069
+ };
22070
+ return execution.adapter.transactionMode === "sync" ? finish(storeResponseSync(value, context.set)) : storeResponse(value, context.set).then(finish);
20616
22071
  }
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/");
22072
+ function assertSynchronous(mode, value) {
22073
+ if (mode === "sync" && (value instanceof Promise || Object.prototype.toString.call(value) === "[object AsyncFunction]")) {
22074
+ throw new Error("[furin] Bun SQLite mutation callbacks must be synchronous.");
22075
+ }
22076
+ }
22077
+ function invoke(execution, callback, tx) {
22078
+ assertSynchronous(execution.adapter.transactionMode, callback);
22079
+ const value = callback(tx);
22080
+ assertSynchronous(execution.adapter.transactionMode, value);
22081
+ if (value instanceof Promise) {
22082
+ return value.then(async (original) => prepare(execution, await validateResult(execution, original), original));
22083
+ }
22084
+ const encoded = validateResult(execution, value);
22085
+ return encoded instanceof Promise ? encoded.then((result) => prepare(execution, result, value)) : prepare(execution, encoded, value);
22086
+ }
22087
+ async function afterCommit(execution, result) {
22088
+ execution.onCommit(result);
22089
+ if (execution.resolvedInvalidate) {
22090
+ await runInvalidationRules(execution.resolvedInvalidate).catch(() => getLogger().warn("Sync cache invalidation failed after mutation; preserving the idempotent result"));
22091
+ appendPendingInvalidationHeader(execution.context.set);
22092
+ }
22093
+ const { notifier } = execution.runtime;
22094
+ if (result.cursor !== undefined) {
22095
+ notifier.publish(result.cursor).catch(() => {
22096
+ return;
22097
+ });
22098
+ }
22099
+ }
22100
+ async function executeAtomicMutation(execution, callback) {
22101
+ const { context } = execution;
22102
+ const previousSyncHeader = context.set.headers["x-furin-sync"];
22103
+ const previousPathHeader = context.set.headers["x-furin-revalidate"];
22104
+ const previousQueryHeader = context.set.headers["x-furin-queries"];
22105
+ let committed = false;
22106
+ try {
22107
+ const result = await execution.adapter.executeMutation(execution.lease, (tx) => invoke(execution, callback, tx));
22108
+ committed = true;
22109
+ await afterCommit(execution, result);
22110
+ return result.value;
22111
+ } catch (error) {
22112
+ if (!committed) {
22113
+ restoreHeader(context, "x-furin-sync", previousSyncHeader);
22114
+ restoreHeader(context, "x-furin-revalidate", previousPathHeader);
22115
+ restoreHeader(context, "x-furin-queries", previousQueryHeader);
22116
+ }
22117
+ if (error instanceof RejectedMutation) {
22118
+ return error.value;
22119
+ }
22120
+ throw error;
22121
+ }
22122
+ }
22123
+ function restoreHeader(context, key, value) {
22124
+ if (value === undefined) {
22125
+ delete context.set.headers[key];
22126
+ } else {
22127
+ context.set.headers[key] = value;
22128
+ }
20621
22129
  }
20622
22130
  function conflictResponse(reason) {
20623
22131
  const inProgress = reason === "in-progress";
@@ -20629,12 +22137,6 @@ function conflictResponse(reason) {
20629
22137
  status: 409
20630
22138
  });
20631
22139
  }
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
22140
  function normalizedInvalidations(input) {
20639
22141
  if (!input) {
20640
22142
  return [];
@@ -20654,8 +22156,122 @@ function normalizedInvalidations(input) {
20654
22156
  function pendingPathInvalidations(entries) {
20655
22157
  return entries.map((entry) => entry.endsWith(":layout") ? { kind: "path", path: entry.slice(0, -":layout".length), type: "layout" } : { kind: "path", path: entry, type: "page" });
20656
22158
  }
20657
- function furinSync(options) {
22159
+
22160
+ // src/server/sync/execution-error.ts
22161
+ class MutationLeaseLost extends Error {
22162
+ }
22163
+
22164
+ // src/server/sync/fingerprint.ts
22165
+ function compareCodePoints(left, right) {
22166
+ if (left === right) {
22167
+ return 0;
22168
+ }
22169
+ return left < right ? -1 : 1;
22170
+ }
22171
+ function canonicalize(value) {
22172
+ if (Array.isArray(value)) {
22173
+ return value.map(canonicalize);
22174
+ }
22175
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
22176
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => compareCodePoints(left, right)).map(([key, entry]) => [key, canonicalize(entry)]));
22177
+ }
22178
+ return value;
22179
+ }
22180
+ function sha256Hex(source) {
22181
+ const hasher = new Bun.CryptoHasher("sha256");
22182
+ hasher.update(source);
22183
+ return hasher.digest("hex");
22184
+ }
22185
+ function createMutationFingerprint(input) {
22186
+ const url = new URL(input.request.url);
22187
+ url.searchParams.sort();
22188
+ const query = [...url.searchParams.entries()];
22189
+ const source = JSON.stringify({
22190
+ body: canonicalize(input.body) ?? null,
22191
+ contentType: input.request.headers.get("content-type") ?? "",
22192
+ method: input.request.method,
22193
+ pathname: url.pathname,
22194
+ query
22195
+ });
22196
+ return sha256Hex(source);
22197
+ }
22198
+
22199
+ // src/server/sync/plugin.ts
22200
+ init_runtime();
22201
+ var routeMetadata = new WeakMap;
22202
+ var activeMutations = new WeakMap;
22203
+ var atomicCalls = new WeakSet;
22204
+ var atomicResponses = new WeakMap;
22205
+ function hideTransportResponse(hook) {
22206
+ return hook;
22207
+ }
22208
+ function invalidationInputFromSync(input) {
22209
+ if (input && typeof input === "object" && "invalidate" in input) {
22210
+ return input.invalidate;
22211
+ }
22212
+ if ("id" in input) {
22213
+ return;
22214
+ }
22215
+ return input;
22216
+ }
22217
+ function isMutationMethod(method) {
22218
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
22219
+ }
22220
+ function getIdempotencyKey(ctx) {
22221
+ const fromCtxHeaders = ctx.headers["idempotency-key"];
22222
+ if (typeof fromCtxHeaders === "string" && fromCtxHeaders.length > 0) {
22223
+ return fromCtxHeaders;
22224
+ }
22225
+ const fromRequest = ctx.request.headers.get("Idempotency-Key");
22226
+ return fromRequest || undefined;
22227
+ }
22228
+ function supportsReplayBody(request) {
22229
+ const contentType = request.headers.get("content-type")?.toLowerCase();
22230
+ const mediaType = contentType?.split(";", 1)[0]?.trim();
22231
+ return contentType === undefined || mediaType === "application/json" || mediaType?.startsWith("application/") === true && mediaType.endsWith("+json") || contentType.startsWith("application/x-www-form-urlencoded") || contentType.startsWith("text/");
22232
+ }
22233
+ function leaseLostResponse() {
22234
+ return Response.json({
22235
+ code: "FURIN_SYNC_LEASE_LOST",
22236
+ message: "The mutation lease was lost before its response could be committed."
22237
+ }, { status: 503 });
22238
+ }
22239
+ function createSyncPlugin(options) {
20658
22240
  const runtime = resolveSyncRuntime(options);
22241
+ const transactional = "executeMutation" in options.adapter ? options.adapter : undefined;
22242
+ function mutationFor(ctx) {
22243
+ const mutation = async (callback) => {
22244
+ const active = activeMutations.get(ctx.request);
22245
+ if (!(transactional && active)) {
22246
+ throw new Error("[furin] mutation() requires a transactional sync adapter and an enabled mutation route.");
22247
+ }
22248
+ if (atomicCalls.has(ctx.request)) {
22249
+ throw new Error("[furin] Call mutation() once and return its result from the handler.");
22250
+ }
22251
+ atomicCalls.add(ctx.request);
22252
+ try {
22253
+ return await executeAtomicMutation({
22254
+ adapter: transactional,
22255
+ app: syncValidationApp(ctx),
22256
+ context: ctx,
22257
+ lease: active.lease,
22258
+ invalidate: routeMetadata.get(ctx.request)?.invalidate,
22259
+ runtime,
22260
+ onCommit: (result) => atomicResponses.set(ctx.request, result)
22261
+ }, callback);
22262
+ } finally {
22263
+ if (atomicResponses.has(ctx.request)) {
22264
+ releaseMutation(ctx.request);
22265
+ } else {
22266
+ await abortMutation(ctx.request).catch(() => {
22267
+ return;
22268
+ });
22269
+ }
22270
+ atomicCalls.delete(ctx.request);
22271
+ }
22272
+ };
22273
+ return mutation;
22274
+ }
20659
22275
  async function beginMutation(ctx) {
20660
22276
  if (!isMutationMethod(ctx.request.method) || routeMetadata.get(ctx.request)?.disabled) {
20661
22277
  return;
@@ -20703,21 +22319,25 @@ function furinSync(options) {
20703
22319
  activeMutations.set(ctx.request, active);
20704
22320
  scheduleRenewal();
20705
22321
  }
20706
- async function abortMutation(request) {
22322
+ function releaseMutation(request) {
20707
22323
  const active = activeMutations.get(request);
20708
- if (!active) {
20709
- return;
20710
- }
20711
22324
  activeMutations.delete(request);
20712
- if (active.renewal) {
22325
+ if (active?.renewal) {
20713
22326
  clearTimeout(active.renewal);
20714
22327
  }
20715
- await runtime.adapter.abortMutation(active.lease);
22328
+ return active;
22329
+ }
22330
+ async function abortMutation(request) {
22331
+ const active = releaseMutation(request);
22332
+ if (active) {
22333
+ await runtime.adapter.abortMutation(active.lease);
22334
+ }
20716
22335
  }
20717
22336
  async function persistMutation(ctx, active) {
20718
22337
  const result = await storeResponse(ctx.responseValue, ctx.set);
20719
22338
  const manualPending = peekPendingInvalidations();
20720
- const invalidate = routeMetadata.get(ctx.request)?.invalidate;
22339
+ const invalidate = resolveSyncInvalidations(routeMetadata.get(ctx.request)?.invalidate, ctx, ctx.responseValue);
22340
+ appendQueryInvalidations(invalidate, ctx);
20721
22341
  const logger = getLogger();
20722
22342
  if (invalidate) {
20723
22343
  try {
@@ -20747,7 +22367,7 @@ function furinSync(options) {
20747
22367
  if (completion.kind === "lost") {
20748
22368
  return leaseLostResponse();
20749
22369
  }
20750
- const notificationAlreadyPublished = runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
22370
+ const notificationAlreadyPublished = runtime.adapter.publishesNotifications !== false && runtime.adapter.notificationChannel !== undefined && runtime.adapter.notificationChannel === runtime.notifier.notificationChannel;
20751
22371
  if (completion.cursor !== undefined && !notificationAlreadyPublished) {
20752
22372
  runtime.notifier.publish(completion.cursor).catch(() => {
20753
22373
  return;
@@ -20758,6 +22378,19 @@ function furinSync(options) {
20758
22378
  }
20759
22379
  }
20760
22380
  async function finishMutation(ctx) {
22381
+ const atomic = atomicResponses.get(ctx.request);
22382
+ atomicResponses.delete(ctx.request);
22383
+ atomicCalls.delete(ctx.request);
22384
+ if (atomic && ctx.responseValue === atomic.value) {
22385
+ if (atomic.value instanceof Response) {
22386
+ return atomic.value;
22387
+ }
22388
+ if (atomic.value instanceof ElysiaStatus3) {
22389
+ ctx.set.status = atomic.value.status;
22390
+ Object.assign(ctx.set.headers, atomic.value.headers);
22391
+ }
22392
+ return replayResponse(atomic.response);
22393
+ }
20761
22394
  const active = activeMutations.get(ctx.request);
20762
22395
  if (!active) {
20763
22396
  return;
@@ -20780,21 +22413,121 @@ function furinSync(options) {
20780
22413
  }
20781
22414
  }
20782
22415
  }
20783
- const beginMutationHook = hideTransportResponse(beginMutation);
20784
22416
  const finishMutationHook = hideTransportResponse(finishMutation);
20785
- return new Elysia11({ name: "furin-sync" }).beforeHandle("global", beginMutationHook).afterHandle("global", finishMutationHook).error("global", ({ request }) => abortMutation(request)).macro({
22417
+ const plugin = new Elysia11({ name: "furin-sync" }).derive("global", (ctx) => ({ mutation: mutationFor(ctx) })).beforeHandle("global", (context) => {
22418
+ if (isMutationMethod(context.request.method) && !routeMetadata.get(context.request)?.disabled) {
22419
+ prepareMutationHandler(context, () => beginMutation(context));
22420
+ }
22421
+ }).afterHandle("global", finishMutationHook).afterHandle("global", async (ctx) => {
22422
+ const read = routeMetadata.get(ctx.request)?.read;
22423
+ if (ctx.request.method !== "GET" || !read || !isSuccessfulMutationResponse({
22424
+ set: ctx.set,
22425
+ responseValue: ctx.responseValue instanceof Response || ctx.responseValue instanceof ElysiaStatus3 ? ctx.responseValue : undefined
22426
+ })) {
22427
+ return;
22428
+ }
22429
+ const principal = await options.principal(ctx);
22430
+ if (principal.length === 0) {
22431
+ throw new Error("[furin] Sync principal must not be empty.");
22432
+ }
22433
+ const identity = {
22434
+ id: read.id,
22435
+ scope: typeof read.scope === "function" ? read.scope(ctx) : read.scope ?? {},
22436
+ session: new Bun.CryptoHasher("sha256").update(principal).digest("hex")
22437
+ };
22438
+ queryTag(identity);
22439
+ ctx.set.headers["x-furin-query"] = serializeQueryHeader(identity);
22440
+ }).error("global", MutationLeaseLost, hideTransportResponse(() => Promise.resolve(leaseLostResponse()))).error("global", hideTransportResponse(async ({ request }) => {
22441
+ atomicResponses.delete(request);
22442
+ atomicCalls.delete(request);
22443
+ await abortMutation(request);
22444
+ })).macro({
20786
22445
  sync(input) {
20787
22446
  return {
20788
22447
  transform({ request }) {
20789
- routeMetadata.set(request, input === false ? { disabled: true } : { disabled: false, invalidate: invalidationInputFromSync(input) });
22448
+ routeMetadata.set(request, input === false ? { disabled: true } : {
22449
+ disabled: false,
22450
+ invalidate: invalidationInputFromSync(input),
22451
+ read: "id" in input ? input : undefined
22452
+ });
20790
22453
  }
20791
22454
  };
20792
22455
  }
20793
22456
  });
22457
+ return plugin;
22458
+ }
22459
+ function furinSync(options) {
22460
+ return (app) => {
22461
+ installMutationHandlers(app);
22462
+ if ("executeMutation" in options.adapter) {
22463
+ bindSyncValidation(app);
22464
+ }
22465
+ return app.use(createSyncPlugin(options));
22466
+ };
20794
22467
  }
20795
22468
 
20796
22469
  // src/server/sync/index.ts
20797
22470
  var furinSync2 = furinSync;
22471
+ // src/shared/await.tsx
22472
+ import { Component as Component2, createContext as createContext8, createElement as createElement10, use as use2, useMemo as useMemo2 } from "react";
22473
+ var AsyncErrorContext = createContext8(undefined);
22474
+ function useAsyncError() {
22475
+ return use2(AsyncErrorContext);
22476
+ }
22477
+ function useAsyncValue() {
22478
+ const ctx = use2(AwaitValueContext);
22479
+ if (!ctx) {
22480
+ throw new Error("useAsyncValue must be used inside <Await> children");
22481
+ }
22482
+ return use2(ctx.promise);
22483
+ }
22484
+ var AwaitValueContext = createContext8(undefined);
22485
+ function isAbortError(error) {
22486
+ return error instanceof Error && error.name === "AbortError";
22487
+ }
22488
+ function silenceAbortError(promise) {
22489
+ return promise.catch((error) => {
22490
+ if (isAbortError(error)) {
22491
+ return new Promise(() => {});
22492
+ }
22493
+ throw error;
22494
+ });
22495
+ }
22496
+
22497
+ class AsyncErrorBoundary extends Component2 {
22498
+ constructor(props) {
22499
+ super(props);
22500
+ this.state = { error: undefined, hasError: false, resolve: props.resolve };
22501
+ }
22502
+ static getDerivedStateFromProps(props, state) {
22503
+ if (props.resolve !== state.resolve) {
22504
+ return { error: undefined, hasError: false, resolve: props.resolve };
22505
+ }
22506
+ return null;
22507
+ }
22508
+ static getDerivedStateFromError(error) {
22509
+ return { error, hasError: true };
22510
+ }
22511
+ render() {
22512
+ const { hasError, error } = this.state;
22513
+ const { children, errorElement } = this.props;
22514
+ if (hasError) {
22515
+ if (errorElement === undefined) {
22516
+ throw error;
22517
+ }
22518
+ return createElement10(AsyncErrorContext.Provider, { value: error }, errorElement);
22519
+ }
22520
+ return children;
22521
+ }
22522
+ }
22523
+ function Await({ resolve, errorElement, children }) {
22524
+ const guardedResolve = useMemo2(() => silenceAbortError(resolve), [resolve]);
22525
+ return createElement10(AsyncErrorBoundary, { errorElement, resolve: guardedResolve }, createElement10(AwaitInner, { children, resolve: guardedResolve }));
22526
+ }
22527
+ function AwaitInner({ resolve, children }) {
22528
+ const value = use2(resolve);
22529
+ return createElement10(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
22530
+ }
20798
22531
 
20799
22532
  // src/furin.ts
20800
22533
  async function createProductionBrowserEventsPlugin(sync, deploymentTarget) {
@@ -20827,8 +22560,8 @@ function resolveClientDirFromEnv(dirName) {
20827
22560
  if (!envClientDir) {
20828
22561
  return null;
20829
22562
  }
20830
- const base = envClientDir.startsWith("/") ? envClientDir : resolve9(process.cwd(), envClientDir);
20831
- return dirName === "client" ? base : join7(dirname7(base), dirName);
22563
+ const base = envClientDir.startsWith("/") ? envClientDir : resolve10(process.cwd(), envClientDir);
22564
+ return dirName === "client" ? base : join7(dirname9(base), dirName);
20832
22565
  }
20833
22566
  function resolveClientDirFromModuleUrl(dirName) {
20834
22567
  try {
@@ -20840,7 +22573,7 @@ function resolveClientDirFromModuleUrl(dirName) {
20840
22573
  if (modulePath.includes("/$bunfs/")) {
20841
22574
  return null;
20842
22575
  }
20843
- const moduleClientDir = join7(dirname7(modulePath), dirName);
22576
+ const moduleClientDir = join7(dirname9(modulePath), dirName);
20844
22577
  if (existsSync8(join7(moduleClientDir, "index.html"))) {
20845
22578
  return moduleClientDir;
20846
22579
  }
@@ -20870,9 +22603,9 @@ function resolveClientDirFromCandidate(candidate, dirName) {
20870
22603
  if (candidate.includes("/$bunfs/") || candidate.startsWith("bunfs:")) {
20871
22604
  return null;
20872
22605
  }
20873
- const absolute = candidate.startsWith("/") ? candidate : resolve9(process.cwd(), candidate);
22606
+ const absolute = candidate.startsWith("/") ? candidate : resolve10(process.cwd(), candidate);
20874
22607
  if (existsSync8(absolute)) {
20875
- const clientDir = join7(dirname7(absolute), dirName);
22608
+ const clientDir = join7(dirname9(absolute), dirName);
20876
22609
  if (existsSync8(join7(clientDir, "index.html"))) {
20877
22610
  return clientDir;
20878
22611
  }
@@ -20887,7 +22620,7 @@ function resolveClientDirFromPath(candidate, dirName) {
20887
22620
  for (const dir of pathEntries) {
20888
22621
  const fullPath = join7(dir, candidate);
20889
22622
  if (existsSync8(fullPath)) {
20890
- const clientDir = join7(dirname7(fullPath), dirName);
22623
+ const clientDir = join7(dirname9(fullPath), dirName);
20891
22624
  if (existsSync8(join7(clientDir, "index.html"))) {
20892
22625
  return clientDir;
20893
22626
  }
@@ -20896,7 +22629,7 @@ function resolveClientDirFromPath(candidate, dirName) {
20896
22629
  return null;
20897
22630
  }
20898
22631
  function resolveFallbackClientDir(dirName) {
20899
- const defaultClientDir = resolve9(process.cwd(), ".furin/build/bun", dirName);
22632
+ const defaultClientDir = resolve10(process.cwd(), ".furin/build/bun", dirName);
20900
22633
  if (existsSync8(join7(defaultClientDir, "index.html"))) {
20901
22634
  return defaultClientDir;
20902
22635
  }
@@ -20919,6 +22652,9 @@ async function setupProdTemplate(embedded, clientDir, instance) {
20919
22652
  setProductionTemplatePath(templatePath, instance);
20920
22653
  }
20921
22654
  async function setupCompiledTemplate(ctx, embedded, clientDir, instance) {
22655
+ if (ctx.preloadManifest) {
22656
+ setProductionPreloadManifest(ctx.preloadManifest, instance);
22657
+ }
20922
22658
  if (ctx.templateHtml === undefined) {
20923
22659
  await setupProdTemplate(embedded, clientDir, instance);
20924
22660
  return;
@@ -21099,9 +22835,12 @@ function wrapWithRequestScope(app) {
21099
22835
  });
21100
22836
  });
21101
22837
  }
21102
- function createFurinPlugin(app, hmrPrefix) {
22838
+ function createFurinPlugin(app, hmrPrefix, hasSync) {
21103
22839
  const scopedApp = wrapWithRequestScope(app);
21104
22840
  return (parentApp) => {
22841
+ if (hasSync) {
22842
+ bindSyncValidation(parentApp);
22843
+ }
21105
22844
  const mounted = parentApp.use(scopedApp);
21106
22845
  if (hmrPrefix !== undefined) {
21107
22846
  const parentConfig = Reflect.get(parentApp, "~config");
@@ -21129,7 +22868,7 @@ function createNativeRouteRenderer(prefix, routes, root, buildId, searchRoutes)
21129
22868
  const hasPrefix = prefix !== "" && (pathname === prefix || pathname.startsWith(`${prefix}/`));
21130
22869
  const logicalPath = hasPrefix ? pathname.slice(prefix.length) : pathname;
21131
22870
  const matched = matchNativeRoute(logicalPath || "/");
21132
- if (!matched) {
22871
+ if (!matched || IS_DEV && !existsSync8(matched.route.path)) {
21133
22872
  const listenerOrigin = context.server?.url?.origin;
21134
22873
  return renderRootNotFound(root, request, listenerOrigin);
21135
22874
  }
@@ -21200,10 +22939,10 @@ async function furin({
21200
22939
  const syncPath = resolveSyncPath(sync);
21201
22940
  const elysiaLoggerOptions = initializeLogger(logger);
21202
22941
  const cwd = process.cwd();
21203
- const paramPagesDir = resolve9(cwd, pagesDir ?? "src/pages");
22942
+ const paramPagesDir = resolve10(cwd, pagesDir ?? "src/pages");
21204
22943
  const ctx = getCompileContext(paramPagesDir, prefix);
21205
22944
  const loggerPlugin = createLoggerPlugin(prefix, syncPath, elysiaLoggerOptions, clientLogging === true || ctx?.clientLogging === true);
21206
- const resolvedPagesDir = ctx?.rootPath ? dirname7(ctx.rootPath) : paramPagesDir;
22945
+ const resolvedPagesDir = ctx?.rootPath ? dirname9(ctx.rootPath) : paramPagesDir;
21207
22946
  const instanceName = `furin-${prefix}-${resolvedPagesDir.replaceAll("\\", "/")}`;
21208
22947
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
21209
22948
  assertPrefixAvailable(prefix, normalizedPagesDir);
@@ -21212,7 +22951,7 @@ async function furin({
21212
22951
  configurePageCache(instance, ctx, pageCache);
21213
22952
  if (IS_DEV) {
21214
22953
  const instanceSlug = prefix === "" ? "" : prefix.slice(1).replaceAll("/", "__");
21215
- const furinDir = resolve9(cwd, ".furin", instanceSlug);
22954
+ const furinDir = resolve10(cwd, ".furin", instanceSlug);
21216
22955
  await Promise.resolve().then(() => init_diagnostics());
21217
22956
  await Promise.resolve().then(() => init_graph());
21218
22957
  await Promise.resolve().then(() => init_plugin3());
@@ -21232,7 +22971,7 @@ async function furin({
21232
22971
  for (const sourcePath of sourcePaths) {
21233
22972
  let source;
21234
22973
  try {
21235
- source = readFileSync8(sourcePath, "utf8");
22974
+ source = readFileSync9(sourcePath, "utf8");
21236
22975
  } catch (error) {
21237
22976
  console.warn(`[furin] Could not read ${sourcePath} for route config autofix: ${error instanceof Error ? error.message : String(error)}`);
21238
22977
  continue;
@@ -21258,7 +22997,40 @@ async function furin({
21258
22997
  let matchNavigationData = buildRouteMatcher(initialSnapshot.routes);
21259
22998
  navigationDataMatchers.set(instance, (path) => matchNavigationData(path) !== null);
21260
22999
  await Promise.resolve().then(() => init_hydrate());
21261
- const writeCurrentDevFiles = (snapshot) => {
23000
+ await Promise.resolve().then(() => init_transform_client());
23001
+ let serverSourceVersion = 0;
23002
+ let serverDataSignatures = new Map;
23003
+ let serverSourcePaths;
23004
+ const writeCurrentDevFiles = (snapshot, changedSources) => {
23005
+ const paths = [
23006
+ ...new Set([
23007
+ snapshot.root.path,
23008
+ ...snapshot.routes.flatMap((route) => [
23009
+ route.path,
23010
+ ...route.routeChain.flatMap((entry) => entry.sourcePath ? [entry.sourcePath] : [])
23011
+ ])
23012
+ ])
23013
+ ].toSorted();
23014
+ const nextPaths = JSON.stringify(paths);
23015
+ const nextSignatures = new Map(paths.map((path) => {
23016
+ let signature;
23017
+ try {
23018
+ signature = getHmrDataSignature(readFileSync9(path, "utf8"), path);
23019
+ if (signature.startsWith("external:")) {
23020
+ signature = graph.sourceVersion(path);
23021
+ }
23022
+ } catch {
23023
+ signature = graph.sourceVersion(path);
23024
+ }
23025
+ return [path, signature];
23026
+ }));
23027
+ const changedPaths = new Set(changedSources);
23028
+ const importsChanged = paths.some((path) => !changedPaths.has(path) && serverDataSignatures.get(path) !== nextSignatures.get(path));
23029
+ if (importsChanged && serverSourcePaths === nextPaths) {
23030
+ serverSourceVersion += 1;
23031
+ }
23032
+ serverSourcePaths = nextPaths;
23033
+ serverDataSignatures = nextSignatures;
21262
23034
  writeDevFiles(snapshot.routes, {
21263
23035
  basePath: prefix,
21264
23036
  clientLogging: clientLogging ?? false,
@@ -21266,9 +23038,9 @@ async function furin({
21266
23038
  publicPath: `${prefix}/_client/`,
21267
23039
  rootLayout: snapshot.root.path,
21268
23040
  skipRouteTypes: prefix !== ""
21269
- }, cwd);
23041
+ }, cwd, String(serverSourceVersion));
21270
23042
  };
21271
- writeCurrentDevFiles(initialSnapshot);
23043
+ writeCurrentDevFiles(initialSnapshot, []);
21272
23044
  graph.commit(initialSnapshot);
21273
23045
  const hmrEntry = (await import(join7(furinDir, "index.html"))).default;
21274
23046
  const refreshDevelopmentRoutes = (changedSources) => withInstance(instance, async () => {
@@ -21277,8 +23049,12 @@ async function furin({
21277
23049
  const previousSnapshot = currentSnapshot();
21278
23050
  const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
21279
23051
  const next = await loadDevelopmentRoutes(resolvedPagesDir);
21280
- const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, next.routes);
21281
- writeCurrentDevFiles(nextSnapshot);
23052
+ const nextRoutes = next.routes.map((route) => route.routeChain.length > 0 ? route : {
23053
+ ...route,
23054
+ tags: previousSnapshot.routes.find((previous) => previous.path === route.path)?.tags
23055
+ });
23056
+ const nextSnapshot = createDevelopmentRouteSnapshot(prefix, next.root, nextRoutes);
23057
+ writeCurrentDevFiles(nextSnapshot, changedSources);
21282
23058
  graph.commit(nextSnapshot);
21283
23059
  matchNavigationData = buildRouteMatcher(nextSnapshot.routes);
21284
23060
  const diagnostics = devDiagnosticStore(instance);
@@ -21299,7 +23075,7 @@ async function furin({
21299
23075
  throw error;
21300
23076
  }
21301
23077
  });
21302
- const publicDir = resolve9(cwd, "public");
23078
+ const publicDir = resolve10(cwd, "public");
21303
23079
  const publicExists = existsSync8(publicDir);
21304
23080
  let routeTopologyWatcher;
21305
23081
  navigationDataRefreshers.set(instance, async () => {
@@ -21352,7 +23128,7 @@ async function furin({
21352
23128
  return await dispatchNativeRoute(notFoundContext);
21353
23129
  }));
21354
23130
  registerInstance(instance);
21355
- return createFurinPlugin(devApp, prefix);
23131
+ return createFurinPlugin(devApp, prefix, Boolean(sync));
21356
23132
  }
21357
23133
  if (!ctx) {
21358
23134
  throw new Error("[furin] No pre-built assets found. Run `bunx furin build` first.");
@@ -21394,7 +23170,7 @@ async function furin({
21394
23170
  await withInstance(instance, () => warmSSGCache(routes, root, origin, searchRoutes));
21395
23171
  }).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
23172
  registerInstance(instance);
21397
- return createFurinPlugin(prodApp, undefined);
23173
+ return createFurinPlugin(prodApp, undefined, Boolean(sync));
21398
23174
  }
21399
23175
  function createNotFoundHandling(prefix, routes, root, tryNativeDispatch) {
21400
23176
  const app = new Elysia13;