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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +3 -0
  4. package/dist/build/entry-template.ts +7 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +1671 -276
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/types.d.ts +6 -0
  9. package/dist/cli/index.js +1672 -286
  10. package/dist/client/client-module.d.ts +26 -0
  11. package/dist/client/define-route.d.ts +9 -0
  12. package/dist/client/document.d.ts +2 -0
  13. package/dist/client/internal/runtime-types.d.ts +2 -0
  14. package/dist/client/link.js +932 -118
  15. package/dist/client/mutation.d.ts +38 -0
  16. package/dist/client/query-store.d.ts +85 -0
  17. package/dist/client/query.d.ts +14 -0
  18. package/dist/client/route-api.d.ts +11 -0
  19. package/dist/client/router/context.d.ts +3 -2
  20. package/dist/client/router/index.d.ts +1 -1
  21. package/dist/client/router/link-utils.d.ts +8 -1
  22. package/dist/client/router/navigation.d.ts +2 -9
  23. package/dist/client/router/optimistic.d.ts +41 -0
  24. package/dist/client/router/search/index.d.ts +3 -3
  25. package/dist/client/router/search-store.d.ts +1 -0
  26. package/dist/client/router/sync-catch-up.d.ts +3 -0
  27. package/dist/client/router/types.d.ts +49 -7
  28. package/dist/client/sync.d.ts +39 -22
  29. package/dist/client.d.ts +11 -33
  30. package/dist/client.js +1219 -59
  31. package/dist/config.d.ts +7 -0
  32. package/dist/config.js +1 -0
  33. package/dist/define-route.d.ts +78 -32
  34. package/dist/env.d.ts +2 -2
  35. package/dist/furin.d.ts +1 -2
  36. package/dist/furin.js +2448 -710
  37. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  38. package/dist/plugin/index.js +349 -18
  39. package/dist/plugin/transform-client-module.d.ts +16 -0
  40. package/dist/plugin/transform-client.d.ts +2 -0
  41. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  42. package/dist/routes.d.ts +6 -0
  43. package/dist/rsc-client.js +87 -16
  44. package/dist/rsc.js +87 -16
  45. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  46. package/dist/server/auto-invalidate/types.d.ts +2 -0
  47. package/dist/server/cache/isr.d.ts +2 -4
  48. package/dist/server/cache/route-cache.d.ts +5 -0
  49. package/dist/server/dev/graph.d.ts +1 -0
  50. package/dist/server/dev-page-plugin.d.ts +5 -19
  51. package/dist/server/internal.d.ts +3 -0
  52. package/dist/server/internal.js +55 -35
  53. package/dist/server/production-server.js +54 -34
  54. package/dist/server/render/loaders.d.ts +4 -2
  55. package/dist/server/render/react-stream.d.ts +3 -0
  56. package/dist/server/render/ssr.d.ts +2 -1
  57. package/dist/server/render/template.d.ts +4 -0
  58. package/dist/server/router/defined-route.d.ts +2 -0
  59. package/dist/server/router/hmr.d.ts +1 -1
  60. package/dist/server/sync/adapter.d.ts +25 -4
  61. package/dist/server/sync/atomic.d.ts +25 -0
  62. package/dist/server/sync/drizzle/index.d.ts +45 -0
  63. package/dist/server/sync/drizzle/index.js +540 -0
  64. package/dist/server/sync/execution-error.d.ts +2 -0
  65. package/dist/server/sync/index.d.ts +2 -1
  66. package/dist/server/sync/index.js +533 -105
  67. package/dist/server/sync/mutation-handler.d.ts +4 -0
  68. package/dist/server/sync/plugin.d.ts +34 -11
  69. package/dist/server/sync/postgres/execute.d.ts +3 -0
  70. package/dist/server/sync/postgres/index.d.ts +12 -1
  71. package/dist/server/sync/postgres/index.js +34 -13
  72. package/dist/server/sync/postgres/sql.d.ts +8 -0
  73. package/dist/server/sync/prisma/index.d.ts +24 -0
  74. package/dist/server/sync/prisma/index.js +340 -0
  75. package/dist/server/sync/queries.d.ts +21 -0
  76. package/dist/server/sync/query-context.d.ts +5 -0
  77. package/dist/server/sync/redis/index.js +3 -3
  78. package/dist/server/sync/redis/scripts.d.ts +1 -1
  79. package/dist/server/sync/response.d.ts +1 -0
  80. package/dist/server/sync/sqlite/index.d.ts +3 -0
  81. package/dist/server/sync/sqlite/index.js +10 -4
  82. package/dist/server/sync/stream.d.ts +2 -5
  83. package/dist/server/sync/validation.d.ts +4 -0
  84. package/dist/shared/defer.d.ts +31 -0
  85. package/dist/shared/error.d.ts +2 -2
  86. package/dist/shared/page-key.d.ts +7 -0
  87. package/dist/shared/query-bindings.d.ts +12 -0
  88. package/dist/shared/route-frame.d.ts +1 -0
  89. package/dist/shared/sync-query.d.ts +40 -0
  90. package/package.json +29 -6
  91. package/src/adapter/package.ts +12 -2
  92. package/src/adapter/runtime-build.ts +63 -12
  93. package/src/adapter/static.ts +7 -2
  94. package/src/adapter/vercel.ts +15 -13
  95. package/src/build/client.ts +23 -5
  96. package/src/build/entry-template.ts +7 -0
  97. package/src/build/hydrate.ts +17 -3
  98. package/src/build/preload-manifest.ts +100 -0
  99. package/src/build/production-instrumentation.ts +6 -3
  100. package/src/build/types.ts +4 -0
  101. package/src/cli/index.ts +1 -0
  102. package/src/client/browser-events-runtime.ts +4 -0
  103. package/src/client/client-module.ts +57 -0
  104. package/src/client/define-route.ts +11 -1
  105. package/src/client/document.tsx +28 -18
  106. package/src/client/hmr.ts +2 -1
  107. package/src/client/internal/runtime-types.ts +2 -0
  108. package/src/client/link.tsx +8 -8
  109. package/src/client/mutation.ts +136 -0
  110. package/src/client/query-store.ts +418 -0
  111. package/src/client/query.tsx +67 -0
  112. package/src/client/route-api.tsx +75 -0
  113. package/src/client/router/boundary-tree.tsx +7 -2
  114. package/src/client/router/context.ts +57 -4
  115. package/src/client/router/index.ts +3 -0
  116. package/src/client/router/link-utils.ts +29 -1
  117. package/src/client/router/navigation.ts +3 -50
  118. package/src/client/router/optimistic.ts +233 -0
  119. package/src/client/router/provider.tsx +304 -44
  120. package/src/client/router/search/index.ts +37 -17
  121. package/src/client/router/search-store.ts +4 -0
  122. package/src/client/router/sync-catch-up.ts +7 -0
  123. package/src/client/router/types.ts +71 -9
  124. package/src/client/sync.ts +438 -65
  125. package/src/client.ts +20 -60
  126. package/src/config.ts +5 -0
  127. package/src/define-route.ts +113 -55
  128. package/src/env.d.ts +2 -2
  129. package/src/furin.ts +75 -13
  130. package/src/plugin/hmr-dependencies.ts +58 -0
  131. package/src/plugin/index.ts +38 -2
  132. package/src/plugin/routes.ts +3 -3
  133. package/src/plugin/transform-client-module.ts +123 -0
  134. package/src/plugin/transform-client.ts +293 -13
  135. package/src/plugin/transform-isomorphic.ts +11 -5
  136. package/src/routes.ts +8 -0
  137. package/src/rsc/shared.tsx +104 -18
  138. package/src/server/auto-invalidate/registry.ts +4 -0
  139. package/src/server/auto-invalidate/runtime.ts +17 -0
  140. package/src/server/auto-invalidate/types.ts +6 -0
  141. package/src/server/cache/isr.ts +6 -34
  142. package/src/server/cache/route-cache.ts +40 -4
  143. package/src/server/dev/graph.ts +16 -2
  144. package/src/server/dev-page-plugin.ts +93 -59
  145. package/src/server/internal.ts +3 -0
  146. package/src/server/render/document.tsx +10 -1
  147. package/src/server/render/element.tsx +7 -2
  148. package/src/server/render/isr.ts +61 -29
  149. package/src/server/render/loaders.ts +118 -47
  150. package/src/server/render/mixed-cache.ts +33 -4
  151. package/src/server/render/not-found.ts +4 -7
  152. package/src/server/render/ppr-document.ts +2 -1
  153. package/src/server/render/ppr-route.ts +30 -10
  154. package/src/server/render/react-stream.ts +17 -0
  155. package/src/server/render/route-frame-transport.ts +3 -0
  156. package/src/server/render/ssg.ts +51 -18
  157. package/src/server/render/ssr.ts +53 -8
  158. package/src/server/render/template.ts +23 -0
  159. package/src/server/router/defined-route.ts +3 -0
  160. package/src/server/router/hmr.ts +3 -2
  161. package/src/server/router/plugin.ts +27 -12
  162. package/src/server/sync/adapter.ts +41 -4
  163. package/src/server/sync/atomic.ts +303 -0
  164. package/src/server/sync/drizzle/index.ts +145 -0
  165. package/src/server/sync/execution-error.ts +1 -0
  166. package/src/server/sync/fingerprint.ts +2 -6
  167. package/src/server/sync/index.ts +6 -0
  168. package/src/server/sync/mutation-handler.ts +69 -0
  169. package/src/server/sync/plugin.ts +177 -60
  170. package/src/server/sync/postgres/execute.ts +20 -0
  171. package/src/server/sync/postgres/index.ts +52 -16
  172. package/src/server/sync/postgres/sql.ts +20 -0
  173. package/src/server/sync/prisma/index.ts +70 -0
  174. package/src/server/sync/queries.ts +75 -0
  175. package/src/server/sync/query-context.ts +85 -0
  176. package/src/server/sync/redis/index.ts +7 -3
  177. package/src/server/sync/redis/scripts.ts +1 -1
  178. package/src/server/sync/response.ts +21 -0
  179. package/src/server/sync/sqlite/index.ts +19 -8
  180. package/src/server/sync/stream.ts +14 -22
  181. package/src/server/sync/validation.ts +34 -0
  182. package/src/shared/defer.ts +48 -0
  183. package/src/shared/error.ts +2 -2
  184. package/src/shared/page-key.ts +36 -0
  185. package/src/shared/query-bindings.ts +138 -0
  186. package/src/shared/route-frame.ts +13 -1
  187. package/src/shared/route-map.ts +12 -2
  188. package/src/shared/sync-query.ts +138 -0
@@ -289,7 +289,7 @@ var init_instance = __esm(() => {
289
289
  // src/server/dev/graph.ts
290
290
  import { randomUUID } from "crypto";
291
291
  import { readFileSync, statSync } from "fs";
292
- import { dirname as dirname5, extname, resolve as resolve3 } from "path";
292
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
293
293
  function normalizeModulePath(path) {
294
294
  return path.replaceAll("\\", "/");
295
295
  }
@@ -302,7 +302,7 @@ function resolveDevSourceImports(source, path, loader) {
302
302
  const isSourceExtension = [".js", ".jsx", ".ts", ".tsx"].includes(extension);
303
303
  const absolute = imported.path.startsWith(".") && extension && !isSourceExtension ? resolve3(dirname5(path), imported.path) : Bun.resolveSync(imported.path, dirname5(path));
304
304
  const resolved = normalizeModulePath(absolute);
305
- if (!resolved.includes("/node_modules/")) {
305
+ if (isAbsolute2(resolved) && !resolved.includes("/node_modules/")) {
306
306
  imports.push(resolved);
307
307
  }
308
308
  } catch {}
@@ -448,6 +448,19 @@ class DevGraph {
448
448
  const normalizedTo = normalizeModulePath(to);
449
449
  return this.importChain(from, normalizedTo).includes(normalizedTo);
450
450
  }
451
+ sourceDependencies(from) {
452
+ const pending = [normalizeModulePath(from)];
453
+ const visited = new Set;
454
+ while (pending.length > 0) {
455
+ const path = pending.pop();
456
+ if (path === undefined || visited.has(path)) {
457
+ continue;
458
+ }
459
+ visited.add(path);
460
+ pending.push(...this.#dependencies.get(path) ?? []);
461
+ }
462
+ return [...visited];
463
+ }
451
464
  clearSourceErrors(path) {
452
465
  const modulePath = normalizeModulePath(path);
453
466
  for (const [message, positions] of this.#sourceErrors) {
@@ -3224,6 +3237,87 @@ var init_dead_code_elimination = __esm(() => {
3224
3237
  ]);
3225
3238
  });
3226
3239
 
3240
+ // src/plugin/transform-client-module.ts
3241
+ import { realpathSync as realpathSync2 } from "fs";
3242
+ import { dirname as dirname7 } from "path";
3243
+ function clientModuleKey(modulePath) {
3244
+ const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
3245
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
3246
+ }
3247
+ function collectClientModuleBindings(program) {
3248
+ const bindings = new Set;
3249
+ for (const statement of program.body) {
3250
+ if (statement.type !== "ImportDeclaration") {
3251
+ continue;
3252
+ }
3253
+ const declaration = statement;
3254
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
3255
+ continue;
3256
+ }
3257
+ for (const specifier of declaration.specifiers) {
3258
+ const imported = specifier.imported;
3259
+ const local = specifier.local;
3260
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
3261
+ bindings.add(local.name);
3262
+ }
3263
+ }
3264
+ }
3265
+ return bindings;
3266
+ }
3267
+ function dynamicImportSpecifier(loader) {
3268
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
3269
+ return null;
3270
+ }
3271
+ const body = loader.body;
3272
+ const source = body.type === "ImportExpression" ? body.source : null;
3273
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
3274
+ }
3275
+ function transformClientModules(source, filename, environment) {
3276
+ if (!source.includes("clientModule")) {
3277
+ return source;
3278
+ }
3279
+ const { program } = parseSource(source, detectLangFromPath(filename));
3280
+ const bindings = collectClientModuleBindings(program);
3281
+ if (bindings.size === 0) {
3282
+ return source;
3283
+ }
3284
+ const transformed = new MagicString(source);
3285
+ walk(program, {
3286
+ CallExpression(node, context) {
3287
+ const call = node;
3288
+ const [loader, ...rest] = call.arguments;
3289
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
3290
+ return;
3291
+ }
3292
+ const unwrapped = unwrapTSExpression(loader);
3293
+ const specifier = dynamicImportSpecifier(unwrapped);
3294
+ if (specifier === null) {
3295
+ return;
3296
+ }
3297
+ let key;
3298
+ try {
3299
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname7(filename))));
3300
+ } catch (error) {
3301
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
3302
+ }
3303
+ if (environment === "client") {
3304
+ transformed.appendLeft(loader.end, `, ${key}`);
3305
+ } else {
3306
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
3307
+ }
3308
+ }
3309
+ });
3310
+ return transformed.toString();
3311
+ }
3312
+ var FURIN_CLIENT_MODULES, SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
3313
+ var init_transform_client_module = __esm(() => {
3314
+ init_dist();
3315
+ init_dist2();
3316
+ init_lang_detect();
3317
+ init_parser();
3318
+ FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
3319
+ });
3320
+
3227
3321
  // src/plugin/transform-isomorphic.ts
3228
3322
  function importedName(specifier) {
3229
3323
  const { imported } = specifier;
@@ -3444,11 +3538,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
3444
3538
  }
3445
3539
  });
3446
3540
  }
3447
- function transformIsomorphicFunctions(source, filename, environment) {
3541
+ function transformIsomorphicFunctions(input, filename, environment) {
3448
3542
  const lang = detectLangFromPath(filename);
3449
3543
  if (lang === "dts") {
3450
- return { code: source, map: null, transformed: false };
3544
+ return { code: input, map: null, transformed: false };
3451
3545
  }
3546
+ const source = transformClientModules(input, filename, environment);
3547
+ const clientModulesTransformed = source !== input;
3452
3548
  const { program, diagnostics } = parseSource(source, lang);
3453
3549
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
3454
3550
  if (firstError) {
@@ -3460,7 +3556,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
3460
3556
  assertNoSplitChains(source, filename, program, builders);
3461
3557
  const candidates = collectCandidates(source, filename, program, bindings);
3462
3558
  if (candidates.length === 0) {
3463
- return { code: source, map: null, transformed: false };
3559
+ return { code: source, map: null, transformed: clientModulesTransformed };
3464
3560
  }
3465
3561
  const transformed = new MagicString(source);
3466
3562
  for (const candidate of candidates) {
@@ -3478,7 +3574,8 @@ function isomorphicTransformPlugin(environment) {
3478
3574
  return {
3479
3575
  name: `furin-isomorphic-${environment}`,
3480
3576
  setup(build) {
3481
- build.onLoad({ filter: SCRIPT_FILE_FILTER }, async ({ path }) => {
3577
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
3578
+ const path = args.path.split("?")[0];
3482
3579
  const source = await Bun.file(path).text();
3483
3580
  const loader = detectLoaderFromPath(path);
3484
3581
  const result = transformIsomorphicFunctions(source, path, environment);
@@ -3497,8 +3594,9 @@ var init_transform_isomorphic = __esm(() => {
3497
3594
  init_lang_detect();
3498
3595
  init_parser();
3499
3596
  init_dead_code_elimination();
3597
+ init_transform_client_module();
3500
3598
  FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
3501
- SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)$/;
3599
+ SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)(?:\?.*)?$/;
3502
3600
  });
3503
3601
 
3504
3602
  // src/server/sync/config.ts
@@ -3578,6 +3676,9 @@ class AutoInvalidateRegistry {
3578
3676
  }
3579
3677
  return [...paths];
3580
3678
  }
3679
+ tagsForPath(path) {
3680
+ return [...this.pathToTags.get(path) ?? []];
3681
+ }
3581
3682
  unregisterPath(urlPath, owner) {
3582
3683
  if (owner === undefined) {
3583
3684
  this.pathOwners.delete(urlPath);
@@ -3631,7 +3732,14 @@ function matchesPath(urlPath, path, type) {
3631
3732
  }
3632
3733
  function createRouteCache(options) {
3633
3734
  const store = new Map;
3735
+ const generations = new Map;
3634
3736
  const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
3737
+ const invalidateGenerations = (key) => {
3738
+ for (const generation of generations.get(key) ?? []) {
3739
+ generation.valid = false;
3740
+ }
3741
+ generations.delete(key);
3742
+ };
3635
3743
  const evictOldest = () => {
3636
3744
  if (options.maxSize === undefined || store.size <= options.maxSize) {
3637
3745
  return;
@@ -3642,6 +3750,7 @@ function createRouteCache(options) {
3642
3750
  }
3643
3751
  };
3644
3752
  const deleteEntry = (key) => {
3753
+ invalidateGenerations(key);
3645
3754
  const entry = store.get(key);
3646
3755
  if (entry === undefined) {
3647
3756
  return false;
@@ -3651,7 +3760,20 @@ function createRouteCache(options) {
3651
3760
  return true;
3652
3761
  };
3653
3762
  return {
3763
+ captureGeneration(key) {
3764
+ const generation = { valid: true };
3765
+ let pending = generations.get(key);
3766
+ if (pending === undefined) {
3767
+ pending = new Set;
3768
+ generations.set(key, pending);
3769
+ }
3770
+ pending.add(generation);
3771
+ return generation;
3772
+ },
3654
3773
  clear() {
3774
+ for (const key of generations.keys()) {
3775
+ invalidateGenerations(key);
3776
+ }
3655
3777
  for (const key of [...store.keys()]) {
3656
3778
  deleteEntry(key);
3657
3779
  }
@@ -3677,14 +3799,15 @@ function createRouteCache(options) {
3677
3799
  invalidatePath(path, type) {
3678
3800
  let deleted = false;
3679
3801
  const purgedPaths = [];
3680
- for (const key of [...store.keys()]) {
3802
+ for (const key of new Set([...store.keys(), ...generations.keys()])) {
3681
3803
  const urlPath = pathFromKey(key);
3682
3804
  if (urlPath === null || !matchesPath(urlPath, path, type)) {
3683
3805
  continue;
3684
3806
  }
3685
- deleteEntry(key);
3686
- deleted = true;
3687
- purgedPaths.push(urlPath);
3807
+ if (deleteEntry(key)) {
3808
+ deleted = true;
3809
+ purgedPaths.push(urlPath);
3810
+ }
3688
3811
  }
3689
3812
  return { deleted, purgedPaths: [...new Set(purgedPaths)] };
3690
3813
  },
@@ -3692,6 +3815,13 @@ function createRouteCache(options) {
3692
3815
  return store.keys();
3693
3816
  },
3694
3817
  name: options.name,
3818
+ releaseGeneration(key, generation) {
3819
+ const pending = generations.get(key);
3820
+ pending?.delete(generation);
3821
+ if (pending?.size === 0) {
3822
+ generations.delete(key);
3823
+ }
3824
+ },
3695
3825
  set(key, entry) {
3696
3826
  const previous = store.get(key);
3697
3827
  if (previous !== undefined) {
@@ -3728,7 +3858,7 @@ var init_registry2 = __esm(() => {
3728
3858
  instanceInvalidators = instanceSlot(() => new Map);
3729
3859
  });
3730
3860
 
3731
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
3861
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
3732
3862
  function elapsedMs(startTime) {
3733
3863
  return Math.max(0, Date.now() - startTime);
3734
3864
  }
@@ -3869,7 +3999,7 @@ var init_utils = __esm(() => {
3869
3999
  _isoDate = /* @__PURE__ */ new Date;
3870
4000
  });
3871
4001
 
3872
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
4002
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
3873
4003
  function normalizeRedactPathPattern(pattern) {
3874
4004
  if (!pattern.includes("*") && !pattern.includes("."))
3875
4005
  return `**.${pattern}`;
@@ -4178,7 +4308,7 @@ var init_redact_C7FmdhwI = __esm(() => {
4178
4308
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
4179
4309
  });
4180
4310
 
4181
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4311
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4182
4312
  function logPluginError(name, hook, err) {
4183
4313
  console.error(`[evlog/${name}] ${hook} failed:`, err);
4184
4314
  }
@@ -4348,7 +4478,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
4348
4478
  globalConfig = getRegistry().config;
4349
4479
  });
4350
4480
 
4351
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4481
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4352
4482
  function pushTreeSpacer(children) {
4353
4483
  children.push(PRETTY_ERROR_TREE_SPACER);
4354
4484
  }
@@ -4649,7 +4779,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
4649
4779
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
4650
4780
  });
4651
4781
 
4652
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4782
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4653
4783
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
4654
4784
  const compact = partial.compact ?? (inDev && pretty);
4655
4785
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -4702,7 +4832,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
4702
4832
  };
4703
4833
  });
4704
4834
 
4705
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4835
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4706
4836
  function hasWideEventPublisher() {
4707
4837
  return publisher !== null;
4708
4838
  }
@@ -4718,7 +4848,7 @@ function publishWideEvent(event) {
4718
4848
  var publisher = null;
4719
4849
  var init_wideEventChannel_BUDW48oP = () => {};
4720
4850
 
4721
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4851
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4722
4852
  function isEvlogError(error) {
4723
4853
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
4724
4854
  }
@@ -4727,7 +4857,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
4727
4857
  evlogErrorBrand = Symbol.for("evlog.error.brand");
4728
4858
  });
4729
4859
 
4730
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
4860
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
4731
4861
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
4732
4862
  var init_error = __esm(() => {
4733
4863
  init_utils();
@@ -4836,7 +4966,7 @@ var init_error = __esm(() => {
4836
4966
  });
4837
4967
  });
4838
4968
 
4839
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4969
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4840
4970
  function extractSafeHeaders(headers) {
4841
4971
  const raw = {};
4842
4972
  headers.forEach((value, key) => {
@@ -4857,7 +4987,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
4857
4987
  init_utils();
4858
4988
  });
4859
4989
 
4860
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
4990
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
4861
4991
  function writePrettyStdout(text) {
4862
4992
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
4863
4993
  }
@@ -5779,12 +5909,12 @@ var init_audit_C8euLMvu = __esm(() => {
5779
5909
  initLogger(__EVLOG_CONFIG__);
5780
5910
  });
5781
5911
 
5782
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
5912
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
5783
5913
  var init_dist3 = __esm(() => {
5784
5914
  init_audit_C8euLMvu();
5785
5915
  });
5786
5916
 
5787
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5917
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5788
5918
  function shouldDeferEmitForResponse(response) {
5789
5919
  if (!response.body)
5790
5920
  return false;
@@ -5864,7 +5994,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
5864
5994
  }
5865
5995
  var init_streamResponse_OlirMA5P = () => {};
5866
5996
 
5867
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
5997
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
5868
5998
  function extractErrorStatus(error) {
5869
5999
  if (error === null || typeof error !== "object")
5870
6000
  return 500;
@@ -5874,7 +6004,7 @@ function extractErrorStatus(error) {
5874
6004
  }
5875
6005
  var init_errors_CL8dDgIi = () => {};
5876
6006
 
5877
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
6007
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
5878
6008
  function shouldLog(path, include, exclude) {
5879
6009
  if (exclude && exclude.length > 0) {
5880
6010
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -5902,7 +6032,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
5902
6032
  init_utils();
5903
6033
  });
5904
6034
 
5905
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
6035
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
5906
6036
  function resolveMiddlewarePluginRunner(options) {
5907
6037
  const global2 = getGlobalPluginRunner();
5908
6038
  const local = options.plugins;
@@ -6097,7 +6227,7 @@ var init_middleware_fam3VyaL = __esm(() => {
6097
6227
  runnerCache = /* @__PURE__ */ new WeakMap;
6098
6228
  });
6099
6229
 
6100
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
6230
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
6101
6231
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
6102
6232
  const log = parent;
6103
6233
  log.fork = (label, fn) => {
@@ -6200,7 +6330,7 @@ var init_integration_CGD18W8r = __esm(() => {
6200
6330
  init_middleware_fam3VyaL();
6201
6331
  });
6202
6332
 
6203
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
6333
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
6204
6334
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6205
6335
  function createLoggerStorage(contextHint, id = contextHint) {
6206
6336
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -6219,7 +6349,7 @@ var init_storage = __esm(() => {
6219
6349
  init_globalRegistry_Bh3bIGwA();
6220
6350
  });
6221
6351
 
6222
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
6352
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
6223
6353
  var init_toolkit = __esm(() => {
6224
6354
  init_integration_CGD18W8r();
6225
6355
  init_storage();
@@ -6588,12 +6718,12 @@ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection",
6588
6718
  var init_plugin2 = () => {};
6589
6719
 
6590
6720
  // src/build/index.ts
6591
- import { existsSync as existsSync15, writeFileSync as writeFileSync11 } from "fs";
6592
- import { join as join17, relative as relative11, resolve as resolve10 } from "path";
6721
+ import { existsSync as existsSync16, writeFileSync as writeFileSync12 } from "fs";
6722
+ import { join as join17, relative as relative11, resolve as resolve12 } from "path";
6593
6723
 
6594
6724
  // src/adapter/bun.ts
6595
- import { existsSync as existsSync10, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
6596
- import { join as join12, resolve as resolve7 } from "path";
6725
+ import { existsSync as existsSync11, readFileSync as readFileSync8, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "fs";
6726
+ import { join as join12, resolve as resolve9 } from "path";
6597
6727
 
6598
6728
  // src/build/bun-build.ts
6599
6729
  function runBunBuild(config) {
@@ -6663,6 +6793,7 @@ function buildAppContextBlock(app, varPrefix) {
6663
6793
  const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
6664
6794
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
6665
6795
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
6796
+ const preloadManifestLine = app.preloadManifest ? ` preloadManifest: ${JSON.stringify(app.preloadManifest)},` : "";
6666
6797
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
6667
6798
  const contextLines = [
6668
6799
  "__setCompileContext({",
@@ -6682,6 +6813,7 @@ function buildAppContextBlock(app, varPrefix) {
6682
6813
  routeMetadataLine,
6683
6814
  serveAssetsLine,
6684
6815
  ssgCacheLine,
6816
+ preloadManifestLine,
6685
6817
  templateHtmlLine,
6686
6818
  ...app.extraContext ?? [],
6687
6819
  "});"
@@ -6945,9 +7077,9 @@ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from
6945
7077
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
6946
7078
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
6947
7079
  var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
6948
- var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
7080
+ var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\](?:route-config-autofix|transform-client))(?:\.ts|\.js)?$/;
6949
7081
  var HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
6950
- var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
7082
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix|transform-client)(?:\.ts|\.js)?$/;
6951
7083
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
6952
7084
  var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
6953
7085
  function isFurinRuntimePath(path) {
@@ -6955,6 +7087,9 @@ function isFurinRuntimePath(path) {
6955
7087
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
6956
7088
  }
6957
7089
  function devBuildExport(path) {
7090
+ if (path.includes("transform-client")) {
7091
+ return "getHmrDataSignature";
7092
+ }
6958
7093
  return path.includes("route-config-autofix") ? "fixRouteConfigLayout" : "writeDevFiles";
6959
7094
  }
6960
7095
  function productionInstrumentationPlugin() {
@@ -7007,13 +7142,24 @@ import {
7007
7142
  statSync as statSync2,
7008
7143
  watch
7009
7144
  } from "fs";
7010
- import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve4, sep } from "path";
7145
+ import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute3, join as join5, relative as relative4, resolve as resolve4, sep } from "path";
7011
7146
  import { pathToFileURL } from "url";
7012
7147
  import { Elysia } from "elysia";
7013
7148
 
7014
7149
  // src/shared/elysia-contract.ts
7015
7150
  import { Validator } from "elysia";
7016
7151
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
7152
+ function getSchemaValidator(schema) {
7153
+ const validator = Validator.create(schema);
7154
+ if (validator === undefined) {
7155
+ return;
7156
+ }
7157
+ return {
7158
+ Check: (value) => validator.Check(value),
7159
+ Errors: (value) => validator.Errors(value),
7160
+ parse: async (value, type) => validator.From ? await validator.From(value, type) : value
7161
+ };
7162
+ }
7017
7163
  function isTypeBoxObjectSchema(schema) {
7018
7164
  if (schema === null || typeof schema !== "object") {
7019
7165
  return false;
@@ -7187,6 +7333,214 @@ function mergeRouteSchemas(routeChain, key) {
7187
7333
  }
7188
7334
 
7189
7335
  // src/server/router/schemas.ts
7336
+ function decodeQueryPart(value) {
7337
+ return new URLSearchParams(`value=${value}`).get("value") ?? "";
7338
+ }
7339
+ function parseArrayQueryValue(raw, decoded, repeated) {
7340
+ const rawBracketed = raw.startsWith("[") && raw.endsWith("]");
7341
+ const decodedBracketed = decoded.startsWith("[") && decoded.endsWith("]");
7342
+ if (repeated && !rawBracketed && !decodedBracketed) {
7343
+ return [decoded];
7344
+ }
7345
+ if (decoded === "[]") {
7346
+ return [];
7347
+ }
7348
+ if (rawBracketed) {
7349
+ return raw.slice(1, -1).split(",").map(decodeQueryPart);
7350
+ }
7351
+ if (decodedBracketed) {
7352
+ return decoded.slice(1, -1).split(",");
7353
+ }
7354
+ return raw.includes(",") ? raw.split(",").map(decodeQueryPart) : [decoded];
7355
+ }
7356
+ function parseQueryFromURL(search, arrayKeys) {
7357
+ const query = Object.create(null);
7358
+ if (!arrayKeys) {
7359
+ for (const [key, value] of new URLSearchParams(search)) {
7360
+ query[key] = value;
7361
+ }
7362
+ return query;
7363
+ }
7364
+ for (const pair of search.slice(1).split("&")) {
7365
+ const entry = new URLSearchParams(pair).entries().next().value;
7366
+ if (!entry) {
7367
+ continue;
7368
+ }
7369
+ const [key, value] = entry;
7370
+ if (!arrayKeys[key]) {
7371
+ query[key] = value;
7372
+ continue;
7373
+ }
7374
+ const equalIndex = pair.indexOf("=");
7375
+ const rawValue = equalIndex === -1 ? "" : pair.slice(equalIndex + 1);
7376
+ const previous = query[key];
7377
+ const values = parseArrayQueryValue(rawValue, value, Array.isArray(previous));
7378
+ if (Array.isArray(previous)) {
7379
+ previous.push(...values);
7380
+ } else {
7381
+ query[key] = values;
7382
+ }
7383
+ }
7384
+ return query;
7385
+ }
7386
+ function isObjectSchema(schema) {
7387
+ return !!schema && typeof schema === "object";
7388
+ }
7389
+ function isStandardSchema(schema) {
7390
+ return isObjectSchema(schema) && "~standard" in schema;
7391
+ }
7392
+ function collectQueryArrayKeys(schema) {
7393
+ return collectQueryKeys(schema, "array");
7394
+ }
7395
+ function collectQueryObjectKeys(schema) {
7396
+ return collectQueryKeys(schema, "object");
7397
+ }
7398
+ function collectQueryKeys(schema, type) {
7399
+ if (!isObjectSchema(schema)) {
7400
+ return;
7401
+ }
7402
+ const keys = {};
7403
+ if (isObjectSchema(schema.properties)) {
7404
+ for (const [key, value] of Object.entries(schema.properties)) {
7405
+ if (hasSchemaType(value, type)) {
7406
+ keys[key] = 1;
7407
+ }
7408
+ }
7409
+ }
7410
+ for (const keyword of ["allOf", "anyOf"]) {
7411
+ const members = schema[keyword];
7412
+ if (!Array.isArray(members)) {
7413
+ continue;
7414
+ }
7415
+ for (const member of members) {
7416
+ Object.assign(keys, collectQueryKeys(member, type));
7417
+ }
7418
+ }
7419
+ return Object.keys(keys).length > 0 ? keys : undefined;
7420
+ }
7421
+ function hasSchemaType(schema, type) {
7422
+ if (!isObjectSchema(schema)) {
7423
+ return false;
7424
+ }
7425
+ if (schema.type === type) {
7426
+ return true;
7427
+ }
7428
+ for (const keyword of ["allOf", "anyOf"]) {
7429
+ const members = schema[keyword];
7430
+ if (Array.isArray(members) && members.some((member) => hasSchemaType(member, type))) {
7431
+ return true;
7432
+ }
7433
+ }
7434
+ return false;
7435
+ }
7436
+ function parseJsonQueryObjects(query, objectKeys) {
7437
+ if (!objectKeys) {
7438
+ return query;
7439
+ }
7440
+ const parsed = { ...query };
7441
+ for (const key of Object.keys(objectKeys)) {
7442
+ const value = parsed[key];
7443
+ if (typeof value !== "string") {
7444
+ continue;
7445
+ }
7446
+ try {
7447
+ parsed[key] = JSON.parse(value);
7448
+ } catch {
7449
+ parsed[key] = value;
7450
+ }
7451
+ }
7452
+ return parsed;
7453
+ }
7454
+ function coerceUnionValue(members, value) {
7455
+ for (const member of members) {
7456
+ const candidate = coerceSchemaValue(member, value);
7457
+ const validator = getSchemaValidator(member);
7458
+ if (validator?.Check(candidate)) {
7459
+ return candidate;
7460
+ }
7461
+ }
7462
+ return value;
7463
+ }
7464
+ function coerceObjectValue(properties, value) {
7465
+ const coerced = { ...value };
7466
+ for (const [key, propertySchema] of Object.entries(properties)) {
7467
+ if (key in coerced) {
7468
+ coerced[key] = coerceSchemaValue(propertySchema, coerced[key]);
7469
+ }
7470
+ }
7471
+ return coerced;
7472
+ }
7473
+ function coerceStringValue(schema, value) {
7474
+ if (value.length === 0) {
7475
+ return value;
7476
+ }
7477
+ if (schema.type === "boolean") {
7478
+ if (value === "true") {
7479
+ return true;
7480
+ }
7481
+ if (value === "false") {
7482
+ return false;
7483
+ }
7484
+ return value;
7485
+ }
7486
+ if (schema.type === "number" || schema.type === "integer") {
7487
+ const number = Number(value);
7488
+ if (Number.isFinite(number) && (schema.type !== "integer" || Number.isInteger(number))) {
7489
+ return number;
7490
+ }
7491
+ }
7492
+ return value;
7493
+ }
7494
+ function coerceSchemaValue(schema, value) {
7495
+ if (!isObjectSchema(schema)) {
7496
+ return value;
7497
+ }
7498
+ if (Array.isArray(schema.anyOf)) {
7499
+ return coerceUnionValue(schema.anyOf, value);
7500
+ }
7501
+ if (Array.isArray(schema.allOf)) {
7502
+ return schema.allOf.reduce((candidate, member) => coerceSchemaValue(member, candidate), value);
7503
+ }
7504
+ if (schema.type === "object" && isObjectSchema(schema.properties) && isObjectSchema(value)) {
7505
+ return coerceObjectValue(schema.properties, value);
7506
+ }
7507
+ if (schema.type === "array" && Array.isArray(value)) {
7508
+ return value.map((entry) => coerceSchemaValue(schema.items, entry));
7509
+ }
7510
+ return typeof value === "string" ? coerceStringValue(schema, value) : value;
7511
+ }
7512
+ function coerceRouteInput(schema, value) {
7513
+ return coerceSchemaValue(schema, value);
7514
+ }
7515
+ async function validateRouteInput(input, schema, type) {
7516
+ const inputWithDefaults = isStandardSchema(schema) ? input : applySchemaDefaults(schema, input);
7517
+ const valueToValidate = isStandardSchema(schema) ? inputWithDefaults : coerceRouteInput(schema, inputWithDefaults);
7518
+ const validator = getSchemaValidator(schema);
7519
+ try {
7520
+ const parsed = await validator?.parse(valueToValidate, type);
7521
+ return {
7522
+ ok: true,
7523
+ value: parsed ?? valueToValidate
7524
+ };
7525
+ } catch {
7526
+ return { errors: [...validator?.Errors(valueToValidate) ?? []], ok: false };
7527
+ }
7528
+ }
7529
+ async function parseRouteQuery(url, schema) {
7530
+ if (!schema) {
7531
+ return { ok: true, query: parseQueryFromURL(url.search) };
7532
+ }
7533
+ const rawQuery = isStandardSchema(schema) ? parseQueryFromURL(url.search) : parseJsonQueryObjects(parseQueryFromURL(url.search, collectQueryArrayKeys(schema)), collectQueryObjectKeys(schema));
7534
+ const result = await validateRouteInput(rawQuery, schema, "query");
7535
+ return result.ok ? { ok: true, query: result.value } : result;
7536
+ }
7537
+ async function parseRouteParams(params, schema) {
7538
+ if (!schema) {
7539
+ return { ok: true, params };
7540
+ }
7541
+ const result = await validateRouteInput(params, schema, "params");
7542
+ return result.ok ? { ok: true, params: result.value } : result;
7543
+ }
7190
7544
  function createSearchRouteMetadata(routes) {
7191
7545
  const metadata = [];
7192
7546
  for (const route of routes) {
@@ -7202,6 +7556,23 @@ function createSearchRouteMetadata(routes) {
7202
7556
  }
7203
7557
  return metadata;
7204
7558
  }
7559
+ function applySchemaDefaults(schema, values) {
7560
+ if (!schema || typeof schema !== "object") {
7561
+ return values;
7562
+ }
7563
+ const s = schema;
7564
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
7565
+ return values;
7566
+ }
7567
+ const result = { ...values };
7568
+ const properties = s.properties;
7569
+ for (const [key, propSchema] of Object.entries(properties)) {
7570
+ if (!(key in result) && propSchema && typeof propSchema === "object" && "default" in propSchema) {
7571
+ result[key] = propSchema.default;
7572
+ }
7573
+ }
7574
+ return result;
7575
+ }
7205
7576
 
7206
7577
  // src/plugin/routes.ts
7207
7578
  init_lang_detect();
@@ -7459,7 +7830,7 @@ function findPackageRoot(sourcePath) {
7459
7830
  }
7460
7831
  function isWithinDirectory(path, directory) {
7461
7832
  const relativePath = relative4(directory, path);
7462
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
7833
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute3(relativePath));
7463
7834
  }
7464
7835
  function isFurinPackageImport(specifier) {
7465
7836
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -7477,7 +7848,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
7477
7848
  }
7478
7849
  try {
7479
7850
  const resolvedImport = realpathSync.native(Bun.resolveSync(imported.path, dirname6(dependencyPath)));
7480
- if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative4(packageRoot, resolvedImport).split(sep).includes("node_modules")) {
7851
+ if (isAbsolute3(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative4(packageRoot, resolvedImport).split(sep).includes("node_modules")) {
7481
7852
  resolvedImports.push(resolvedImport);
7482
7853
  }
7483
7854
  } catch {}
@@ -7551,7 +7922,7 @@ async function clientRoutesSource(instance) {
7551
7922
  const module = await loadRouteModule(routeFile.sourcePath);
7552
7923
  validateRouteParams(routeFile.path, module.route?.schemas);
7553
7924
  return {
7554
- hasLoader: module.route?.loader !== undefined || module.route?.useLoaderData !== undefined,
7925
+ hasLoader: module.route?.loader !== undefined,
7555
7926
  mode: module.route?.mode ?? "ssr",
7556
7927
  pattern: routeFile.path
7557
7928
  };
@@ -7740,13 +8111,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
7740
8111
  }
7741
8112
 
7742
8113
  // src/adapter/runtime-build.ts
7743
- import { existsSync as existsSync9, writeFileSync as writeFileSync6 } from "fs";
7744
- import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join11, relative as relative7, resolve as resolve6 } from "path";
8114
+ import { existsSync as existsSync10, realpathSync as realpathSync4, writeFileSync as writeFileSync7 } from "fs";
8115
+ import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute5, join as join11, relative as relative7, resolve as resolve8 } from "path";
7745
8116
  import { fileURLToPath as fileURLToPath5 } from "url";
7746
8117
 
7747
8118
  // src/build/client.ts
7748
- import { existsSync as existsSync8, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
7749
- import { basename as basename2, dirname as dirname7, join as join9, resolve as resolve5 } from "path";
8119
+ import { existsSync as existsSync9, mkdirSync as mkdirSync3, writeFileSync as writeFileSync5 } from "fs";
8120
+ import { basename as basename3, dirname as dirname9, join as join9, resolve as resolve7 } from "path";
7750
8121
 
7751
8122
  // src/plugin/transform-client.ts
7752
8123
  init_dist();
@@ -7754,13 +8125,60 @@ init_dist2();
7754
8125
  init_lang_detect();
7755
8126
  init_parser();
7756
8127
  init_dead_code_elimination();
8128
+
8129
+ // src/plugin/hmr-dependencies.ts
8130
+ init_lang_detect();
8131
+ import { readFileSync as readFileSync3 } from "fs";
8132
+ import { dirname as dirname8, isAbsolute as isAbsolute4, resolve as resolve5 } from "path";
8133
+ var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
8134
+ function hmrDependencySignature(imports, filename) {
8135
+ const routePath = resolve5(filename);
8136
+ const visited = new Set;
8137
+ const hash = new Bun.CryptoHasher("sha256");
8138
+ const visit = (specifier, importer) => {
8139
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
8140
+ return true;
8141
+ }
8142
+ const path = Bun.resolveSync(specifier, dirname8(importer));
8143
+ if (path === routePath) {
8144
+ return false;
8145
+ }
8146
+ hash.update(JSON.stringify([specifier, path]));
8147
+ if (!isAbsolute4(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
8148
+ return true;
8149
+ }
8150
+ visited.add(path);
8151
+ const source = readFileSync3(path, "utf8");
8152
+ hash.update(source);
8153
+ if (SCRIPT_FILE.test(path)) {
8154
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
8155
+ for (const dependency of transpiler.scanImports(source)) {
8156
+ if (!visit(dependency.path, path)) {
8157
+ return false;
8158
+ }
8159
+ }
8160
+ }
8161
+ return true;
8162
+ };
8163
+ try {
8164
+ for (const specifier of imports) {
8165
+ if (!visit(specifier, routePath)) {
8166
+ return;
8167
+ }
8168
+ }
8169
+ return hash.digest("hex");
8170
+ } catch {}
8171
+ }
8172
+
8173
+ // src/plugin/transform-client.ts
7757
8174
  init_transform_isomorphic();
7758
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
8175
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
7759
8176
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
7760
8177
  var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
7761
8178
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
7762
8179
  var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
7763
8180
  var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
8181
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
7764
8182
  var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7765
8183
  ["TSAsExpression", ["expression"]],
7766
8184
  ["TSInstantiationExpression", ["expression"]],
@@ -7770,7 +8188,7 @@ var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7770
8188
  ["TSTypeAssertion", ["expression"]]
7771
8189
  ]);
7772
8190
  function isFurinRouteModule(source) {
7773
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
8191
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
7774
8192
  }
7775
8193
  function importedName2(specifier) {
7776
8194
  const { imported } = specifier;
@@ -7870,8 +8288,51 @@ function chainRootIsDefineRoute(node, bindings, ancestors) {
7870
8288
  }
7871
8289
  return false;
7872
8290
  }
7873
- function removeChainedServerCalls(source, program, bindings) {
8291
+ function assertCompleteRouteChains(program, bindings, filename) {
8292
+ const namespaces = new Set;
8293
+ for (const statement of program.body) {
8294
+ if (statement.type !== "ImportDeclaration") {
8295
+ continue;
8296
+ }
8297
+ const declaration = statement;
8298
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
8299
+ continue;
8300
+ }
8301
+ for (const specifier of declaration.specifiers) {
8302
+ const name = localName2(specifier);
8303
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
8304
+ namespaces.add(name);
8305
+ }
8306
+ }
8307
+ }
8308
+ walk(program, {
8309
+ MemberExpression(node, context) {
8310
+ const object = asAstNode(node.object);
8311
+ const property = asAstNode(node.property);
8312
+ const method = property?.type === "Identifier" ? property.name : property?.value;
8313
+ if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
8314
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
8315
+ }
8316
+ if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
8317
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
8318
+ }
8319
+ },
8320
+ VariableDeclarator(node, context) {
8321
+ const initializer = asAstNode(node.init);
8322
+ if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
8323
+ return;
8324
+ }
8325
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
8326
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
8327
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
8328
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
8329
+ }
8330
+ }
8331
+ });
8332
+ }
8333
+ function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
7874
8334
  let transformed = rewriteClientImports(source, program, bindings);
8335
+ const { declarations } = collectModuleBindings(program);
7875
8336
  walk(program, {
7876
8337
  CallExpression(call, context) {
7877
8338
  const callee = asAstNode(call.callee);
@@ -7886,12 +8347,93 @@ function removeChainedServerCalls(source, program, bindings) {
7886
8347
  if (!object) {
7887
8348
  return;
7888
8349
  }
8350
+ if (property.name === "config" && Array.isArray(call.arguments)) {
8351
+ const config = asAstNode(call.arguments[0]);
8352
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8353
+ collectConfigBindings(config, declarations, configBindings);
8354
+ const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
8355
+ if (remount) {
8356
+ source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
8357
+ transformed = true;
8358
+ return;
8359
+ }
8360
+ }
8361
+ }
7889
8362
  source.remove(object.end, call.end);
7890
8363
  transformed = true;
7891
8364
  }
7892
8365
  });
7893
8366
  return transformed;
7894
8367
  }
8368
+ function collectConfigBindings(config, declarations, names) {
8369
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
8370
+ names.add(config.name);
8371
+ const declaration = declarations.get(config.name);
8372
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
8373
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8374
+ for (const property of config.properties) {
8375
+ const entry = asAstNode(property);
8376
+ if (entry?.type === "SpreadElement") {
8377
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
8378
+ }
8379
+ }
8380
+ }
8381
+ }
8382
+ function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
8383
+ if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
8384
+ visiting.add(config.name);
8385
+ configBindings.add(config.name);
8386
+ const declaration = declarations.get(config.name);
8387
+ const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
8388
+ visiting.delete(config.name);
8389
+ return result;
8390
+ }
8391
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
8392
+ throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
8393
+ }
8394
+ for (let index = config.properties.length - 1;index >= 0; index -= 1) {
8395
+ const entry = asAstNode(config.properties[index]);
8396
+ if (entry?.type === "SpreadElement") {
8397
+ const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
8398
+ if (remount) {
8399
+ return remount;
8400
+ }
8401
+ } else if (entry?.type === "Property") {
8402
+ const key = asAstNode(entry.key);
8403
+ if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
8404
+ return entry;
8405
+ }
8406
+ }
8407
+ }
8408
+ return null;
8409
+ }
8410
+ function pruneUnusedConfigBindings(source, filename, names) {
8411
+ let result = source;
8412
+ let pruned = true;
8413
+ while (pruned) {
8414
+ pruned = false;
8415
+ const code = result.toString();
8416
+ const { program } = parseSource(code, detectLangFromPath(filename));
8417
+ const references = new Set;
8418
+ walkWithAncestors(program, [], (node, ancestors) => {
8419
+ if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
8420
+ references.add(node.name);
8421
+ }
8422
+ });
8423
+ result = new MagicString(code);
8424
+ for (const statement of program.body) {
8425
+ if (statement.type !== "VariableDeclaration") {
8426
+ continue;
8427
+ }
8428
+ const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
8429
+ if (retained.length !== statement.declarations.length) {
8430
+ result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
8431
+ pruned = true;
8432
+ }
8433
+ }
8434
+ }
8435
+ return result;
8436
+ }
7895
8437
  function collectBindingNames(pattern, names) {
7896
8438
  const node = asAstNode(pattern);
7897
8439
  if (!node) {
@@ -7943,13 +8485,13 @@ function collectDeclarationBindings(declaration, declarations) {
7943
8485
  }
7944
8486
  function collectModuleBindings(program) {
7945
8487
  const declarations = new Map;
7946
- const imports = new Set;
8488
+ const imports = new Map;
7947
8489
  for (const statement of program.body) {
7948
8490
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
7949
8491
  for (const specifier of statement.specifiers) {
7950
8492
  const local = localName2(specifier);
7951
8493
  if (local) {
7952
- imports.add(local);
8494
+ imports.set(local, statement);
7953
8495
  }
7954
8496
  }
7955
8497
  continue;
@@ -8037,13 +8579,16 @@ function walkWithAncestors(value, ancestors, visitor) {
8037
8579
  }
8038
8580
  }
8039
8581
  function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8040
- if (child.type !== "Identifier" || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8582
+ const parent = ancestors.at(-1);
8583
+ 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);
8584
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8041
8585
  return;
8042
8586
  }
8043
8587
  const declaration = state.moduleBindings.declarations.get(child.name);
8044
8588
  if (!declaration) {
8045
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
8046
- state.hasUnresolvedImport = true;
8589
+ const imported = state.moduleBindings.imports.get(child.name);
8590
+ if (trackImports && imported) {
8591
+ state.imports.add(imported);
8047
8592
  }
8048
8593
  return;
8049
8594
  }
@@ -8064,13 +8609,20 @@ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8064
8609
  function collectDependencies(node, trackImports, state) {
8065
8610
  walkWithAncestors(node, [], (child, ancestors) => {
8066
8611
  collectDependencyIdentifier(child, ancestors, trackImports, state);
8612
+ if (trackImports && child.type === "ImportExpression") {
8613
+ const specifier = asAstNode(child.source)?.value;
8614
+ if (typeof specifier === "string") {
8615
+ state.dynamicImports.add(specifier);
8616
+ }
8617
+ }
8067
8618
  });
8068
8619
  }
8069
- function createHmrDataSignature(code, program, bindings) {
8620
+ function createHmrDataSignature(code, program, bindings, filename) {
8070
8621
  const serverStages = [];
8071
8622
  const dependencyState = {
8072
8623
  dependencies: new Map,
8073
- hasUnresolvedImport: false,
8624
+ dynamicImports: new Set,
8625
+ imports: new Set,
8074
8626
  importTrackedDependencies: new Set,
8075
8627
  moduleBindings: collectModuleBindings(program)
8076
8628
  };
@@ -8104,6 +8656,10 @@ function createHmrDataSignature(code, program, bindings) {
8104
8656
  });
8105
8657
  const dataSource = [
8106
8658
  ...serverStages,
8659
+ ...[...dependencyState.imports].map((imported) => ({
8660
+ source: code.slice(imported.start, imported.end),
8661
+ start: imported.start
8662
+ })),
8107
8663
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
8108
8664
  source: code.slice(dependency.start, dependency.end),
8109
8665
  start: dependency.start
@@ -8111,7 +8667,14 @@ function createHmrDataSignature(code, program, bindings) {
8111
8667
  ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
8112
8668
  `);
8113
8669
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
8114
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
8670
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
8671
+ return hash;
8672
+ }
8673
+ const dependencies = hmrDependencySignature(new Set([
8674
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
8675
+ ...dependencyState.dynamicImports
8676
+ ]), filename);
8677
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
8115
8678
  }
8116
8679
  function calledHookName(call) {
8117
8680
  const callee = asAstNode(call.callee);
@@ -8329,9 +8892,14 @@ function transformForClient(code, filename) {
8329
8892
  }
8330
8893
  let source = new MagicString(clientSource);
8331
8894
  const routeBindings = collectDefineRouteBindings(program);
8332
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
8895
+ assertCompleteRouteChains(program, routeBindings, filename);
8896
+ const configBindings = new Set;
8897
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
8333
8898
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
8334
8899
  if (removedServerCode) {
8900
+ if (configBindings.size > 0) {
8901
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
8902
+ }
8335
8903
  source = deadCodeElimination(source, code, lang);
8336
8904
  }
8337
8905
  const transformedCode = source.toString();
@@ -8350,11 +8918,16 @@ function transformForClient(code, filename) {
8350
8918
  if (originalError) {
8351
8919
  throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
8352
8920
  }
8353
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program));
8921
+ const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
8354
8922
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
8355
8923
  source.append(`
8356
8924
  if (import.meta.hot && route?.component) {
8357
8925
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
8926
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
8927
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
8928
+ configurable: true,
8929
+ value: previousSourceSignature,
8930
+ });
8358
8931
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
8359
8932
  configurable: true,
8360
8933
  value: previousDataSignature,
@@ -8370,10 +8943,14 @@ if (import.meta.hot && route?.component) {
8370
8943
  updatedRoute,
8371
8944
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
8372
8945
  );
8946
+ // An unchanged source can be re-evaluated by Bun after an import edit
8947
+ // without rerunning this transform. Its embedded dependency hash is stale.
8373
8948
  const dataChanged =
8374
8949
  previousDataSignature.startsWith("external:") ||
8375
8950
  typeof updatedDataSignature !== "string" ||
8376
8951
  updatedDataSignature.startsWith("external:") ||
8952
+ (updatedDataSignature.startsWith("imports:") &&
8953
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
8377
8954
  updatedDataSignature !== previousDataSignature;
8378
8955
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
8379
8956
  }
@@ -8392,7 +8969,7 @@ if (import.meta.hot && route?.component) {
8392
8969
  init_lang_detect();
8393
8970
 
8394
8971
  // src/build/hydrate.ts
8395
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
8972
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
8396
8973
  import { join as join8 } from "path";
8397
8974
 
8398
8975
  // src/server/render/shell.ts
@@ -8447,7 +9024,7 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
8447
9024
  init_patterns();
8448
9025
 
8449
9026
  // src/build/route-types.ts
8450
- import { existsSync as existsSync6, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
9027
+ import { existsSync as existsSync6, readFileSync as readFileSync4, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
8451
9028
  import { extname as extname3, join as join7, relative as relative5 } from "path";
8452
9029
 
8453
9030
  // src/shared/route-map.ts
@@ -8474,12 +9051,19 @@ function compareRouteProperties(left, right) {
8474
9051
  return leftProperty < rightProperty ? -1 : 1;
8475
9052
  }
8476
9053
  function routeMapDeclaration(entries) {
8477
- const body = entries.toSorted(compareRouteProperties).map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
9054
+ const sorted = entries.toSorted(compareRouteProperties);
9055
+ const body = sorted.map((entry) => ` ${routeTypeProperty(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
9056
+ `);
9057
+ const patterns = sorted.map((entry) => ` ${JSON.stringify(entry.pattern)}: typeof import(${JSON.stringify(entry.importSpecifier)}).route;`).join(`
8478
9058
  `);
8479
9059
  return `declare module "@teyik0/furin/routes" {
8480
9060
  interface RouteMap {
8481
9061
  ${body}
8482
9062
  }
9063
+
9064
+ interface RoutePatternMap {
9065
+ ${patterns}
9066
+ }
8483
9067
  }`;
8484
9068
  }
8485
9069
 
@@ -8515,7 +9099,7 @@ import "@teyik0/furin/routes";
8515
9099
  ${routeMapDeclaration(entries)}${tagBlock}
8516
9100
  `;
8517
9101
  const typesPath = join7(projectRoot, "furin-env.d.ts");
8518
- const existing = existsSync6(typesPath) ? readFileSync3(typesPath, "utf8") : "";
9102
+ const existing = existsSync6(typesPath) ? readFileSync4(typesPath, "utf8") : "";
8519
9103
  if (content === existing) {
8520
9104
  return false;
8521
9105
  }
@@ -8582,7 +9166,7 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
8582
9166
  }).join(" ");
8583
9167
  const boundaryResult = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
8584
9168
  const pageComponentKey = JSON.stringify(`page:${resolvedPage}`);
8585
- 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} }; })`;
9169
+ 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} }; })`;
8586
9170
  const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
8587
9171
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
8588
9172
  }
@@ -8816,6 +9400,12 @@ if (__deferred && __deferred._chunks) {
8816
9400
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
8817
9401
  } as any);
8818
9402
  } else {
9403
+ // A removed active route has no match in the new development manifest.
9404
+ // Reload its document so the server can render the current 404 response.
9405
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
9406
+ window.location.reload();
9407
+ return;
9408
+ }
8819
9409
  // No match and no 404 signal \u2014 either the client bundle is out of sync
8820
9410
  // with the server (stale deploy) or the server returned something we
8821
9411
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -8892,13 +9482,16 @@ if (__deferred && __deferred._chunks) {
8892
9482
  });
8893
9483
  `;
8894
9484
  }
8895
- function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot) {
9485
+ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }, projectRoot, serverSourceVersion) {
8896
9486
  if (!existsSync7(outDir)) {
8897
9487
  mkdirSync2(outDir, { recursive: true });
8898
9488
  }
8899
- const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging);
9489
+ const serverVersion = serverSourceVersion === undefined ? "" : `
9490
+ if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};
9491
+ `;
9492
+ const hydrateCode = generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
8900
9493
  const hydratePath = join8(outDir, "_hydrate.tsx");
8901
- const existingHydrate = existsSync7(hydratePath) ? readFileSync4(hydratePath, "utf8") : "";
9494
+ const existingHydrate = existsSync7(hydratePath) ? readFileSync5(hydratePath, "utf8") : "";
8902
9495
  let changed = false;
8903
9496
  if (hydrateCode !== existingHydrate) {
8904
9497
  writeFileSync3(hydratePath, hydrateCode);
@@ -8906,7 +9499,7 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, sk
8906
9499
  }
8907
9500
  const indexHtml = generateIndexHtml();
8908
9501
  const indexPath = join8(outDir, "index.html");
8909
- const existingIndex = existsSync7(indexPath) ? readFileSync4(indexPath, "utf8") : "";
9502
+ const existingIndex = existsSync7(indexPath) ? readFileSync5(indexPath, "utf8") : "";
8910
9503
  if (indexHtml !== existingIndex) {
8911
9504
  writeFileSync3(indexPath, indexHtml);
8912
9505
  changed = true;
@@ -8919,9 +9512,65 @@ function writeDevFiles(routes, { outDir, rootLayout, basePath, clientLogging, sk
8919
9512
  }
8920
9513
  }
8921
9514
 
9515
+ // src/build/preload-manifest.ts
9516
+ init_transform_client_module();
9517
+ import { existsSync as existsSync8, readFileSync as readFileSync6, realpathSync as realpathSync3, writeFileSync as writeFileSync4 } from "fs";
9518
+ import { basename as basename2, resolve as resolve6 } from "path";
9519
+ var CLIENT_MODULE_KEY_RE = /(["'`])(__FURIN_CLIENT_MODULE_[a-z0-9]+__)\1/g;
9520
+ function routeModulePaths(route) {
9521
+ const layouts = (route.routeChain ?? []).slice(1).filter((entry) => entry.layout && entry.sourcePath).map((entry) => entry.sourcePath);
9522
+ const boundaries = (route.segmentBoundaries ?? []).flatMap((segment) => [segment.errorPath, segment.notFoundPath].filter((path) => path !== undefined));
9523
+ return [route.path, ...layouts, ...boundaries];
9524
+ }
9525
+ function realPath(path) {
9526
+ return existsSync8(path) ? realpathSync3(path) : null;
9527
+ }
9528
+ function writeClientPreloadManifest(metafile, outputPaths, entryChunkPath, routes, publicPrefix) {
9529
+ const outputs = new Map(Object.entries(metafile.outputs).map(([path, output]) => [basename2(path), output]));
9530
+ const closure = (file, seen) => {
9531
+ if (!seen.has(file)) {
9532
+ seen.add(file);
9533
+ for (const imported of outputs.get(file)?.imports ?? []) {
9534
+ if (imported.kind === "import-statement") {
9535
+ closure(basename2(imported.path), seen);
9536
+ }
9537
+ }
9538
+ }
9539
+ return seen;
9540
+ };
9541
+ const entryFiles = closure(basename2(entryChunkPath), new Set);
9542
+ const hrefsOf = (file) => [...closure(file, new Set)].filter((chunk) => !entryFiles.has(chunk)).map((chunk) => `${publicPrefix}${chunk}`);
9543
+ const chunkByModule = new Map;
9544
+ for (const [file, output] of outputs) {
9545
+ const modulePath = output.entryPoint ? realPath(resolve6(output.entryPoint)) : null;
9546
+ if (modulePath !== null) {
9547
+ chunkByModule.set(modulePath, file);
9548
+ }
9549
+ }
9550
+ const routeManifest = {};
9551
+ for (const route of routes) {
9552
+ const files = routeModulePaths(route).map((path) => chunkByModule.get(realPath(path) ?? path)).filter((file) => file !== undefined);
9553
+ routeManifest[route.pattern] = [...new Set(files.flatMap(hrefsOf))];
9554
+ }
9555
+ const moduleHrefs = new Map([...chunkByModule].map(([modulePath, file]) => [clientModuleKey(modulePath), file]));
9556
+ const modules = {};
9557
+ for (const path of outputPaths.filter((output) => output.endsWith(".js"))) {
9558
+ const code = readFileSync6(path, "utf8");
9559
+ const rewritten = code.replace(CLIENT_MODULE_KEY_RE, (_match, _quote, key) => {
9560
+ const file = moduleHrefs.get(key);
9561
+ modules[key] = file === undefined ? [] : hrefsOf(file);
9562
+ return JSON.stringify(modules[key]);
9563
+ });
9564
+ if (rewritten !== code) {
9565
+ writeFileSync4(path, rewritten);
9566
+ }
9567
+ }
9568
+ return { modules, routes: routeManifest };
9569
+ }
9570
+
8922
9571
  // src/build/client.ts
8923
9572
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8924
- var ROUTER_PROVIDER_PATH = resolve5(import.meta.dir, "../client/router/provider.tsx");
9573
+ var ROUTER_PROVIDER_PATH = resolve7(import.meta.dir, "../client/router/provider.tsx");
8925
9574
  function resolveClientModuleSpecifiers(code) {
8926
9575
  return code.replaceAll(`"@teyik0/furin/client"`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`'furin/client'`, JSON.stringify(CLIENT_MODULE_PATH)).replaceAll(`"@teyik0/furin/link"`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`'furin/link'`, JSON.stringify(LINK_MODULE_PATH)).replaceAll(`"@teyik0/furin/search"`, JSON.stringify(SEARCH_MODULE_PATH)).replaceAll(`'furin/search'`, JSON.stringify(SEARCH_MODULE_PATH));
8927
9576
  }
@@ -8929,6 +9578,7 @@ async function buildClient(routes, {
8929
9578
  outDir,
8930
9579
  rootLayout,
8931
9580
  plugins,
9581
+ preloadRouteChunks,
8932
9582
  publicPath,
8933
9583
  basePath,
8934
9584
  clientLogging,
@@ -8940,10 +9590,10 @@ async function buildClient(routes, {
8940
9590
  }) {
8941
9591
  const dirName = clientDirName ?? "client";
8942
9592
  const clientDir = join9(outDir, dirName);
8943
- if (!existsSync8(outDir)) {
9593
+ if (!existsSync9(outDir)) {
8944
9594
  mkdirSync3(outDir, { recursive: true });
8945
9595
  }
8946
- if (!existsSync8(clientDir)) {
9596
+ if (!existsSync9(clientDir)) {
8947
9597
  mkdirSync3(clientDir, { recursive: true });
8948
9598
  }
8949
9599
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
@@ -8987,6 +9637,7 @@ async function buildClient(routes, {
8987
9637
  files: hydrateEntry.files,
8988
9638
  outdir: clientDir,
8989
9639
  target: "browser",
9640
+ env: "FURIN_PUBLIC_*",
8990
9641
  format: "esm",
8991
9642
  splitting: true,
8992
9643
  optimizeImports,
@@ -8994,7 +9645,7 @@ async function buildClient(routes, {
8994
9645
  reactCompilerOutputMode: "client",
8995
9646
  minify: true,
8996
9647
  sourcemap: "none",
8997
- metafile: metafilePath !== undefined,
9648
+ metafile: true,
8998
9649
  naming: {
8999
9650
  entry: "[name]-[hash].[ext]",
9000
9651
  chunk: "[name]-[hash].[ext]"
@@ -9014,16 +9665,17 @@ async function buildClient(routes, {
9014
9665
  "@teyik0/furin/search": SEARCH_MODULE_PATH
9015
9666
  },
9016
9667
  define: {
9668
+ ...Object.fromEntries(Object.entries(process.env).filter(([name, value]) => name.startsWith("FURIN_PUBLIC_") && value !== undefined).map(([name, value]) => [`process.env.${name}`, JSON.stringify(value)])),
9017
9669
  "process.env.NODE_ENV": JSON.stringify("production")
9018
9670
  }
9019
9671
  };
9020
9672
  const result = await runBunBuild(clientBuildConfig);
9673
+ if (result.metafile === undefined) {
9674
+ throw new Error("[furin] client build did not produce the requested metafile");
9675
+ }
9021
9676
  if (metafilePath !== undefined) {
9022
- if (result.metafile === undefined) {
9023
- throw new Error("[furin] client build did not produce the requested metafile");
9024
- }
9025
- mkdirSync3(dirname7(metafilePath), { recursive: true });
9026
- writeFileSync4(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
9677
+ mkdirSync3(dirname9(metafilePath), { recursive: true });
9678
+ writeFileSync5(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
9027
9679
  `);
9028
9680
  console.log(`[furin] Client metafile: ${metafilePath}`);
9029
9681
  }
@@ -9041,10 +9693,11 @@ async function buildClient(routes, {
9041
9693
  } else {
9042
9694
  publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
9043
9695
  }
9044
- const entryChunk = `${publicPrefix}${basename2(entryOutput.path)}`;
9045
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename2(o.path)}`);
9696
+ const entryChunk = `${publicPrefix}${basename3(entryOutput.path)}`;
9697
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename3(o.path)}`);
9698
+ const preloadManifest = writeClientPreloadManifest(result.metafile, result.outputs.map((output) => output.path), entryOutput.path, preloadRouteChunks === false ? [] : routes, publicPrefix);
9046
9699
  console.log("[furin] Production client build complete");
9047
- return { entryChunk, cssChunks };
9700
+ return { entryChunk, cssChunks, preloadManifest };
9048
9701
  }
9049
9702
 
9050
9703
  // src/server/render/assemble.ts
@@ -9073,6 +9726,65 @@ async function streamToString(stream) {
9073
9726
  html += decoder.decode();
9074
9727
  return html;
9075
9728
  }
9729
+ // src/shared/sync-query.ts
9730
+ function mergeQuerySeeds(target, incoming) {
9731
+ for (const seed of incoming) {
9732
+ const index = target.findIndex((existing) => existing.url === seed.url);
9733
+ const previous = target[index];
9734
+ const bindings = [...seed.bindings ?? []];
9735
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
9736
+ for (const binding of previous.bindings ?? []) {
9737
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
9738
+ bindings.push(binding);
9739
+ }
9740
+ }
9741
+ }
9742
+ const merged = { ...seed, bindings };
9743
+ if (index < 0) {
9744
+ target.push(merged);
9745
+ } else {
9746
+ target[index] = merged;
9747
+ }
9748
+ }
9749
+ }
9750
+ function queryTagsFromData(data) {
9751
+ return (data.__furinQueries ?? []).map((seed) => queryTag(seed.identity));
9752
+ }
9753
+ var PREFIX = "__furin.query:";
9754
+ function queryTag(identity) {
9755
+ for (const [key, value] of Object.entries(identity.scope)) {
9756
+ if (value === undefined) {
9757
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
9758
+ }
9759
+ }
9760
+ return PREFIX + JSON.stringify([
9761
+ identity.id,
9762
+ Object.entries(identity.scope).sort(([a], [b]) => {
9763
+ if (a === b) {
9764
+ return 0;
9765
+ }
9766
+ return a < b ? -1 : 1;
9767
+ })
9768
+ ]);
9769
+ }
9770
+ function queryFromTag(tag) {
9771
+ if (!tag.startsWith(PREFIX)) {
9772
+ return;
9773
+ }
9774
+ try {
9775
+ const value = JSON.parse(tag.slice(PREFIX.length));
9776
+ 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"))) {
9777
+ return;
9778
+ }
9779
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
9780
+ } catch {}
9781
+ }
9782
+ function queryUrl(url, origin) {
9783
+ const parsed = new URL(url, origin);
9784
+ parsed.searchParams.sort();
9785
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
9786
+ }
9787
+
9076
9788
  // src/shared/utils/index.ts
9077
9789
  function collectRouteChainFromRoute(route) {
9078
9790
  const chain = [];
@@ -9195,8 +9907,7 @@ function setSSGCache(key, entry) {
9195
9907
  }
9196
9908
 
9197
9909
  // src/server/render/ssr.ts
9198
- import { createElement as createElement6 } from "react";
9199
- import { renderToReadableStream } from "react-dom/server";
9910
+ import { createElement as createElement7 } from "react";
9200
9911
 
9201
9912
  // ../../node_modules/.bun/seroval@1.6.7/node_modules/seroval/dist/dev/index.js
9202
9913
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
@@ -11301,6 +12012,7 @@ function fromCrossJSON(source, options) {
11301
12012
 
11302
12013
  // src/client/document.tsx
11303
12014
  import { createContext, createElement, useContext } from "react";
12015
+ import { preloadModule } from "react-dom";
11304
12016
  import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
11305
12017
  var DocumentContext = createContext(null);
11306
12018
  function serializeJson(value) {
@@ -11315,29 +12027,39 @@ function DocumentProvider({
11315
12027
  children
11316
12028
  }, undefined, false, undefined, this);
11317
12029
  }
11318
- function renderMeta(meta, index) {
12030
+ function renderMeta(meta, key) {
11319
12031
  if ("title" in meta) {
11320
12032
  return /* @__PURE__ */ jsxDEV("title", {
11321
12033
  children: meta.title
11322
- }, `title:${index}`, false, undefined, this);
12034
+ }, key, false, undefined, this);
11323
12035
  }
11324
12036
  if ("script:ld+json" in meta) {
11325
12037
  return /* @__PURE__ */ jsxDEV("script", {
11326
12038
  dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
11327
12039
  type: "application/ld+json"
11328
- }, `json-ld:${index}`, false, undefined, this);
12040
+ }, key, false, undefined, this);
11329
12041
  }
11330
12042
  if ("tagName" in meta) {
11331
12043
  const { tagName, ...attributes } = meta;
11332
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
12044
+ return createElement(tagName, { ...attributes, key });
11333
12045
  }
11334
- return createElement("meta", { ...meta, key: `meta:${index}` });
12046
+ return createElement("meta", { ...meta, key });
11335
12047
  }
11336
12048
  function HeadContent() {
11337
12049
  const state = useContext(DocumentContext);
11338
12050
  if (state === null) {
11339
12051
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
11340
12052
  }
12053
+ for (const href of state.assets.modulePreloads ?? []) {
12054
+ preloadModule(href, { as: "script", nonce: state.nonce });
12055
+ }
12056
+ const occurrences = new Map;
12057
+ const descriptorKey = (descriptor) => {
12058
+ const identity = JSON.stringify(descriptor);
12059
+ const occurrence = occurrences.get(identity) ?? 0;
12060
+ occurrences.set(identity, occurrence + 1);
12061
+ return `${identity}:${occurrence}`;
12062
+ };
11341
12063
  return /* @__PURE__ */ jsxDEV(Fragment, {
11342
12064
  children: [
11343
12065
  state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
@@ -11370,20 +12092,20 @@ function HeadContent() {
11370
12092
  href,
11371
12093
  rel: "stylesheet"
11372
12094
  }, href, false, undefined, this)),
11373
- state.head?.meta?.map(renderMeta),
11374
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV("link", {
12095
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
12096
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV("link", {
11375
12097
  ...link
11376
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
11377
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV("script", {
12098
+ }, descriptorKey(link), false, undefined, this)),
12099
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV("script", {
11378
12100
  ...attributes,
11379
- dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children },
11380
- nonce: state.nonce ?? attributes.nonce
11381
- }, `script:${index}`, false, undefined, this)),
11382
- state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV("style", {
12101
+ nonce: state.nonce ?? attributes.nonce,
12102
+ children
12103
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
12104
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV("style", {
11383
12105
  dangerouslySetInnerHTML: { __html: children },
11384
12106
  nonce: state.nonce,
11385
12107
  type
11386
- }, `style:${index}`, false, undefined, this))
12108
+ }, descriptorKey({ children, type }), false, undefined, this))
11387
12109
  ]
11388
12110
  }, undefined, true, undefined, this);
11389
12111
  }
@@ -11452,7 +12174,7 @@ function FurinDocumentFallback({ children }) {
11452
12174
  }
11453
12175
 
11454
12176
  // src/client/router/context.ts
11455
- import { createContext as createContext2, useContext as useContext2 } from "react";
12177
+ import { createContext as createContext2, useCallback, useContext as useContext2, useMemo } from "react";
11456
12178
 
11457
12179
  // src/client/router/link-utils.ts
11458
12180
  function navigationHrefPolicy(href, currentOrigin) {
@@ -11542,7 +12264,7 @@ var CLIENT_FALLBACK_ROUTER = {
11542
12264
  search: {},
11543
12265
  searchRoutes: []
11544
12266
  };
11545
- function useRouter() {
12267
+ function useRouterContext() {
11546
12268
  const ctx = useContext2(RouterContext);
11547
12269
  return ctx ?? CLIENT_FALLBACK_ROUTER;
11548
12270
  }
@@ -11550,7 +12272,7 @@ function useRouter() {
11550
12272
  // src/client/router/search-store.ts
11551
12273
  import { createContext as createContext3 } from "react";
11552
12274
  function searchSnapshotChanged(a, b) {
11553
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
12275
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
11554
12276
  }
11555
12277
  function createSearchStore(initialSnapshot) {
11556
12278
  let snapshot = initialSnapshot;
@@ -11587,6 +12309,7 @@ function createSearchStore(initialSnapshot) {
11587
12309
  function searchSnapshotFromRouterContext(context) {
11588
12310
  return {
11589
12311
  currentHref: context.currentHref,
12312
+ currentPattern: context.currentPattern,
11590
12313
  navigate: context.navigate,
11591
12314
  search: context.search,
11592
12315
  searchRoutes: context.searchRoutes
@@ -11594,6 +12317,7 @@ function searchSnapshotFromRouterContext(context) {
11594
12317
  }
11595
12318
  var FALLBACK_SEARCH_STORE = createSearchStore({
11596
12319
  currentHref: "/",
12320
+ currentPattern: undefined,
11597
12321
  navigate: (href, _opts) => {
11598
12322
  if (typeof window !== "undefined") {
11599
12323
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -11871,9 +12595,292 @@ function serializeRouteFrames(data, deferredKeys) {
11871
12595
  // src/server/render/ssr.ts
11872
12596
  init_context_logger();
11873
12597
  init_instance();
11874
-
11875
12598
  // src/server/render/document.tsx
11876
12599
  import { createElement as createElement3 } from "react";
12600
+
12601
+ // src/client/query.tsx
12602
+ import {
12603
+ createContext as createContext4,
12604
+ useCallback as useCallback2,
12605
+ useContext as useContext3,
12606
+ useEffect,
12607
+ useSyncExternalStore
12608
+ } from "react";
12609
+
12610
+ // src/client/query-store.ts
12611
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
12612
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
12613
+ var environmentGlobal = globalThis;
12614
+ function setServerQueryEnvironment(read) {
12615
+ environmentGlobal[SERVER_ENVIRONMENT] = read;
12616
+ }
12617
+ function currentQueryEnvironment() {
12618
+ return environmentGlobal[SERVER_ENVIRONMENT]?.();
12619
+ }
12620
+ class QueryStore {
12621
+ entries = new Map;
12622
+ listeners = new Set;
12623
+ revisionValue = 0;
12624
+ projections = new Set;
12625
+ session;
12626
+ epoch = 0;
12627
+ origin;
12628
+ constructor(origin) {
12629
+ this.origin = origin;
12630
+ }
12631
+ key(url) {
12632
+ const absolute = new URL(url, this.origin).href;
12633
+ return queryUrl(absolute, undefined);
12634
+ }
12635
+ entry(url) {
12636
+ const key = this.key(url);
12637
+ let entry = this.entries.get(key);
12638
+ if (!entry) {
12639
+ entry = {
12640
+ base: undefined,
12641
+ listeners: new Set,
12642
+ snapshot: { data: undefined, error: null, isFetching: false },
12643
+ stale: true,
12644
+ version: 0
12645
+ };
12646
+ this.entries.set(key, entry);
12647
+ }
12648
+ return entry;
12649
+ }
12650
+ publish(entry) {
12651
+ let data = entry.base;
12652
+ for (const projection of this.projections) {
12653
+ const transform = projection.transforms.get(entry);
12654
+ if (transform && data !== undefined) {
12655
+ data = transform(data);
12656
+ }
12657
+ }
12658
+ entry.snapshot = { ...entry.snapshot, data };
12659
+ for (const listener of entry.listeners) {
12660
+ listener();
12661
+ }
12662
+ this.revisionValue += 1;
12663
+ for (const listener of this.listeners) {
12664
+ listener();
12665
+ }
12666
+ }
12667
+ revision = () => this.revisionValue;
12668
+ subscribeAll = (listener) => {
12669
+ this.listeners.add(listener);
12670
+ return () => this.listeners.delete(listener);
12671
+ };
12672
+ observe(url, result, epoch, version) {
12673
+ const existing = this.entries.get(this.key(url));
12674
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
12675
+ return;
12676
+ }
12677
+ const header = result.response?.headers.get("x-furin-query");
12678
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
12679
+ if (identity) {
12680
+ this.setSession(identity.session);
12681
+ }
12682
+ const entry = this.entry(url);
12683
+ entry.base = result.data;
12684
+ entry.version += 1;
12685
+ entry.identity = identity;
12686
+ entry.local = result.local ?? result.response?.url === "";
12687
+ entry.stale = false;
12688
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
12689
+ for (const projection of this.projections) {
12690
+ if (!projection.pending) {
12691
+ projection.transforms.delete(entry);
12692
+ if (projection.transforms.size === 0) {
12693
+ this.projections.delete(projection);
12694
+ projection.onRemove?.();
12695
+ }
12696
+ }
12697
+ }
12698
+ this.publish(entry);
12699
+ if (this.entries.size > 100) {
12700
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
12701
+ if (oldest) {
12702
+ this.entries.delete(oldest[0]);
12703
+ }
12704
+ }
12705
+ }
12706
+ setSession(session) {
12707
+ if (this.session !== undefined && this.session !== session) {
12708
+ this.epoch += 1;
12709
+ for (const projection of this.projections) {
12710
+ projection.onRemove?.();
12711
+ }
12712
+ this.projections.clear();
12713
+ for (const entry of this.entries.values()) {
12714
+ entry.base = undefined;
12715
+ entry.identity = undefined;
12716
+ entry.stale = true;
12717
+ entry.version += 1;
12718
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12719
+ this.publish(entry);
12720
+ }
12721
+ }
12722
+ this.session = session;
12723
+ }
12724
+ generation() {
12725
+ return this.epoch;
12726
+ }
12727
+ version(url) {
12728
+ return this.entry(url).version;
12729
+ }
12730
+ snapshot(url) {
12731
+ return this.entry(url).snapshot;
12732
+ }
12733
+ subscribe(url, listener) {
12734
+ const entry = this.entry(url);
12735
+ entry.listeners.add(listener);
12736
+ return () => entry.listeners.delete(listener);
12737
+ }
12738
+ bind(url, load, client) {
12739
+ const entry = this.entry(url);
12740
+ if (client && entry.client && client !== entry.client) {
12741
+ entry.base = undefined;
12742
+ entry.identity = undefined;
12743
+ entry.stale = true;
12744
+ entry.version += 1;
12745
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12746
+ for (const projection of this.projections) {
12747
+ projection.transforms.delete(entry);
12748
+ }
12749
+ }
12750
+ entry.client = client ?? entry.client;
12751
+ entry.load = load;
12752
+ }
12753
+ pending(entry) {
12754
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
12755
+ }
12756
+ fetch(url) {
12757
+ const entry = this.entry(url);
12758
+ if (entry.promise) {
12759
+ return entry.promise;
12760
+ }
12761
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
12762
+ return Promise.resolve();
12763
+ }
12764
+ const { version } = entry;
12765
+ const { epoch } = this;
12766
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
12767
+ this.publish(entry);
12768
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
12769
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
12770
+ return;
12771
+ }
12772
+ if (result.error === null) {
12773
+ this.observe(url, result, epoch);
12774
+ } else {
12775
+ entry.snapshot = { ...entry.snapshot, error: result.error };
12776
+ }
12777
+ }).catch((error) => {
12778
+ if (epoch === this.epoch && version === entry.version) {
12779
+ entry.snapshot = { ...entry.snapshot, error };
12780
+ }
12781
+ }).finally(() => {
12782
+ entry.promise = undefined;
12783
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
12784
+ this.publish(entry);
12785
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
12786
+ this.fetch(url);
12787
+ }
12788
+ });
12789
+ return entry.promise;
12790
+ }
12791
+ invalidate(identities) {
12792
+ const tags = new Set(identities.map(queryTag));
12793
+ let affected = false;
12794
+ for (const [url, entry] of this.entries) {
12795
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
12796
+ affected = true;
12797
+ this.invalidateEntry(url, entry);
12798
+ }
12799
+ }
12800
+ return affected;
12801
+ }
12802
+ invalidateEntry(url, entry) {
12803
+ entry.stale = true;
12804
+ entry.version += 1;
12805
+ if (entry.listeners.size > 0) {
12806
+ this.fetch(url);
12807
+ }
12808
+ }
12809
+ invalidateAll() {
12810
+ for (const [url, entry] of this.entries) {
12811
+ this.invalidateEntry(url, entry);
12812
+ }
12813
+ }
12814
+ begin() {
12815
+ return { pending: true, transforms: new Map };
12816
+ }
12817
+ update(projection, url, transform) {
12818
+ const entry = this.entries.get(this.key(url));
12819
+ if (!entry || entry.base === undefined) {
12820
+ return;
12821
+ }
12822
+ const previous = projection.transforms.get(entry);
12823
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
12824
+ entry.version += 1;
12825
+ this.projections.add(projection);
12826
+ this.publish(entry);
12827
+ }
12828
+ finish(projection, outcome) {
12829
+ projection.pending = false;
12830
+ const entries = [...projection.transforms.keys()];
12831
+ if (outcome === "error") {
12832
+ this.projections.delete(projection);
12833
+ projection.onRemove?.();
12834
+ }
12835
+ for (const entry of entries) {
12836
+ this.publish(entry);
12837
+ if (outcome !== "error") {
12838
+ entry.stale = true;
12839
+ }
12840
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
12841
+ if (url && entry.stale) {
12842
+ this.fetch(url);
12843
+ }
12844
+ }
12845
+ }
12846
+ dehydrate() {
12847
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
12848
+ }
12849
+ seedUrl(seed, localOrigin) {
12850
+ const original = new URL(seed.url, this.origin);
12851
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
12852
+ }
12853
+ captureHydration() {
12854
+ const { epoch } = this;
12855
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
12856
+ return (seeds, localOrigin) => {
12857
+ if (epoch === this.epoch) {
12858
+ this.hydrate(seeds.filter((seed) => {
12859
+ const url = this.seedUrl(seed, localOrigin);
12860
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
12861
+ }), localOrigin);
12862
+ }
12863
+ };
12864
+ }
12865
+ hydrate(seeds, localOrigin) {
12866
+ for (const seed of seeds) {
12867
+ const url = this.seedUrl(seed, localOrigin);
12868
+ this.observe(url, {
12869
+ data: seed.data,
12870
+ error: null,
12871
+ identity: seed.identity,
12872
+ local: seed.local ?? false
12873
+ }, this.epoch);
12874
+ }
12875
+ }
12876
+ }
12877
+
12878
+ // src/client/query.tsx
12879
+ var QUERY_CONTEXT = Symbol.for("furin.query.context.v1");
12880
+ var contextGlobal = globalThis;
12881
+ var QueryStoreContext = contextGlobal[QUERY_CONTEXT] ??= createContext4(null);
12882
+
12883
+ // src/server/render/document.tsx
11877
12884
  init_instance();
11878
12885
  init_config();
11879
12886
  function withDocumentState(element, assets, head, data, nonce) {
@@ -11892,11 +12899,13 @@ function withDocumentState(element, assets, head, data, nonce) {
11892
12899
  routeFrames,
11893
12900
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
11894
12901
  };
11895
- return createElement3(DocumentProvider, { value: state }, element);
12902
+ const queries = new QueryStore(undefined);
12903
+ queries.hydrate(data?.__furinQueries ?? []);
12904
+ return createElement3(DocumentProvider, { value: state }, createElement3(QueryStoreContext.Provider, { value: queries }, element));
11896
12905
  }
11897
12906
 
11898
12907
  // src/server/render/element.tsx
11899
- import { createElement as createElement5 } from "react";
12908
+ import { createElement as createElement6 } from "react";
11900
12909
 
11901
12910
  // src/client/boundaries.tsx
11902
12911
  import { Component, Fragment as Fragment2 } from "react";
@@ -11926,7 +12935,57 @@ function isNotFoundError(err) {
11926
12935
  }
11927
12936
 
11928
12937
  // src/client/link.tsx
11929
- import { createElement as createElement4, useCallback, useEffect, useRef } from "react";
12938
+ import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef } from "react";
12939
+
12940
+ // src/shared/page-key.ts
12941
+ function identityValue(value) {
12942
+ return Object.is(value, -0) ? "-0" : String(value);
12943
+ }
12944
+ function pageKey(pattern, data, remountDeps) {
12945
+ const { params, query } = data;
12946
+ if (remountDeps) {
12947
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
12948
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
12949
+ }
12950
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
12951
+ if (left < right) {
12952
+ return -1;
12953
+ }
12954
+ return left > right ? 1 : 0;
12955
+ });
12956
+ return JSON.stringify([
12957
+ pattern,
12958
+ entries.map(([name, value]) => [
12959
+ name,
12960
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
12961
+ ])
12962
+ ]);
12963
+ }
12964
+
12965
+ // src/client/route-api.tsx
12966
+ import { createContext as createContext5, createElement as createElement4, useContext as useContext4 } from "react";
12967
+ var RESERVED_RENDER_KEYS = new Set([
12968
+ "catch",
12969
+ "children",
12970
+ "finally",
12971
+ "key",
12972
+ "ref",
12973
+ "then",
12974
+ "toJSON"
12975
+ ]);
12976
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
12977
+ var contextGlobal2 = globalThis;
12978
+ var RouteContext = contextGlobal2[ROUTE_CONTEXT] ??= createContext5(null);
12979
+ function withRouteSnapshot(element, pattern, props) {
12980
+ const {
12981
+ params,
12982
+ path: _path,
12983
+ query: _query,
12984
+ ...data
12985
+ } = props;
12986
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
12987
+ return createElement4(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
12988
+ }
11930
12989
 
11931
12990
  // src/client/server-error.ts
11932
12991
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
@@ -11944,6 +13003,96 @@ class FurinServerError extends Error {
11944
13003
  function isFurinServerError(err) {
11945
13004
  return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
11946
13005
  }
13006
+
13007
+ // src/shared/query-bindings.ts
13008
+ function isContainer(value) {
13009
+ if (!value || typeof value !== "object") {
13010
+ return false;
13011
+ }
13012
+ const prototype = Object.getPrototypeOf(value);
13013
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
13014
+ }
13015
+ function bindQueryData(data, seeds) {
13016
+ return seeds.map((seed) => {
13017
+ const sources = new WeakMap;
13018
+ const index = (value, path) => {
13019
+ if (!isContainer(value) || sources.has(value)) {
13020
+ return;
13021
+ }
13022
+ sources.set(value, path);
13023
+ if (!Array.isArray(value)) {
13024
+ for (const [key, child] of Object.entries(value)) {
13025
+ index(child, [...path, key]);
13026
+ }
13027
+ }
13028
+ };
13029
+ index(seed.data, []);
13030
+ const bindings = [];
13031
+ const visiting = new WeakSet;
13032
+ const visit = (value, target) => {
13033
+ if (!isContainer(value) || visiting.has(value)) {
13034
+ return;
13035
+ }
13036
+ const source = sources.get(value);
13037
+ if (source) {
13038
+ bindings.push({ source, target });
13039
+ return;
13040
+ }
13041
+ visiting.add(value);
13042
+ for (const [key, child] of Object.entries(value)) {
13043
+ visit(child, [...target, key]);
13044
+ }
13045
+ visiting.delete(value);
13046
+ };
13047
+ visit(data, []);
13048
+ return { ...seed, bindings };
13049
+ });
13050
+ }
13051
+ function replace(value, path, next) {
13052
+ const [key, ...rest] = path;
13053
+ if (key === undefined) {
13054
+ return next;
13055
+ }
13056
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
13057
+ return value;
13058
+ }
13059
+ const child = replace(value[key], rest, next);
13060
+ if (child === value[key]) {
13061
+ return value;
13062
+ }
13063
+ const copy = Array.isArray(value) ? [...value] : { ...value };
13064
+ Object.defineProperty(copy, key, {
13065
+ configurable: true,
13066
+ enumerable: true,
13067
+ value: child,
13068
+ writable: true
13069
+ });
13070
+ return copy;
13071
+ }
13072
+ function isDeferredTarget(data, target) {
13073
+ const [key] = target;
13074
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
13075
+ }
13076
+ function projectQueryData(data, seeds, read) {
13077
+ let projected = data;
13078
+ for (const seed of seeds) {
13079
+ const snapshot = read(seed);
13080
+ if (snapshot === undefined) {
13081
+ continue;
13082
+ }
13083
+ for (const binding of seed.bindings ?? []) {
13084
+ if (isDeferredTarget(data, binding.target)) {
13085
+ continue;
13086
+ }
13087
+ let value = snapshot;
13088
+ for (const key of binding.source) {
13089
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
13090
+ }
13091
+ projected = replace(projected, binding.target, value);
13092
+ }
13093
+ }
13094
+ return projected;
13095
+ }
11947
13096
  // src/client/link.tsx
11948
13097
  function computeLinkView({
11949
13098
  to,
@@ -11993,7 +13142,7 @@ function LinkInteractive({
11993
13142
  href: _href,
11994
13143
  ...anchorProps
11995
13144
  }) {
11996
- const router2 = useRouter();
13145
+ const router2 = useRouterContext();
11997
13146
  const anchorRef = useRef(null);
11998
13147
  const intentTimerRef = useRef(null);
11999
13148
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -12001,15 +13150,15 @@ function LinkInteractive({
12001
13150
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
12002
13151
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
12003
13152
  const { prefetch } = router2;
12004
- const triggerPrefetch = useCallback(() => {
13153
+ const triggerPrefetch = useCallback3(() => {
12005
13154
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
12006
13155
  }, [prefetch, logicalHref, effectiveStaleTime]);
12007
- useEffect(() => {
13156
+ useEffect2(() => {
12008
13157
  if (effectivePreload === "render") {
12009
13158
  triggerPrefetch();
12010
13159
  }
12011
13160
  }, [effectivePreload, triggerPrefetch]);
12012
- useEffect(() => {
13161
+ useEffect2(() => {
12013
13162
  if (effectivePreload !== "viewport" || !anchorRef.current) {
12014
13163
  return;
12015
13164
  }
@@ -12022,7 +13171,7 @@ function LinkInteractive({
12022
13171
  observer.observe(anchorRef.current);
12023
13172
  return () => observer.disconnect();
12024
13173
  }, [effectivePreload, triggerPrefetch]);
12025
- useEffect(() => () => {
13174
+ useEffect2(() => () => {
12026
13175
  if (intentTimerRef.current !== null) {
12027
13176
  clearTimeout(intentTimerRef.current);
12028
13177
  intentTimerRef.current = null;
@@ -12076,7 +13225,7 @@ function LinkInteractive({
12076
13225
  triggerPrefetch();
12077
13226
  }
12078
13227
  };
12079
- return createElement4("a", {
13228
+ return createElement5("a", {
12080
13229
  "data-furin-link": true,
12081
13230
  href,
12082
13231
  onClick: handleClick,
@@ -12127,7 +13276,7 @@ function renderLinkElement(props, router2) {
12127
13276
  href: _href,
12128
13277
  ...anchorProps
12129
13278
  } = props;
12130
- return createElement4("a", {
13279
+ return createElement5("a", {
12131
13280
  "data-furin-link": true,
12132
13281
  href,
12133
13282
  ...isActive ? { "data-status": "active" } : {},
@@ -12138,11 +13287,11 @@ function renderLinkElement(props, router2) {
12138
13287
  }
12139
13288
  function Link(props) {
12140
13289
  if (typeof window === "undefined") {
12141
- return createElement4(RouterContext.Consumer, {
13290
+ return createElement5(RouterContext.Consumer, {
12142
13291
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
12143
13292
  });
12144
13293
  }
12145
- return createElement4(LinkInteractive, props);
13294
+ return createElement5(LinkInteractive, props);
12146
13295
  }
12147
13296
 
12148
13297
  // src/client/default-screens.tsx
@@ -12548,7 +13697,10 @@ function wrapSegmentBoundaries(inner, segment, options) {
12548
13697
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
12549
13698
  function buildElement(route, data, rootLayout) {
12550
13699
  const Component = route.page.component;
12551
- let element = createElement5(Component, data);
13700
+ let element = createElement6(Component, {
13701
+ ...data,
13702
+ key: pageKey(route.pattern, data, route.page._route.remountDeps)
13703
+ });
12552
13704
  const byDepth = new Map;
12553
13705
  const legacyRoute = route;
12554
13706
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
@@ -12559,22 +13711,22 @@ function buildElement(route, data, rootLayout) {
12559
13711
  const routeEntry = route.routeChain[i];
12560
13712
  if (routeEntry?.layout) {
12561
13713
  const Layout = routeEntry.layout;
12562
- element = createElement5(Layout, data, element);
13714
+ element = createElement6(Layout, data, element);
12563
13715
  }
12564
13716
  }
12565
13717
  element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
12566
13718
  if (rootLayout.layout) {
12567
13719
  const RootLayoutComponent = rootLayout.layout;
12568
- element = createElement5(RootLayoutComponent, data, element);
13720
+ element = createElement6(RootLayoutComponent, data, element);
12569
13721
  }
12570
- return element;
13722
+ return withRouteSnapshot(element, route.pattern, data);
12571
13723
  }
12572
13724
  function wrapRootLayout(element, data, rootLayout) {
12573
13725
  if (!rootLayout.layout) {
12574
13726
  return element;
12575
13727
  }
12576
13728
  const RootLayoutComponent = rootLayout.layout;
12577
- return createElement5(RootLayoutComponent, data, element);
13729
+ return createElement6(RootLayoutComponent, data, element);
12578
13730
  }
12579
13731
  function buildNotFoundElement(component, error) {
12580
13732
  const NotFound = component ?? DefaultNotFoundFallback;
@@ -12614,12 +13766,6 @@ function buildErrorElement(component, error, digest, messageOverride, status) {
12614
13766
  }, undefined, false, undefined, this);
12615
13767
  }
12616
13768
 
12617
- // src/client.ts
12618
- var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
12619
- function isDeferred(value) {
12620
- return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
12621
- }
12622
-
12623
13769
  // src/rsc/render-error.ts
12624
13770
  var INTERNAL_STACK_FRAMES = new Set([
12625
13771
  "<anonymous>",
@@ -12683,17 +13829,88 @@ function isFurinRscRenderError(error) {
12683
13829
  return error instanceof FurinRscRenderError || typeof error === "object" && error !== null && error.code === "FURIN_RSC_RENDER_ERROR";
12684
13830
  }
12685
13831
 
13832
+ // src/shared/defer.ts
13833
+ var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
13834
+ function isDeferred(value) {
13835
+ return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
13836
+ }
13837
+
12686
13838
  // src/server/render/loaders.ts
12687
13839
  init_context_logger();
12688
13840
  init_instrumentation();
12689
13841
  init_patterns();
12690
13842
 
13843
+ // src/server/sync/query-context.ts
13844
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
13845
+ init_registry();
13846
+ init_instance();
13847
+ var QUERY_CONTEXT2 = Symbol.for("furin.query.server-context.v1");
13848
+ var contextGlobal3 = globalThis;
13849
+ var contexts = contextGlobal3[QUERY_CONTEXT2] ??= new AsyncLocalStorage6;
13850
+ setServerQueryEnvironment(() => contexts.getStore());
13851
+ var trackedQueryPaths = instanceSlot(() => new Set);
13852
+ var deferredQueries = new WeakMap;
13853
+ function deferredQuerySeeds(promise) {
13854
+ return deferredQueries.get(promise);
13855
+ }
13856
+ function captureQueryReads(ctx, run, owner) {
13857
+ const { origin } = new URL(ctx.request.url);
13858
+ const store = new QueryStore(origin);
13859
+ const registry = getAutoInvalidateRegistry();
13860
+ const trackedPaths = trackedQueryPaths();
13861
+ const requestUrl = new URL(ctx.request.url);
13862
+ const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
13863
+ const onRead = () => {
13864
+ const seeds = store.dehydrate();
13865
+ registry.registerLoaderTags(path, seeds.map((seed) => queryTag(seed.identity)), owner ?? "eden-queries");
13866
+ trackedPaths.delete(path);
13867
+ if (seeds.length > 0) {
13868
+ trackedPaths.add(path);
13869
+ }
13870
+ if (trackedPaths.size > 1000) {
13871
+ const oldest = trackedPaths.values().next().value;
13872
+ if (oldest !== undefined) {
13873
+ trackedPaths.delete(oldest);
13874
+ registry.unregisterPath(oldest, "eden-queries");
13875
+ registry.unregisterPath(oldest, "eden-request-queries");
13876
+ }
13877
+ }
13878
+ };
13879
+ return contexts.run({ origin, store, onRead }, async () => {
13880
+ const result = { ...await run() };
13881
+ const seeds = store.dehydrate();
13882
+ if (result.type === "data" && seeds.length > 0) {
13883
+ const captured = [...result.syncData.__furinQueries ?? []];
13884
+ mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
13885
+ result.syncData = { ...result.syncData, __furinQueries: captured };
13886
+ }
13887
+ if (result.type === "data" && result.deferredPromises) {
13888
+ for (const [key, promise] of Object.entries(result.deferredPromises)) {
13889
+ promise.then((value) => {
13890
+ const completed = store.dehydrate();
13891
+ if (completed.length > 0) {
13892
+ const captured = deferredQueries.get(promise) ?? [];
13893
+ mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
13894
+ deferredQueries.set(promise, captured);
13895
+ }
13896
+ }).catch(() => {
13897
+ return;
13898
+ });
13899
+ }
13900
+ }
13901
+ return result;
13902
+ });
13903
+ }
13904
+
12691
13905
  // src/server/render/mixed-cache.ts
12692
13906
  init_registry();
12693
13907
  init_registry2();
12694
13908
  init_context_logger();
12695
13909
  init_instance();
12696
13910
  init_source_version();
13911
+ function capturedQueryTags() {
13912
+ return currentQueryEnvironment()?.store.dehydrate().map((seed) => queryTag(seed.identity)) ?? [];
13913
+ }
12697
13914
  var mixedCacheKey = Symbol("furin-mixed-loader-cache");
12698
13915
  function cachePathWithSearch(key) {
12699
13916
  const separator = key.indexOf("|");
@@ -12746,7 +13963,11 @@ async function readCachedSegment(entry, revalidate, parentData) {
12746
13963
  return;
12747
13964
  }
12748
13965
  }
12749
- return fromCrossJSON(snapshot.data, {});
13966
+ const environment = currentQueryEnvironment();
13967
+ environment?.store.hydrate(snapshot.queries ?? []);
13968
+ environment?.onRead();
13969
+ const data = fromCrossJSON(snapshot.data, {});
13970
+ return projectQueryData(data, snapshot.queries ?? [], (seed) => seed.data);
12750
13971
  } catch {
12751
13972
  getLogger().warn("Mixed loader cache entry is invalid; loading fresh data");
12752
13973
  }
@@ -12759,7 +13980,8 @@ async function createSegmentSnapshot(data, parentData, parentFieldsRead) {
12759
13980
  })));
12760
13981
  return JSON.stringify({
12761
13982
  data: await toCrossJSONAsync(data),
12762
- dependencies
13983
+ dependencies,
13984
+ queries: bindQueryData(data, currentQueryEnvironment()?.store.dehydrate() ?? []).filter((seed) => (seed.bindings?.length ?? 0) > 0)
12763
13985
  });
12764
13986
  }
12765
13987
  async function acquireSharedSegment(shared, identity) {
@@ -12786,6 +14008,10 @@ async function readSharedSegment(shared, identity, revalidate, parentData) {
12786
14008
  }
12787
14009
  }
12788
14010
  async function commitSharedSegment(shared, identity, lease, cached, revalidate) {
14011
+ const identityTags = new Set(identity.tags);
14012
+ if (capturedQueryTags().some((tag) => !identityTags.has(tag))) {
14013
+ return;
14014
+ }
12789
14015
  try {
12790
14016
  await shared.commit({
12791
14017
  entry: {
@@ -12813,6 +14039,7 @@ function storeLocalSegment(state, generation, key, path, tags, cached) {
12813
14039
  }
12814
14040
  async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, parentFieldsRead, run) {
12815
14041
  const instance = currentInstance();
14042
+ const declaredTags = route.tags ?? [];
12816
14043
  const mode = segment.mode ?? route.mode;
12817
14044
  const revalidate = mode === "isr" ? segment.revalidate ?? 60 : Number.POSITIVE_INFINITY;
12818
14045
  const requestUrl = new URL(ctx.request.url);
@@ -12833,7 +14060,12 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12833
14060
  mode: mode === "isr" ? "isr" : "ssg",
12834
14061
  path,
12835
14062
  scope: instance.prefix,
12836
- tags: route.tags ?? []
14063
+ tags: [
14064
+ ...new Set([
14065
+ ...declaredTags,
14066
+ ...getAutoInvalidateRegistry().tagsForPath(`${path}${requestUrl.search}`)
14067
+ ])
14068
+ ]
12837
14069
  };
12838
14070
  const stored = shared === undefined ? undefined : await readSharedSegment(shared, identity, revalidate, parentData);
12839
14071
  if (stored !== undefined) {
@@ -12849,7 +14081,7 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12849
14081
  cachedAt: Date.now(),
12850
14082
  payload: await createSegmentSnapshot(data, parentData, parentFieldsRead)
12851
14083
  };
12852
- storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, route.tags, cached);
14084
+ storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, [...declaredTags, ...capturedQueryTags()], cached);
12853
14085
  if (shared !== undefined && lease !== null) {
12854
14086
  await commitSharedSegment(shared, identity, lease, cached, revalidate);
12855
14087
  }
@@ -12884,6 +14116,12 @@ function assertPublicLoaderKey(key) {
12884
14116
  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.`);
12885
14117
  }
12886
14118
  }
14119
+ function assertRequestLoaderKey(key, ctx) {
14120
+ assertPublicLoaderKey(key);
14121
+ if (key === "log" || Object.hasOwn(ctx, key) || key in ctx && !Object.hasOwn(Object.prototype, key)) {
14122
+ throw new Error(`[furin] requestLoader data key "${key}" is reserved: it is overwritten by the SSR loader context. Rename this field to avoid conflicts.`);
14123
+ }
14124
+ }
12887
14125
  function isHttpRedirect(res) {
12888
14126
  return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
12889
14127
  }
@@ -12898,7 +14136,7 @@ async function readResponseMessage(res) {
12898
14136
  return res.statusText;
12899
14137
  }
12900
14138
  }
12901
- function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
14139
+ function createLoaderCtx(ctx, accumulatedParentPromise, inheritedRequestFields, onParentFieldAccess) {
12902
14140
  const cache = new Map;
12903
14141
  return new Proxy(ctx, {
12904
14142
  get(target, prop) {
@@ -12911,6 +14149,9 @@ function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
12911
14149
  if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
12912
14150
  return target[prop];
12913
14151
  }
14152
+ if (inheritedRequestFields && Object.hasOwn(inheritedRequestFields, prop)) {
14153
+ return inheritedRequestFields[prop];
14154
+ }
12914
14155
  onParentFieldAccess?.(prop);
12915
14156
  let entry = cache.get(prop);
12916
14157
  if (!entry) {
@@ -13023,6 +14264,8 @@ function runRequestLoaderFields(route, ctx) {
13023
14264
  if (declarations?.length !== route.routeChain.length) {
13024
14265
  throw new Error(`[furin] Missing per-loader request field metadata for ${route.pattern}.`);
13025
14266
  }
14267
+ const declaredKeys = declarations.map((keys) => new Set(keys));
14268
+ const requestKeys = new Set(route.requestKeys);
13026
14269
  const requestContext = createRequestLoaderContext(ctx);
13027
14270
  const results = loaderIndexes.map((index) => {
13028
14271
  const loader = route.routeChain[index]?.requestLoader;
@@ -13033,8 +14276,8 @@ function runRequestLoaderFields(route, ctx) {
13033
14276
  const result = observeLoader(() => invocation, `request:${index}`, ctx.path).then((value) => {
13034
14277
  const data = value;
13035
14278
  for (const key of Object.keys(data)) {
13036
- assertPublicLoaderKey(key);
13037
- if (!declarations[index]?.includes(key)) {
14279
+ assertRequestLoaderKey(key, ctx);
14280
+ if (!declaredKeys[index]?.has(key)) {
13038
14281
  throw new Error(`[furin] requestLoader in ${route.pattern} returned undeclared field "${key}".`);
13039
14282
  }
13040
14283
  }
@@ -13043,27 +14286,36 @@ function runRequestLoaderFields(route, ctx) {
13043
14286
  result.catch(() => {});
13044
14287
  return { index, result };
13045
14288
  });
13046
- const fields = {};
14289
+ let fields = {};
14290
+ const fieldsByLoader = route.routeChain.map((_, boundaryIndex) => {
14291
+ fields = { ...fields };
14292
+ for (const key of declarations[boundaryIndex] ?? []) {
14293
+ if (!requestKeys.has(key)) {
14294
+ continue;
14295
+ }
14296
+ const candidates = results.filter(({ index }) => index <= boundaryIndex && declaredKeys[index]?.has(key));
14297
+ fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
14298
+ for (let index = values.length - 1;index >= 0; index -= 1) {
14299
+ const data = values[index];
14300
+ if (data && Object.hasOwn(data, key)) {
14301
+ return data[key];
14302
+ }
14303
+ }
14304
+ });
14305
+ fields[key].catch(() => {});
14306
+ }
14307
+ return fields;
14308
+ });
13047
14309
  for (const key of route.requestKeys) {
13048
- const candidates = results.filter(({ index }) => declarations[index]?.includes(key));
13049
- if (candidates.length === 0) {
14310
+ if (!Object.hasOwn(fields, key)) {
13050
14311
  throw new Error(`[furin] No requestLoader declares field "${key}" in ${route.pattern}.`);
13051
14312
  }
13052
- fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
13053
- for (let index = values.length - 1;index >= 0; index -= 1) {
13054
- const data = values[index];
13055
- if (data && Object.hasOwn(data, key)) {
13056
- return data[key];
13057
- }
13058
- }
13059
- });
13060
- fields[key].catch(() => {});
13061
14313
  }
13062
14314
  const noFieldCompletion = Promise.all(results.filter(({ index }) => declarations[index]?.length === 0).map(({ result }) => result)).then(() => {
13063
14315
  return;
13064
14316
  });
13065
14317
  noFieldCompletion.catch(() => {});
13066
- return { fields, noFieldCompletion };
14318
+ return { fields, fieldsByLoader, noFieldCompletion };
13067
14319
  }
13068
14320
  function requestFieldPromises(route, fields, syncData, publicDeferred) {
13069
14321
  for (const key of Object.keys(fields)) {
@@ -13144,6 +14396,15 @@ async function normalizeLoaderError(err, headers) {
13144
14396
  const message = body || "Something went wrong";
13145
14397
  return { error: err, headers, message, status, type: "error" };
13146
14398
  }
14399
+ 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") {
14400
+ let message = "Something went wrong";
14401
+ if ("detail" in err.value && typeof err.value.detail === "string") {
14402
+ message = err.value.detail;
14403
+ } else if ("title" in err.value && typeof err.value.title === "string") {
14404
+ message = err.value.title;
14405
+ }
14406
+ return { error: err, headers, message, status: err.status, type: "error" };
14407
+ }
13147
14408
  if (isFurinRscRenderError(err)) {
13148
14409
  getLogger().error(err);
13149
14410
  return {
@@ -13172,10 +14433,10 @@ function mergeParentData(parent, own, path) {
13172
14433
  }
13173
14434
  return { ...parent, ...own };
13174
14435
  }
13175
- function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, ctxRecord, publicCtxRecord, mixed) {
14436
+ function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, inheritedRequestFields, ctxRecord, publicCtxRecord, mixed) {
13176
14437
  const publicSegment = mixed && (segment.mode ?? route.mode) !== "ssr";
13177
14438
  const parentFieldsRead = new Set;
13178
- const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
14439
+ const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? undefined : inheritedRequestFields, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
13179
14440
  return observeLoader(() => {
13180
14441
  const run = async () => await segment.loader?.(loaderCtx) ?? {};
13181
14442
  return publicSegment ? cacheMixedPublicLoader(route, ctx, segment, index, publicParent, parentFieldsRead, run) : run();
@@ -13190,13 +14451,13 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13190
14451
  let accumulatedParentPromise = Promise.resolve({});
13191
14452
  let publicParentPromise = Promise.resolve({});
13192
14453
  let loaderIndex = 0;
13193
- for (const r of route.routeChain) {
14454
+ for (const [routeIndex, r] of route.routeChain.entries()) {
13194
14455
  const parentAccum = accumulatedParentPromise;
13195
14456
  const publicParent = publicParentPromise;
13196
14457
  const privateSegment = mixed && (r.mode ?? route.mode) === "ssr";
13197
14458
  if (r.loader) {
13198
14459
  const index = loaderIndex;
13199
- const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, ctxRecord, publicCtxRecord, mixed);
14460
+ const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, requestFields?.fieldsByLoader[routeIndex - 1], ctxRecord, publicCtxRecord, mixed);
13200
14461
  loaderIndex += 1;
13201
14462
  loaderMap.set(r, loaderPromise);
13202
14463
  accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => mergeParentData(acc, own, ctx.path));
@@ -13210,7 +14471,7 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13210
14471
  }
13211
14472
  }
13212
14473
  }
13213
- const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
14474
+ const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, requestFields?.fields, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
13214
14475
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
13215
14476
  await requestFields?.noFieldCompletion;
13216
14477
  const headers = {};
@@ -13253,10 +14514,10 @@ function createPublicLoaderContext(ctx) {
13253
14514
  return publicContext;
13254
14515
  }
13255
14516
  function runLoaders(route, ctx) {
13256
- return runLoadersInternal(route, ctx, true, false);
14517
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, false));
13257
14518
  }
13258
14519
  function runPublicLoaders(route, ctx) {
13259
- return runLoadersInternal(route, ctx, false, false);
14520
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, false));
13260
14521
  }
13261
14522
  function hasSsrLoaderAncestor(route) {
13262
14523
  return route.routeChain.some((entry) => entry.mode === "ssr" && entry.loader !== undefined);
@@ -13266,26 +14527,53 @@ function hasMixedLoaderModes(route) {
13266
14527
  return route.routeChain.some((entry) => entry.loader !== undefined && entry.mode !== undefined && (entry.mode !== route.mode || entry.mode === "isr" && (entry.revalidate ?? 60) !== pageRevalidate));
13267
14528
  }
13268
14529
  function runMixedLoaders(route, ctx) {
13269
- return runLoadersInternal(route, ctx, true, true);
14530
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, true));
13270
14531
  }
13271
14532
  function runRouteLoaders(route, ctx) {
13272
14533
  return hasMixedLoaderModes(route) ? runMixedLoaders(route, ctx) : runLoaders(route, ctx);
13273
14534
  }
13274
14535
  function runSegmentPublicLoaders(route, ctx) {
13275
- return runLoadersInternal(route, ctx, false, true);
14536
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, true));
13276
14537
  }
13277
14538
  function hasRequestLoader(route) {
13278
14539
  return route.routeChain.some((entry) => entry.requestLoader !== undefined);
13279
14540
  }
13280
14541
 
14542
+ // src/server/render/react-stream.ts
14543
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "async_hooks";
14544
+ import { renderToReadableStream as renderReactStream } from "react-dom/server";
14545
+
14546
+ // src/client/client-module.ts
14547
+ import { preloadModule as preloadModule2 } from "react-dom";
14548
+ var resolveModuleHrefs = () => [];
14549
+ var resolveNonce = () => {
14550
+ return;
14551
+ };
14552
+ function setClientModuleNonceResolver(resolver) {
14553
+ resolveNonce = resolver;
14554
+ }
14555
+ function setClientModuleHrefResolver(resolver) {
14556
+ resolveModuleHrefs = resolver;
14557
+ }
14558
+
14559
+ // src/server/render/react-stream.ts
14560
+ var renderNonces = new AsyncLocalStorage7;
14561
+ setClientModuleNonceResolver(() => renderNonces.getStore());
14562
+ function renderToReadableStream(element, options) {
14563
+ const nonce = options?.nonce;
14564
+ return renderNonces.run(typeof nonce === "string" ? nonce : nonce?.script, () => renderReactStream(element, options));
14565
+ }
14566
+
13281
14567
  // src/server/render/route-frame-transport.ts
13282
14568
  async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13283
14569
  try {
13284
14570
  const { rscFrames, value } = serializeRouteFrameValue(await promise, idPrefix);
14571
+ const queries = deferredQuerySeeds(promise);
13285
14572
  return serializeRouteFrame({
13286
14573
  key,
13287
14574
  type: "defer-resolve",
13288
- value
14575
+ value,
14576
+ ...queries && { queries: toCrossJSON(queries) }
13289
14577
  }) + rscFrames;
13290
14578
  } catch (error) {
13291
14579
  return serializeRouteFrame({
@@ -13297,16 +14585,17 @@ async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13297
14585
  }
13298
14586
 
13299
14587
  // src/server/render/template.ts
14588
+ import { readFileSync as readFileSync7 } from "fs";
13300
14589
  init_plugin();
13301
14590
  init_instrumentation();
13302
14591
  init_instance();
13303
- import { readFileSync as readFileSync5 } from "fs";
13304
14592
  var instanceTemplateState = instanceSlot(() => ({
13305
14593
  devAssets: null,
13306
14594
  devCache: null,
13307
14595
  prodAssets: null,
13308
14596
  prodContent: null,
13309
- prodPath: null
14597
+ prodPath: null,
14598
+ prodPreload: null
13310
14599
  }));
13311
14600
  var DEV_TEMPLATE_TTL_MS = 1000;
13312
14601
  var TAG_ATTRIBUTE_PATTERN = /([A-Za-z][\w:-]*)="([^"]*)"/g;
@@ -13424,7 +14713,7 @@ function readTemplate(state) {
13424
14713
  return null;
13425
14714
  }
13426
14715
  try {
13427
- state.prodContent = readFileSync5(state.prodPath, "utf8");
14716
+ state.prodContent = readFileSync7(state.prodPath, "utf8");
13428
14717
  return state.prodContent;
13429
14718
  } catch {
13430
14719
  return null;
@@ -13441,10 +14730,17 @@ function readDocumentAssets(state) {
13441
14730
  state.prodAssets = documentAssetsFromTemplate(template);
13442
14731
  return state.prodAssets;
13443
14732
  }
14733
+ function setProductionPreloadManifest(manifest, instance) {
14734
+ instanceTemplateState(instance).prodPreload = manifest;
14735
+ }
14736
+ function getProductionPreloadManifest() {
14737
+ return instanceTemplateState().prodPreload ?? instanceTemplateState(defaultInstanceBucket()).prodPreload;
14738
+ }
14739
+ setClientModuleHrefResolver((key) => getProductionPreloadManifest()?.modules[key] ?? []);
13444
14740
 
13445
14741
  // src/server/render/ssr.ts
13446
14742
  function withSSRRouterContext(element, contextValue) {
13447
- return createElement6(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement6(RouterContext.Provider, { value: contextValue }, element));
14743
+ return createElement7(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement7(RouterContext.Provider, { value: contextValue }, element));
13448
14744
  }
13449
14745
  function hasDocumentMarkers(html) {
13450
14746
  return html.includes('data-furin-head=""') && html.includes('data-furin-scripts=""');
@@ -13513,7 +14809,8 @@ async function renderElementWithShellFallback(element, errorComponent, ssrContex
13513
14809
  }
13514
14810
  }
13515
14811
  function assertDeferredModeAllowed(route, deferredPromises) {
13516
- const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !route.requestKeys?.includes(key));
14812
+ const requestKeys = new Set(route.requestKeys);
14813
+ const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !requestKeys.has(key));
13517
14814
  if (deferredKeys.length > 0 && route.mode !== "ssr" && !hasSsrLoaderAncestor(route)) {
13518
14815
  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.");
13519
14816
  }
@@ -13548,6 +14845,10 @@ function resolveDocumentAssets(ctx) {
13548
14845
  }
13549
14846
  return documentAssetsFromTemplate(generateIndexHtml());
13550
14847
  }
14848
+ function withRouteModulePreloads(assets, pattern) {
14849
+ const modulePreloads = getProductionPreloadManifest()?.routes[pattern];
14850
+ return modulePreloads ? { ...assets, modulePreloads } : assets;
14851
+ }
13551
14852
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
13552
14853
  const loaderStart = Date.now();
13553
14854
  const loaderResult = precomputedLoaderResult ?? await runRouteLoaders(route, ctx);
@@ -13555,7 +14856,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13555
14856
  if (loaderResult.type === "redirect") {
13556
14857
  return loaderResult.response;
13557
14858
  }
13558
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
14859
+ if (throwOnFailure && loaderResult.type === "error") {
13559
14860
  throw loaderResult.error;
13560
14861
  }
13561
14862
  const isNotFound = loaderResult.type === "not-found";
@@ -13566,7 +14867,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13566
14867
  assertDeferredModeAllowed(route, deferredPromises);
13567
14868
  const { headers } = loaderResult;
13568
14869
  const componentProps = deferredPromises === undefined ? syncData : { ...syncData, ...deferredPromises };
13569
- const assets = await resolveDocumentAssets(ctx);
14870
+ const assets = withRouteModulePreloads(await resolveDocumentAssets(ctx), route.pattern);
13570
14871
  const errorComponent = route.error ?? root.error;
13571
14872
  let element;
13572
14873
  let headData;
@@ -13594,6 +14895,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13594
14895
  const ssrContext = {
13595
14896
  basePath: resolvedBasePath,
13596
14897
  currentHref: currentHrefFromContext(ctx, resolvedBasePath),
14898
+ currentPattern: route.pattern,
13597
14899
  defaultPreload: "intent",
13598
14900
  defaultPreloadDelay: 50,
13599
14901
  defaultPreloadStaleTime: 30000,
@@ -13624,7 +14926,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13624
14926
  }
13625
14927
  async function renderBufferedResult(prepared, route, root) {
13626
14928
  const { assets, deferredPromises, element, headData, headers, syncData } = prepared;
13627
- const { shellError, stream } = await renderElementWithShellFallback(withDocumentState(element, assets, headData, syncData), route.error ?? root.error, prepared.ssrContext, (fallback, digest, message) => withDocumentState(createElement6(FurinDocumentFallback, null, fallback), assets, headData, {
14929
+ const { shellError, stream } = await renderElementWithShellFallback(withDocumentState(element, assets, headData, syncData), route.error ?? root.error, prepared.ssrContext, (fallback, digest, message) => withDocumentState(createElement7(FurinDocumentFallback, null, fallback), assets, headData, {
13628
14930
  __furinError: { digest, message, status: 500 },
13629
14931
  __furinStatus: 500
13630
14932
  }));
@@ -13649,9 +14951,30 @@ async function renderBufferedResult(prepared, route, root) {
13649
14951
  headers,
13650
14952
  html,
13651
14953
  ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
14954
+ queryTags: queryTagsFromData(syncData),
13652
14955
  status: prepared.status
13653
14956
  };
13654
14957
  }
14958
+ async function normalizePrerenderContext(route, ctx) {
14959
+ const parsedParams = await parseRouteParams(ctx.params, mergeRouteSchemas(route.routeChain, "params"));
14960
+ if (!parsedParams.ok) {
14961
+ throw new Error(`[furin] Invalid prerender params for "${route.pattern}".`, {
14962
+ cause: parsedParams.errors
14963
+ });
14964
+ }
14965
+ ctx.params = parsedParams.params;
14966
+ const querySchema = mergeRouteSchemas(route.routeChain, "query");
14967
+ if (querySchema === undefined) {
14968
+ return;
14969
+ }
14970
+ const parsedQuery = await parseRouteQuery(new URL(ctx.request.url), querySchema);
14971
+ if (!parsedQuery.ok) {
14972
+ throw new Error(`[furin] Invalid prerender query for "${route.pattern}".`, {
14973
+ cause: parsedQuery.errors
14974
+ });
14975
+ }
14976
+ ctx.query = parsedQuery.query;
14977
+ }
13655
14978
  function renderForPath(route, params, root, origin, mode, basePath, searchRoutes, search, requestContext) {
13656
14979
  return runInSyntheticRenderScope(async () => {
13657
14980
  const resolvedPath = resolvePath(route.pattern, params);
@@ -13677,6 +15000,9 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
13677
15000
  request: new Request(requestUrl),
13678
15001
  set: { headers: {} }
13679
15002
  };
15003
+ if (requestContext === undefined) {
15004
+ await normalizePrerenderContext(route, ctx);
15005
+ }
13680
15006
  const loaderResult = await (hasMixedLoaderModes(route) ? runSegmentPublicLoaders(route, ctx) : runPublicLoaders(route, ctx));
13681
15007
  const prepared = await prepareRender(route, ctx, root, basePath, true, loaderResult, searchRoutes);
13682
15008
  if (prepared instanceof Response) {
@@ -13717,7 +15043,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
13717
15043
  }
13718
15044
 
13719
15045
  // src/server/render/static-params.ts
13720
- import { dirname as dirname8, relative as relative6 } from "path";
15046
+ import { dirname as dirname10, relative as relative6 } from "path";
13721
15047
  init_patterns();
13722
15048
  var STATIC_PARAMS_CONCURRENCY = 4;
13723
15049
  function collectStaticParamsStages(route) {
@@ -13738,8 +15064,8 @@ function ancestorPattern(route, ancestors) {
13738
15064
  if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
13739
15065
  return route.pattern;
13740
15066
  }
13741
- const pagesDir = dirname8(rootSourcePath);
13742
- const ancestorDir = dirname8(ancestorSourcePath);
15067
+ const pagesDir = dirname10(rootSourcePath);
15068
+ const ancestorDir = dirname10(ancestorSourcePath);
13743
15069
  if (ancestorDir === pagesDir) {
13744
15070
  return "/";
13745
15071
  }
@@ -13839,25 +15165,44 @@ async function prerenderRoute(route, params, root, origin, mode, basePath, searc
13839
15165
  html: renderResult.html,
13840
15166
  ndjson: renderResult.ndjson,
13841
15167
  status: renderResult.status,
13842
- tags: route.tags
15168
+ tags: [...route.tags ?? [], ...renderResult.queryTags ?? []]
13843
15169
  };
13844
15170
  }
13845
- async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15171
+ async function prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes) {
13846
15172
  const resolvedPath = resolvePath(route.pattern, params);
13847
15173
  const cached = getSSGCache(resolvedPath);
13848
15174
  if (cached) {
13849
15175
  if (cached.tags === route.tags) {
13850
- return cached;
15176
+ return { cacheStored: true, entry: cached };
13851
15177
  }
13852
- const taggedEntry = { ...cached, tags: route.tags };
15178
+ const taggedEntry = {
15179
+ ...cached,
15180
+ tags: [
15181
+ ...route.tags ?? [],
15182
+ ...(cached.tags ?? []).filter((tag) => queryFromTag(tag) !== undefined)
15183
+ ]
15184
+ };
13853
15185
  setSSGCache(resolvedPath, taggedEntry);
13854
- return taggedEntry;
15186
+ return { cacheStored: true, entry: taggedEntry };
13855
15187
  }
13856
- const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
13857
- if (entry instanceof Response) {
13858
- return entry;
15188
+ const cache = ssgRouteCache();
15189
+ const generation = cache.captureGeneration(resolvedPath);
15190
+ try {
15191
+ const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
15192
+ if (entry instanceof Response || entry.status !== 200 || !generation.valid) {
15193
+ return { cacheStored: false, entry };
15194
+ }
15195
+ setSSGCache(resolvedPath, entry);
15196
+ return { cacheStored: true, entry };
15197
+ } finally {
15198
+ cache.releaseGeneration(resolvedPath, generation);
15199
+ }
15200
+ }
15201
+ async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15202
+ const { entry } = await prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes);
15203
+ if (!(entry instanceof Response) && entry.status >= 500) {
15204
+ throw new Error(`[furin] Failed to prerender SSG route "${route.pattern}" (HTTP ${entry.status}).`);
13859
15205
  }
13860
- setSSGCache(resolvedPath, entry);
13861
15206
  return entry;
13862
15207
  }
13863
15208
  // src/build/ssg-cache.ts
@@ -13920,8 +15265,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
13920
15265
  }
13921
15266
 
13922
15267
  // src/rsc/build/index.ts
13923
- import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "fs";
13924
- import { basename as basename3, join as join10 } from "path";
15268
+ import { mkdirSync as mkdirSync4, writeFileSync as writeFileSync6 } from "fs";
15269
+ import { basename as basename4, join as join10 } from "path";
13925
15270
  import { fileURLToPath as fileURLToPath4 } from "url";
13926
15271
  init_transform_isomorphic();
13927
15272
 
@@ -14031,22 +15376,23 @@ ${result.logs.map((log) => log.message).join(`
14031
15376
  ${codecResult.logs.map((log) => log.message).join(`
14032
15377
  `)}`);
14033
15378
  }
14034
- const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
15379
+ const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename4(output.path)}` }));
14035
15380
  const manifest = { buildId, clientReferences: [], css };
14036
- writeFileSync5(join10(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
15381
+ writeFileSync6(join10(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
14037
15382
  return manifest;
14038
15383
  }
14039
15384
 
14040
15385
  // src/adapter/runtime-build.ts
14041
15386
  init_patterns();
14042
- var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
14043
- var _pkgSrcDir2 = existsSync9(join11(_pkgRoot2, "src", "furin.ts")) ? join11(_pkgRoot2, "src") : join11(_pkgRoot2, "dist");
15387
+ var _pkgRoot2 = dirname11(dirname11(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
15388
+ var _pkgSrcDir2 = existsSync10(join11(_pkgRoot2, "src", "furin.ts")) ? join11(_pkgRoot2, "src") : join11(_pkgRoot2, "dist");
14044
15389
  var _ext2 = ".ts";
14045
15390
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
14046
15391
  var MIXED_CACHE_IMPORT_RE = /mixed-cache(?:\.ts)?$/;
14047
15392
  var ANY_MODULE_RE = /.*/;
14048
15393
  var REACT_SERVER_IMPORT_RE = /^react-dom\/server(?:\.edge)?$/;
14049
15394
  var REACT_STATIC_IMPORT_RE = /^react-dom\/static\.edge$/;
15395
+ var SCRIPT_FILE_RE = /\.[cm]?[jt]sx?$/;
14050
15396
  var BUILD_ID_INPUT_PATHS = [
14051
15397
  `${_pkgSrcDir2}/build/compile-entry${_ext2}`,
14052
15398
  `${_pkgSrcDir2}/build/entry-template${_ext2}`,
@@ -14102,16 +15448,49 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
14102
15448
  }
14103
15449
  }
14104
15450
  }
15451
+ const sources = new Map;
15452
+ const visit = async (inputPath) => {
15453
+ const path = existsSync10(inputPath) ? realpathSync4(inputPath) : inputPath;
15454
+ fingerprintPaths.delete(inputPath);
15455
+ fingerprintPaths.add(path);
15456
+ if (sources.has(path)) {
15457
+ return;
15458
+ }
15459
+ sources.set(path, "");
15460
+ const content = existsSync10(path) ? await Bun.file(path).text() : "";
15461
+ sources.set(path, content);
15462
+ if (!SCRIPT_FILE_RE.test(path)) {
15463
+ return;
15464
+ }
15465
+ const transpiler = new Bun.Transpiler({ loader: path.endsWith("x") ? "tsx" : "ts" });
15466
+ await Promise.all(transpiler.scanImports(content).flatMap(({ path: specifier }) => {
15467
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
15468
+ return [];
15469
+ }
15470
+ let dependency;
15471
+ try {
15472
+ dependency = Bun.resolveSync(specifier, dirname11(path));
15473
+ } catch {
15474
+ return [];
15475
+ }
15476
+ if (!isAbsolute5(dependency) || toPosixPath(dependency).includes("/node_modules/")) {
15477
+ return [];
15478
+ }
15479
+ fingerprintPaths.add(dependency);
15480
+ return [visit(dependency)];
15481
+ }));
15482
+ };
15483
+ await Promise.all([...fingerprintPaths].map(visit));
14105
15484
  for (const path of BUILD_ID_INPUT_PATHS) {
14106
- if (!existsSync9(path)) {
15485
+ if (!existsSync10(path)) {
14107
15486
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
14108
15487
  }
14109
15488
  fingerprintPaths.add(path);
14110
15489
  }
14111
- const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
14112
- const content = existsSync9(path) ? await Bun.file(path).text() : "";
15490
+ const fileParts = (await Promise.all([...fingerprintPaths].map(async (path) => {
15491
+ const content = sources.get(path) ?? (existsSync10(path) ? await Bun.file(path).text() : "");
14113
15492
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
14114
- }));
15493
+ }))).sort(compareCodeUnits);
14115
15494
  const routeParts = routes.map((route) => JSON.stringify({
14116
15495
  mode: route.mode,
14117
15496
  path: stableFingerprintPath(route.path, projectRoot),
@@ -14123,15 +15502,16 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
14123
15502
  `);
14124
15503
  }
14125
15504
  function stableFingerprintPath(path, projectRoot) {
14126
- const projectPath = relative7(projectRoot, path);
14127
- if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
15505
+ const absolutePath = existsSync10(path) ? realpathSync4(path) : path;
15506
+ const projectPath = relative7(realpathSync4(projectRoot), absolutePath);
15507
+ if (!isAbsolute5(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
14128
15508
  return `app/${toPosixPath(projectPath)}`;
14129
15509
  }
14130
- const frameworkPath = relative7(_pkgRoot2, path);
14131
- if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
15510
+ const frameworkPath = relative7(_pkgRoot2, absolutePath);
15511
+ if (!isAbsolute5(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
14132
15512
  return `furin/${toPosixPath(frameworkPath)}`;
14133
15513
  }
14134
- return `external/${basename4(path)}`;
15514
+ return `external/${basename5(path)}`;
14135
15515
  }
14136
15516
  function buildCompileMetadata(root, routes) {
14137
15517
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14155,7 +15535,7 @@ function buildCompileMetadata(root, routes) {
14155
15535
  }
14156
15536
  function pprRuntimePlugin(apps) {
14157
15537
  const enabled = apps.some((app) => app.routes.some((route) => resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
14158
- const pprPath = resolve6(_pkgSrcDir2, "server/render/ppr-route.ts");
15538
+ const pprPath = resolve8(_pkgSrcDir2, "server/render/ppr-route.ts");
14159
15539
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
14160
15540
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
14161
15541
  return {
@@ -14167,7 +15547,7 @@ function pprRuntimePlugin(apps) {
14167
15547
  return;
14168
15548
  }
14169
15549
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
14170
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15550
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14171
15551
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
14172
15552
  return;
14173
15553
  }
@@ -14185,7 +15565,7 @@ export const runPprPublicLoaders = renderPprRoute;`,
14185
15565
  }
14186
15566
  function mixedRuntimePlugin(apps) {
14187
15567
  const enabled = apps.some((app) => app.routes.some(hasMixedLoaderModes));
14188
- const mixedPath = resolve6(_pkgSrcDir2, "server/render/mixed-cache.ts");
15568
+ const mixedPath = resolve8(_pkgSrcDir2, "server/render/mixed-cache.ts");
14189
15569
  return {
14190
15570
  name: "furin-mixed-runtime",
14191
15571
  setup(build) {
@@ -14193,7 +15573,7 @@ function mixedRuntimePlugin(apps) {
14193
15573
  return;
14194
15574
  }
14195
15575
  build.onResolve({ filter: MIXED_CACHE_IMPORT_RE }, ({ path, importer }) => {
14196
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15576
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14197
15577
  if (absolute !== mixedPath && `${absolute}.ts` !== mixedPath) {
14198
15578
  return;
14199
15579
  }
@@ -14219,15 +15599,16 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
14219
15599
  const modulePaths = routeSourcePaths(app);
14220
15600
  const clientDirName = clientDirNameForPrefix(prefix);
14221
15601
  const label = prefix === "" ? "root app" : `app "${prefix}"`;
14222
- const { entryChunk, cssChunks } = await buildClient(routes, {
15602
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14223
15603
  basePath: prefix,
14224
15604
  clientDirName,
14225
15605
  clientLogging: options.clientLogging ?? false,
14226
- metafilePath: options.analyze ? join11(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
15606
+ metafilePath: options.analyze ? join11(dirname11(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
14227
15607
  optimizeImports: options.optimizeImports,
14228
15608
  outDir: targetDir,
14229
15609
  pagesDir: app.pagesDir,
14230
15610
  plugins: options.plugins,
15611
+ preloadRouteChunks: options.preload?.routeChunks,
14231
15612
  publicPath: `${prefix}/_client/`,
14232
15613
  reactCompiler: options.reactCompiler,
14233
15614
  rootLayout: root.path
@@ -14237,8 +15618,9 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14237
15618
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14238
15619
  const clientDir = join11(targetDir, clientDirName);
14239
15620
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14240
- writeFileSync6(join11(clientDir, "index.html"), indexHtml);
15621
+ writeFileSync7(join11(clientDir, "index.html"), indexHtml);
14241
15622
  setProductionTemplateContent(indexHtml);
15623
+ setProductionPreloadManifest(preloadManifest);
14242
15624
  ssgRouteCache().clear();
14243
15625
  let ssgCache;
14244
15626
  let prerenders = [];
@@ -14262,6 +15644,7 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14262
15644
  modulePaths,
14263
15645
  nativeRoutes: composableRouteModuleSpecifier(app),
14264
15646
  prefix,
15647
+ preloadManifest,
14265
15648
  rootConventions,
14266
15649
  rootPath: root.path,
14267
15650
  routeMetadata,
@@ -14332,7 +15715,7 @@ function writeServerMetafile(build, analyze, buildRoot) {
14332
15715
  const analysisDir = join12(buildRoot, "analysis");
14333
15716
  ensureDir(analysisDir);
14334
15717
  const metafilePath = join12(analysisDir, "bun-server.json");
14335
- writeFileSync7(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
15718
+ writeFileSync8(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
14336
15719
  `);
14337
15720
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
14338
15721
  }
@@ -14364,7 +15747,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
14364
15747
  ...context.extraContext ?? [],
14365
15748
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
14366
15749
  ],
14367
- templateHtml: readFileSync6(join12(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
15750
+ templateHtml: readFileSync8(join12(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
14368
15751
  }));
14369
15752
  return await materializeServerAppEntry({
14370
15753
  apps: contexts,
@@ -14383,14 +15766,14 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14383
15766
  }
14384
15767
  const target = "bun";
14385
15768
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
14386
- const targetDir = resolve7(rootDir, targetManifest.targetDir);
15769
+ const targetDir = resolve9(rootDir, targetManifest.targetDir);
14387
15770
  rmSync2(targetDir, { force: true, recursive: true });
14388
15771
  rmSync2(join12(buildRoot, "private", "server-sourcemaps", "bun"), {
14389
15772
  force: true,
14390
15773
  recursive: true
14391
15774
  });
14392
15775
  ensureDir(targetDir);
14393
- const publicDir = existsSync10(join12(rootDir, "public")) ? join12(rootDir, "public") : undefined;
15776
+ const publicDir = existsSync11(join12(rootDir, "public")) ? join12(rootDir, "public") : undefined;
14394
15777
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
14395
15778
  targetManifest.buildId = headlineBuildId;
14396
15779
  if (serverEntry) {
@@ -14467,15 +15850,16 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14467
15850
  }
14468
15851
 
14469
15852
  // src/adapter/package.ts
14470
- import { existsSync as existsSync11, rmSync as rmSync3, writeFileSync as writeFileSync8 } from "fs";
14471
- import { join as join13, relative as relative8, resolve as resolve8 } from "path";
15853
+ import { existsSync as existsSync12, rmSync as rmSync3, writeFileSync as writeFileSync9 } from "fs";
15854
+ import { join as join13, relative as relative8, resolve as resolve10 } from "path";
15855
+ init_transform_isomorphic();
14472
15856
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
14473
15857
  const { prefix, root, routes, pagesDir } = app;
14474
15858
  const modulePaths = routeSourcePaths(app);
14475
15859
  const targetDir = join13(buildRoot, "package");
14476
15860
  rmSync3(targetDir, { force: true, recursive: true });
14477
15861
  ensureDir(targetDir);
14478
- const { entryChunk, cssChunks } = await buildClient(routes, {
15862
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14479
15863
  basePath: prefix,
14480
15864
  clientLogging: options.clientLogging ?? false,
14481
15865
  metafilePath: options.analyze ? join13(buildRoot, "analysis", "package-client.json") : undefined,
@@ -14483,6 +15867,7 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
14483
15867
  outDir: targetDir,
14484
15868
  pagesDir,
14485
15869
  plugins: options.plugins,
15870
+ preloadRouteChunks: options.preload?.routeChunks,
14486
15871
  publicPath: `${prefix}/_client/`,
14487
15872
  reactCompiler: options.reactCompiler,
14488
15873
  rootLayout: root.path
@@ -14492,12 +15877,13 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14492
15877
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14493
15878
  const clientDir = join13(targetDir, "client");
14494
15879
  const publicDir = join13(rootDir, "public");
14495
- if (existsSync11(publicDir)) {
15880
+ if (existsSync12(publicDir)) {
14496
15881
  copyDirRecursive(publicDir, join13(targetDir, "public"));
14497
15882
  }
14498
15883
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14499
- writeFileSync8(join13(clientDir, "index.html"), indexHtml);
15884
+ writeFileSync9(join13(clientDir, "index.html"), indexHtml);
14500
15885
  setProductionTemplateContent(indexHtml);
15886
+ setProductionPreloadManifest(preloadManifest);
14501
15887
  ssgRouteCache().clear();
14502
15888
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
14503
15889
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14525,6 +15911,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14525
15911
  modulePaths,
14526
15912
  nativeRoutes: composableRouteModuleSpecifier(app),
14527
15913
  prefix,
15914
+ preloadManifest,
14528
15915
  rootConventions,
14529
15916
  rootPath: root.path,
14530
15917
  routeMetadata,
@@ -14547,7 +15934,9 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14547
15934
  plugins: [
14548
15935
  register.plugin,
14549
15936
  ...options.plugins ?? [],
14550
- createRoutesPlugin({ instances: [app], target: "server" })
15937
+ createRoutesPlugin({ instances: [app], target: "server" }),
15938
+ isomorphicTransformPlugin("server"),
15939
+ environmentGuardPlugin("ssr")
14551
15940
  ],
14552
15941
  sourcemap: "none",
14553
15942
  target: "bun"
@@ -14555,7 +15944,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14555
15944
  if (!result.success) {
14556
15945
  throw new AggregateError(result.logs, "[furin] package register build failed");
14557
15946
  }
14558
- const relativePagesDir = toPosixPath(relative8(targetDir, resolve8(rootDir, pagesDir)));
15947
+ const relativePagesDir = toPosixPath(relative8(targetDir, resolve10(rootDir, pagesDir)));
14559
15948
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
14560
15949
  import { fileURLToPath } from "node:url";
14561
15950
  import { furin } from "@teyik0/furin";
@@ -14582,7 +15971,7 @@ export function createFurinApp(options = {}) {
14582
15971
 
14583
15972
  export const prefix = ${JSON.stringify(prefix)};
14584
15973
  `;
14585
- writeFileSync8(join13(targetDir, "index.js"), factorySource);
15974
+ writeFileSync9(join13(targetDir, "index.js"), factorySource);
14586
15975
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
14587
15976
 
14588
15977
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -14590,7 +15979,7 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
14590
15979
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
14591
15980
  export declare const prefix: string;
14592
15981
  `;
14593
- writeFileSync8(join13(targetDir, "index.d.ts"), dtsSource);
15982
+ writeFileSync9(join13(targetDir, "index.d.ts"), dtsSource);
14594
15983
  console.log(`[furin] Package artifact: ${toPosixPath(relative8(rootDir, targetDir))}`);
14595
15984
  return {
14596
15985
  buildId,
@@ -14601,19 +15990,19 @@ export declare const prefix: string;
14601
15990
  }
14602
15991
 
14603
15992
  // src/adapter/static.ts
14604
- import { cpSync as cpSync2, existsSync as existsSync12, rmSync as rmSync4, writeFileSync as writeFileSync9 } from "fs";
14605
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join14, parse as parse3, relative as relative9, resolve as resolve9, sep as sep2, win32 } from "path";
15993
+ import { cpSync as cpSync2, existsSync as existsSync13, rmSync as rmSync4, writeFileSync as writeFileSync10 } from "fs";
15994
+ import { dirname as dirname12, isAbsolute as isAbsolute6, join as join14, parse as parse3, relative as relative9, resolve as resolve11, sep as sep2, win32 } from "path";
14606
15995
  init_patterns();
14607
15996
  var STATIC_CONCURRENCY = 4;
14608
15997
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
14609
15998
  var TRAILING_SLASHES_RE = /\/+$/;
14610
15999
  var STATIC_RENDER_ORIGIN = "http://localhost";
14611
16000
  function pathToOutputFile(urlPath, outDir, fileName) {
14612
- const normalizedOutDir = resolve9(outDir);
16001
+ const normalizedOutDir = resolve11(outDir);
14613
16002
  if (urlPath === "/" || urlPath === "") {
14614
16003
  return join14(normalizedOutDir, fileName);
14615
16004
  }
14616
- const resolved = resolve9(normalizedOutDir, urlPath.slice(1), fileName);
16005
+ const resolved = resolve11(normalizedOutDir, urlPath.slice(1), fileName);
14617
16006
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
14618
16007
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
14619
16008
  }
@@ -14686,22 +16075,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
14686
16075
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
14687
16076
  }
14688
16077
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
14689
- ensureDir(dirname10(htmlOutputFile));
14690
- writeFileSync9(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
16078
+ ensureDir(dirname12(htmlOutputFile));
16079
+ writeFileSync10(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
14691
16080
  if (staticLocation.spa !== null) {
14692
16081
  const serializedRedirect = await toCrossJSONAsync({
14693
16082
  __furinRedirect: staticLocation.spa
14694
16083
  });
14695
- writeFileSync9(dataOutputFile, `${JSON.stringify(serializedRedirect)}
16084
+ writeFileSync10(dataOutputFile, `${JSON.stringify(serializedRedirect)}
14696
16085
  `);
14697
16086
  }
14698
16087
  renderedRoutes.push(urlPath);
14699
16088
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
14700
16089
  return;
14701
16090
  }
14702
- ensureDir(dirname10(htmlOutputFile));
14703
- writeFileSync9(htmlOutputFile, entry.html);
14704
- writeFileSync9(dataOutputFile, entry.ndjson);
16091
+ ensureDir(dirname12(htmlOutputFile));
16092
+ writeFileSync10(htmlOutputFile, entry.html);
16093
+ writeFileSync10(dataOutputFile, entry.ndjson);
14705
16094
  renderedRoutes.push(urlPath);
14706
16095
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
14707
16096
  } catch (err) {
@@ -14808,15 +16197,15 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14808
16197
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
14809
16198
  }
14810
16199
  const rawOutDir = staticConfig.outDir ?? "dist";
14811
- const outDir = resolve9(rootDir, rawOutDir);
14812
- const normalizedRoot = resolve9(rootDir);
14813
- const normalizedBuildRoot = resolve9(buildRoot);
16200
+ const outDir = resolve11(rootDir, rawOutDir);
16201
+ const normalizedRoot = resolve11(rootDir);
16202
+ const normalizedBuildRoot = resolve11(buildRoot);
14814
16203
  if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
14815
16204
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
14816
16205
  }
14817
16206
  function isOutsideOutDir(target) {
14818
16207
  const rel = relative9(outDir, target);
14819
- return rel.startsWith("..") || isAbsolute4(rel);
16208
+ return rel.startsWith("..") || isAbsolute6(rel);
14820
16209
  }
14821
16210
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
14822
16211
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -14835,33 +16224,35 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14835
16224
  const targetDir = join14(buildRoot, "static");
14836
16225
  rmSync4(targetDir, { force: true, recursive: true });
14837
16226
  ensureDir(targetDir);
14838
- const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
16227
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(ssgRoutes, {
14839
16228
  basePath,
14840
16229
  clientLogging: Boolean(options.clientLogging),
14841
16230
  metafilePath: options.analyze ? join14(buildRoot, "analysis", "static-client.json") : undefined,
14842
16231
  optimizeImports: options.optimizeImports,
14843
16232
  outDir: targetDir,
14844
- pagesDir: dirname10(root.path),
16233
+ pagesDir: dirname12(root.path),
14845
16234
  plugins: options.plugins,
16235
+ preloadRouteChunks: options.preload?.routeChunks,
14846
16236
  publicPath,
14847
16237
  reactCompiler: options.reactCompiler,
14848
16238
  rootLayout: root.path
14849
16239
  });
14850
16240
  const publicFavicon = join14(rootDir, "public", "favicon.ico");
14851
- const faviconHref = existsSync12(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
16241
+ const faviconHref = existsSync13(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
14852
16242
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
14853
16243
  setProductionTemplateContent(shellHtml);
16244
+ setProductionPreloadManifest(preloadManifest);
14854
16245
  const publicSrcDir = join14(rootDir, "public");
14855
- if (existsSync12(publicSrcDir)) {
16246
+ if (existsSync13(publicSrcDir)) {
14856
16247
  cpSync2(publicSrcDir, outDir, { recursive: true });
14857
16248
  }
14858
16249
  const clientSrcDir = join14(targetDir, "client");
14859
- if (existsSync12(clientSrcDir)) {
16250
+ if (existsSync13(clientSrcDir)) {
14860
16251
  cpSync2(clientSrcDir, join14(outDir, "_client"), { recursive: true });
14861
16252
  }
14862
16253
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
14863
16254
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
14864
- writeFileSync9(join14(outDir, "404.html"), shellHtml);
16255
+ writeFileSync10(join14(outDir, "404.html"), shellHtml);
14865
16256
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
14866
16257
  rmSync4(targetDir, { force: true, recursive: true });
14867
16258
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -14875,8 +16266,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14875
16266
  }
14876
16267
 
14877
16268
  // src/adapter/vercel.ts
14878
- import { cpSync as cpSync3, existsSync as existsSync13, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync10 } from "fs";
14879
- import { basename as basename5, dirname as dirname11, extname as extname4, join as join15, relative as relative10 } from "path";
16269
+ import { cpSync as cpSync3, existsSync as existsSync14, readFileSync as readFileSync9, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync11 } from "fs";
16270
+ import { basename as basename6, dirname as dirname13, extname as extname4, join as join15, relative as relative10 } from "path";
14880
16271
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
14881
16272
  init_transform_isomorphic();
14882
16273
  init_patterns();
@@ -14888,7 +16279,7 @@ var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
14888
16279
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
14889
16280
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
14890
16281
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
14891
- var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
16282
+ var FURIN_RUNTIME_ROOT2 = dirname13(import.meta.dir);
14892
16283
  function isFurinRuntimeImporter(importer) {
14893
16284
  if (importer === "") {
14894
16285
  return false;
@@ -14919,8 +16310,8 @@ function vercelRuntimePlugin() {
14919
16310
  };
14920
16311
  }
14921
16312
  function frameworkVersion() {
14922
- const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
14923
- const packageJson = JSON.parse(readFileSync7(join15(packageRoot, "package.json"), "utf8"));
16313
+ const packageRoot = dirname13(dirname13(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
16314
+ const packageJson = JSON.parse(readFileSync9(join15(packageRoot, "package.json"), "utf8"));
14924
16315
  return packageJson.version;
14925
16316
  }
14926
16317
  function serverEntryLoader(serverEntry) {
@@ -14938,7 +16329,7 @@ function serverEntryLoader(serverEntry) {
14938
16329
  }
14939
16330
  function assertDefaultServerExport(serverEntry) {
14940
16331
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
14941
- const { exports, imports } = transpiler.scan(readFileSync7(serverEntry, "utf8"));
16332
+ const { exports, imports } = transpiler.scan(readFileSync9(serverEntry, "utf8"));
14942
16333
  if (!exports.includes("default")) {
14943
16334
  throw new Error(`[furin] Vercel server entry "${toPosixPath(serverEntry)}" must export the Elysia app as default. ` + "Guard app.listen() with `if (import.meta.main)` so the same entry also runs locally.");
14944
16335
  }
@@ -15018,7 +16409,7 @@ function isPprRoute(app, route) {
15018
16409
  return resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route));
15019
16410
  }
15020
16411
  async function addPrerenderFallback(spec, physicalRoutePath, prerender, functionsDir) {
15021
- const fallback = `${basename5(spec.functionName)}.prerender-fallback.html`;
16412
+ const fallback = `${basename6(spec.functionName)}.prerender-fallback.html`;
15022
16413
  const { result } = prerender;
15023
16414
  if (result === undefined) {
15024
16415
  return;
@@ -15036,9 +16427,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
15036
16427
  body = result.html;
15037
16428
  ({ status } = result);
15038
16429
  }
15039
- const fallbackPath = join15(dirname11(join15(functionsDir, spec.functionName)), fallback);
15040
- ensureDir(dirname11(fallbackPath));
15041
- writeFileSync10(fallbackPath, body);
16430
+ const fallbackPath = join15(dirname13(join15(functionsDir, spec.functionName)), fallback);
16431
+ ensureDir(dirname13(fallbackPath));
16432
+ writeFileSync11(fallbackPath, body);
15042
16433
  spec.config.fallback = fallback;
15043
16434
  spec.config.initialHeaders = {
15044
16435
  "content-type": contentType,
@@ -15050,8 +16441,8 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
15050
16441
  }
15051
16442
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
15052
16443
  const aliasPath = join15(functionsDir, `${functionName}.func`);
15053
- ensureDir(dirname11(aliasPath));
15054
- const target = relative10(dirname11(aliasPath), serverFunctionDir);
16444
+ ensureDir(dirname13(aliasPath));
16445
+ const target = relative10(dirname13(aliasPath), serverFunctionDir);
15055
16446
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
15056
16447
  }
15057
16448
  function createExactPrerenderSpec(prerender, routePath) {
@@ -15304,7 +16695,7 @@ process.exit(0);
15304
16695
  ${stderr}
15305
16696
  ${stdout}`);
15306
16697
  }
15307
- const results = JSON.parse(readFileSync7(resultPath, "utf8"));
16698
+ const results = JSON.parse(readFileSync9(resultPath, "utf8"));
15308
16699
  for (const [index, job] of jobs.entries()) {
15309
16700
  const result = results[index];
15310
16701
  await addPrerenderFallback(job.spec, job.path, {
@@ -15403,14 +16794,14 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15403
16794
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
15404
16795
  cpSync3(join15(targetDir, "server-codec.js"), join15(serverFunctionDir, "server-codec.js"));
15405
16796
  const publicDir = join15(rootDir, "public");
15406
- if (existsSync13(publicDir)) {
16797
+ if (existsSync14(publicDir)) {
15407
16798
  cpSync3(publicDir, staticDir, { recursive: true });
15408
16799
  for (const app of apps) {
15409
16800
  const appStaticDir = join15(staticDir, app.prefix.slice(1));
15410
16801
  const appPublicDir = join15(appStaticDir, "public");
15411
16802
  cpSync3(publicDir, appPublicDir, { recursive: true });
15412
16803
  const favicon = join15(publicDir, "favicon.ico");
15413
- if (app.prefix !== "" && existsSync13(favicon)) {
16804
+ if (app.prefix !== "" && existsSync14(favicon)) {
15414
16805
  cpSync3(favicon, join15(appStaticDir, "favicon.ico"));
15415
16806
  }
15416
16807
  }
@@ -15422,19 +16813,21 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15422
16813
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
15423
16814
  }
15424
16815
  const pprResumeKey = crypto.randomUUID();
15425
- const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
15426
- const appEntry = await materializeServerAppEntry({
15427
- apps: builds.map(({ entryApp, indexHtml }) => ({
15428
- ...entryApp,
15429
- embed: undefined,
15430
- serveAssets: false,
15431
- templateHtml: indexHtml
15432
- })),
15433
- headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
15434
- instances: apps,
15435
- outDir: serverFunctionDir,
15436
- serverEntry
15437
- });
16816
+ const [prerenderSpecs, appEntry] = await Promise.all([
16817
+ createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey),
16818
+ materializeServerAppEntry({
16819
+ apps: builds.map(({ entryApp, indexHtml }) => ({
16820
+ ...entryApp,
16821
+ embed: undefined,
16822
+ serveAssets: false,
16823
+ templateHtml: indexHtml
16824
+ })),
16825
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
16826
+ instances: apps,
16827
+ outDir: serverFunctionDir,
16828
+ serverEntry
16829
+ })
16830
+ ]);
15438
16831
  const entryPath = join15(serverFunctionDir, "_vercel-handler.ts");
15439
16832
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
15440
16833
  const serverBuild = await runBunBuild({
@@ -15470,15 +16863,15 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15470
16863
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
15471
16864
  }
15472
16865
  const metafilePath = join15(buildRoot, "analysis", "vercel-server.json");
15473
- ensureDir(dirname11(metafilePath));
15474
- writeFileSync10(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
16866
+ ensureDir(dirname13(metafilePath));
16867
+ writeFileSync11(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
15475
16868
  `);
15476
16869
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
15477
16870
  }
15478
16871
  const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
15479
- writeFileSync10(join15(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
16872
+ writeFileSync11(join15(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
15480
16873
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
15481
- writeFileSync10(join15(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
16874
+ writeFileSync11(join15(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
15482
16875
  handler: "index.js",
15483
16876
  launcherType: "Nodejs",
15484
16877
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -15489,7 +16882,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15489
16882
  `);
15490
16883
  for (const spec of prerenderSpecs) {
15491
16884
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
15492
- writeFileSync10(join15(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
16885
+ writeFileSync11(join15(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
15493
16886
  `);
15494
16887
  }
15495
16888
  const assetRoutes = apps.map((app) => ({
@@ -15519,7 +16912,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15519
16912
  ],
15520
16913
  version: 3
15521
16914
  };
15522
- writeFileSync10(join15(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
16915
+ writeFileSync11(join15(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
15523
16916
  `);
15524
16917
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => resolveDocumentMode(prerender.route) === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
15525
16918
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => resolveDocumentMode(route) === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
@@ -15572,6 +16965,7 @@ var configSchema = t.Object({
15572
16965
  clientLogging: t.Optional(t.Boolean()),
15573
16966
  optimizeImports: t.Optional(t.Array(t.String())),
15574
16967
  pagesDir: t.Optional(t.String()),
16968
+ preload: t.Optional(t.Object({ routeChunks: t.Optional(t.Boolean()) })),
15575
16969
  reactCompiler: t.Optional(t.Boolean()),
15576
16970
  rootDir: t.Optional(t.String()),
15577
16971
  serverEntry: t.Optional(t.String()),
@@ -15595,7 +16989,7 @@ init_transform_isomorphic();
15595
16989
  init_instance();
15596
16990
 
15597
16991
  // src/server/router/discovery.ts
15598
- import { existsSync as existsSync14 } from "fs";
16992
+ import { existsSync as existsSync15 } from "fs";
15599
16993
  import { readdir } from "fs/promises";
15600
16994
  import { join as join16, parse as parse4 } from "path";
15601
16995
 
@@ -15696,6 +17090,7 @@ function adaptDefinedPage(route, parent) {
15696
17090
  params: route.schemas?.params,
15697
17091
  parent,
15698
17092
  query: route.schemas?.query,
17093
+ remountDeps: route.remountDeps,
15699
17094
  requestLoader: route.requestLoader
15700
17095
  },
15701
17096
  component,
@@ -15749,7 +17144,7 @@ async function scanPages(pagesDir) {
15749
17144
  async function scanRootLayout(pagesDir) {
15750
17145
  const rootPath = `${pagesDir}/root.tsx`;
15751
17146
  const ctx = getCompileContext();
15752
- if (!(existsSync14(rootPath) || ctx?.modules[rootPath])) {
17147
+ if (!(existsSync15(rootPath) || ctx?.modules[rootPath])) {
15753
17148
  throw new Error("[furin] root.tsx: not found.");
15754
17149
  }
15755
17150
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -15789,8 +17184,8 @@ function getSourceModuleCandidates(dir, name) {
15789
17184
  async function loadConventionComponent(dir, name) {
15790
17185
  const ctx = getCompileContext();
15791
17186
  for (const filePath of getSourceModuleCandidates(dir, name)) {
15792
- if (existsSync14(filePath) || ctx?.modules[filePath]) {
15793
- const moduleSpecifier = IS_DEV && existsSync14(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
17187
+ if (existsSync15(filePath) || ctx?.modules[filePath]) {
17188
+ const moduleSpecifier = IS_DEV && existsSync15(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15794
17189
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15795
17190
  if (mod.default) {
15796
17191
  return { component: mod.default, path: filePath };
@@ -15873,7 +17268,7 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15873
17268
  for (const segment of segments) {
15874
17269
  directory = `${directory}/${segment}`;
15875
17270
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15876
- if (!existsSync14(candidate)) {
17271
+ if (!existsSync15(candidate)) {
15877
17272
  continue;
15878
17273
  }
15879
17274
  const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
@@ -15993,9 +17388,9 @@ init_instance();
15993
17388
  init_lang_detect();
15994
17389
  init_ast_walk();
15995
17390
  init_parser();
15996
- import { readFileSync as readFileSync8 } from "fs";
17391
+ import { readFileSync as readFileSync10 } from "fs";
15997
17392
  function scanFurinInstances(serverEntryPath) {
15998
- const code = readFileSync8(serverEntryPath, "utf8");
17393
+ const code = readFileSync10(serverEntryPath, "utf8");
15999
17394
  const lang = detectLangFromPath(serverEntryPath);
16000
17395
  if (lang === "dts") {
16001
17396
  return [];
@@ -16076,42 +17471,42 @@ function registerIsomorphicRuntimePlugin() {
16076
17471
  function resolveAppSpecs(options, serverEntry, rootDir) {
16077
17472
  if (options.apps && options.apps.length > 0) {
16078
17473
  return options.apps.map((app) => ({
16079
- pagesDir: resolve10(rootDir, app.pagesDir),
17474
+ pagesDir: resolve12(rootDir, app.pagesDir),
16080
17475
  prefix: normalizePrefix(app.prefix)
16081
17476
  }));
16082
17477
  }
16083
17478
  if (options.pagesDir) {
16084
- return [{ pagesDir: resolve10(rootDir, options.pagesDir), prefix: "" }];
17479
+ return [{ pagesDir: resolve12(rootDir, options.pagesDir), prefix: "" }];
16085
17480
  }
16086
17481
  if (serverEntry) {
16087
17482
  const detected = scanFurinInstances(serverEntry);
16088
17483
  if (detected.length > 0) {
16089
17484
  return detected.map((app) => ({
16090
- pagesDir: resolve10(rootDir, app.pagesDir),
17485
+ pagesDir: resolve12(rootDir, app.pagesDir),
16091
17486
  prefix: app.prefix
16092
17487
  }));
16093
17488
  }
16094
17489
  }
16095
- return [{ pagesDir: resolve10(rootDir, "src/pages"), prefix: "" }];
17490
+ return [{ pagesDir: resolve12(rootDir, "src/pages"), prefix: "" }];
16096
17491
  }
16097
17492
  async function buildApp(options) {
16098
17493
  return withProductionBuild(() => buildAppInternal(options));
16099
17494
  }
16100
17495
  async function buildAppInternal(options) {
16101
- const rootDir = resolve10(options.rootDir ?? process.cwd());
17496
+ const rootDir = resolve12(options.rootDir ?? process.cwd());
16102
17497
  const buildRoot = join17(rootDir, BUILD_OUTPUT_DIR);
16103
17498
  const serverEntry = (() => {
16104
17499
  if (options.target === "static" || options.target === "package") {
16105
17500
  return null;
16106
17501
  }
16107
17502
  if (options.serverEntry) {
16108
- const resolved = resolve10(rootDir, options.serverEntry);
16109
- if (existsSync15(resolved)) {
17503
+ const resolved = resolve12(rootDir, options.serverEntry);
17504
+ if (existsSync16(resolved)) {
16110
17505
  return resolved;
16111
17506
  }
16112
17507
  }
16113
- const entry = resolve10(rootDir, "src/server.ts");
16114
- if (!existsSync15(entry)) {
17508
+ const entry = resolve12(rootDir, "src/server.ts");
17509
+ if (!existsSync16(entry)) {
16115
17510
  throw new Error("[furin] Entrypoint server.ts not found");
16116
17511
  }
16117
17512
  return entry;
@@ -16192,7 +17587,7 @@ async function buildAppInternal(options) {
16192
17587
  throw new Error(`[furin] Unsupported build target "${target}"`);
16193
17588
  }
16194
17589
  }
16195
- writeFileSync11(join17(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
17590
+ writeFileSync12(join17(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
16196
17591
  `);
16197
17592
  return {
16198
17593
  manifest,