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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/entry-template.d.ts +3 -0
  4. package/dist/build/entry-template.ts +7 -0
  5. package/dist/build/hydrate.d.ts +1 -1
  6. package/dist/build/index.js +1671 -276
  7. package/dist/build/preload-manifest.d.ts +17 -0
  8. package/dist/build/types.d.ts +6 -0
  9. package/dist/cli/index.js +1672 -286
  10. package/dist/client/client-module.d.ts +26 -0
  11. package/dist/client/define-route.d.ts +9 -0
  12. package/dist/client/document.d.ts +2 -0
  13. package/dist/client/internal/runtime-types.d.ts +2 -0
  14. package/dist/client/link.js +932 -118
  15. package/dist/client/mutation.d.ts +38 -0
  16. package/dist/client/query-store.d.ts +85 -0
  17. package/dist/client/query.d.ts +14 -0
  18. package/dist/client/route-api.d.ts +11 -0
  19. package/dist/client/router/context.d.ts +3 -2
  20. package/dist/client/router/index.d.ts +1 -1
  21. package/dist/client/router/link-utils.d.ts +8 -1
  22. package/dist/client/router/navigation.d.ts +2 -9
  23. package/dist/client/router/optimistic.d.ts +41 -0
  24. package/dist/client/router/search/index.d.ts +3 -3
  25. package/dist/client/router/search-store.d.ts +1 -0
  26. package/dist/client/router/sync-catch-up.d.ts +3 -0
  27. package/dist/client/router/types.d.ts +49 -7
  28. package/dist/client/sync.d.ts +39 -22
  29. package/dist/client.d.ts +11 -33
  30. package/dist/client.js +1219 -59
  31. package/dist/config.d.ts +7 -0
  32. package/dist/config.js +1 -0
  33. package/dist/define-route.d.ts +78 -32
  34. package/dist/env.d.ts +2 -2
  35. package/dist/furin.d.ts +1 -2
  36. package/dist/furin.js +2448 -710
  37. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  38. package/dist/plugin/index.js +349 -18
  39. package/dist/plugin/transform-client-module.d.ts +16 -0
  40. package/dist/plugin/transform-client.d.ts +2 -0
  41. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  42. package/dist/routes.d.ts +6 -0
  43. package/dist/rsc-client.js +87 -16
  44. package/dist/rsc.js +87 -16
  45. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  46. package/dist/server/auto-invalidate/types.d.ts +2 -0
  47. package/dist/server/cache/isr.d.ts +2 -4
  48. package/dist/server/cache/route-cache.d.ts +5 -0
  49. package/dist/server/dev/graph.d.ts +1 -0
  50. package/dist/server/dev-page-plugin.d.ts +5 -19
  51. package/dist/server/internal.d.ts +3 -0
  52. package/dist/server/internal.js +55 -35
  53. package/dist/server/production-server.js +54 -34
  54. package/dist/server/render/loaders.d.ts +4 -2
  55. package/dist/server/render/react-stream.d.ts +3 -0
  56. package/dist/server/render/ssr.d.ts +2 -1
  57. package/dist/server/render/template.d.ts +4 -0
  58. package/dist/server/router/defined-route.d.ts +2 -0
  59. package/dist/server/router/hmr.d.ts +1 -1
  60. package/dist/server/sync/adapter.d.ts +25 -4
  61. package/dist/server/sync/atomic.d.ts +25 -0
  62. package/dist/server/sync/drizzle/index.d.ts +45 -0
  63. package/dist/server/sync/drizzle/index.js +540 -0
  64. package/dist/server/sync/execution-error.d.ts +2 -0
  65. package/dist/server/sync/index.d.ts +2 -1
  66. package/dist/server/sync/index.js +533 -105
  67. package/dist/server/sync/mutation-handler.d.ts +4 -0
  68. package/dist/server/sync/plugin.d.ts +34 -11
  69. package/dist/server/sync/postgres/execute.d.ts +3 -0
  70. package/dist/server/sync/postgres/index.d.ts +12 -1
  71. package/dist/server/sync/postgres/index.js +34 -13
  72. package/dist/server/sync/postgres/sql.d.ts +8 -0
  73. package/dist/server/sync/prisma/index.d.ts +24 -0
  74. package/dist/server/sync/prisma/index.js +340 -0
  75. package/dist/server/sync/queries.d.ts +21 -0
  76. package/dist/server/sync/query-context.d.ts +5 -0
  77. package/dist/server/sync/redis/index.js +3 -3
  78. package/dist/server/sync/redis/scripts.d.ts +1 -1
  79. package/dist/server/sync/response.d.ts +1 -0
  80. package/dist/server/sync/sqlite/index.d.ts +3 -0
  81. package/dist/server/sync/sqlite/index.js +10 -4
  82. package/dist/server/sync/stream.d.ts +2 -5
  83. package/dist/server/sync/validation.d.ts +4 -0
  84. package/dist/shared/defer.d.ts +31 -0
  85. package/dist/shared/error.d.ts +2 -2
  86. package/dist/shared/page-key.d.ts +7 -0
  87. package/dist/shared/query-bindings.d.ts +12 -0
  88. package/dist/shared/route-frame.d.ts +1 -0
  89. package/dist/shared/sync-query.d.ts +40 -0
  90. package/package.json +29 -6
  91. package/src/adapter/package.ts +12 -2
  92. package/src/adapter/runtime-build.ts +63 -12
  93. package/src/adapter/static.ts +7 -2
  94. package/src/adapter/vercel.ts +15 -13
  95. package/src/build/client.ts +23 -5
  96. package/src/build/entry-template.ts +7 -0
  97. package/src/build/hydrate.ts +17 -3
  98. package/src/build/preload-manifest.ts +100 -0
  99. package/src/build/production-instrumentation.ts +6 -3
  100. package/src/build/types.ts +4 -0
  101. package/src/cli/index.ts +1 -0
  102. package/src/client/browser-events-runtime.ts +4 -0
  103. package/src/client/client-module.ts +57 -0
  104. package/src/client/define-route.ts +11 -1
  105. package/src/client/document.tsx +28 -18
  106. package/src/client/hmr.ts +2 -1
  107. package/src/client/internal/runtime-types.ts +2 -0
  108. package/src/client/link.tsx +8 -8
  109. package/src/client/mutation.ts +136 -0
  110. package/src/client/query-store.ts +418 -0
  111. package/src/client/query.tsx +67 -0
  112. package/src/client/route-api.tsx +75 -0
  113. package/src/client/router/boundary-tree.tsx +7 -2
  114. package/src/client/router/context.ts +57 -4
  115. package/src/client/router/index.ts +3 -0
  116. package/src/client/router/link-utils.ts +29 -1
  117. package/src/client/router/navigation.ts +3 -50
  118. package/src/client/router/optimistic.ts +233 -0
  119. package/src/client/router/provider.tsx +304 -44
  120. package/src/client/router/search/index.ts +37 -17
  121. package/src/client/router/search-store.ts +4 -0
  122. package/src/client/router/sync-catch-up.ts +7 -0
  123. package/src/client/router/types.ts +71 -9
  124. package/src/client/sync.ts +438 -65
  125. package/src/client.ts +20 -60
  126. package/src/config.ts +5 -0
  127. package/src/define-route.ts +113 -55
  128. package/src/env.d.ts +2 -2
  129. package/src/furin.ts +75 -13
  130. package/src/plugin/hmr-dependencies.ts +58 -0
  131. package/src/plugin/index.ts +38 -2
  132. package/src/plugin/routes.ts +3 -3
  133. package/src/plugin/transform-client-module.ts +123 -0
  134. package/src/plugin/transform-client.ts +293 -13
  135. package/src/plugin/transform-isomorphic.ts +11 -5
  136. package/src/routes.ts +8 -0
  137. package/src/rsc/shared.tsx +104 -18
  138. package/src/server/auto-invalidate/registry.ts +4 -0
  139. package/src/server/auto-invalidate/runtime.ts +17 -0
  140. package/src/server/auto-invalidate/types.ts +6 -0
  141. package/src/server/cache/isr.ts +6 -34
  142. package/src/server/cache/route-cache.ts +40 -4
  143. package/src/server/dev/graph.ts +16 -2
  144. package/src/server/dev-page-plugin.ts +93 -59
  145. package/src/server/internal.ts +3 -0
  146. package/src/server/render/document.tsx +10 -1
  147. package/src/server/render/element.tsx +7 -2
  148. package/src/server/render/isr.ts +61 -29
  149. package/src/server/render/loaders.ts +118 -47
  150. package/src/server/render/mixed-cache.ts +33 -4
  151. package/src/server/render/not-found.ts +4 -7
  152. package/src/server/render/ppr-document.ts +2 -1
  153. package/src/server/render/ppr-route.ts +30 -10
  154. package/src/server/render/react-stream.ts +17 -0
  155. package/src/server/render/route-frame-transport.ts +3 -0
  156. package/src/server/render/ssg.ts +51 -18
  157. package/src/server/render/ssr.ts +53 -8
  158. package/src/server/render/template.ts +23 -0
  159. package/src/server/router/defined-route.ts +3 -0
  160. package/src/server/router/hmr.ts +3 -2
  161. package/src/server/router/plugin.ts +27 -12
  162. package/src/server/sync/adapter.ts +41 -4
  163. package/src/server/sync/atomic.ts +303 -0
  164. package/src/server/sync/drizzle/index.ts +145 -0
  165. package/src/server/sync/execution-error.ts +1 -0
  166. package/src/server/sync/fingerprint.ts +2 -6
  167. package/src/server/sync/index.ts +6 -0
  168. package/src/server/sync/mutation-handler.ts +69 -0
  169. package/src/server/sync/plugin.ts +177 -60
  170. package/src/server/sync/postgres/execute.ts +20 -0
  171. package/src/server/sync/postgres/index.ts +52 -16
  172. package/src/server/sync/postgres/sql.ts +20 -0
  173. package/src/server/sync/prisma/index.ts +70 -0
  174. package/src/server/sync/queries.ts +75 -0
  175. package/src/server/sync/query-context.ts +85 -0
  176. package/src/server/sync/redis/index.ts +7 -3
  177. package/src/server/sync/redis/scripts.ts +1 -1
  178. package/src/server/sync/response.ts +21 -0
  179. package/src/server/sync/sqlite/index.ts +19 -8
  180. package/src/server/sync/stream.ts +14 -22
  181. package/src/server/sync/validation.ts +34 -0
  182. package/src/shared/defer.ts +48 -0
  183. package/src/shared/error.ts +2 -2
  184. package/src/shared/page-key.ts +36 -0
  185. package/src/shared/query-bindings.ts +138 -0
  186. package/src/shared/route-frame.ts +13 -1
  187. package/src/shared/route-map.ts +12 -2
  188. package/src/shared/sync-query.ts +138 -0
package/dist/cli/index.js CHANGED
@@ -290,7 +290,7 @@ var init_instance = __esm(() => {
290
290
  // src/server/dev/graph.ts
291
291
  import { randomUUID } from "crypto";
292
292
  import { readFileSync, statSync } from "fs";
293
- import { dirname as dirname5, extname, resolve as resolve3 } from "path";
293
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
294
294
  function normalizeModulePath(path) {
295
295
  return path.replaceAll("\\", "/");
296
296
  }
@@ -303,7 +303,7 @@ function resolveDevSourceImports(source, path, loader) {
303
303
  const isSourceExtension = [".js", ".jsx", ".ts", ".tsx"].includes(extension);
304
304
  const absolute = imported.path.startsWith(".") && extension && !isSourceExtension ? resolve3(dirname5(path), imported.path) : Bun.resolveSync(imported.path, dirname5(path));
305
305
  const resolved = normalizeModulePath(absolute);
306
- if (!resolved.includes("/node_modules/")) {
306
+ if (isAbsolute2(resolved) && !resolved.includes("/node_modules/")) {
307
307
  imports.push(resolved);
308
308
  }
309
309
  } catch {}
@@ -449,6 +449,19 @@ class DevGraph {
449
449
  const normalizedTo = normalizeModulePath(to);
450
450
  return this.importChain(from, normalizedTo).includes(normalizedTo);
451
451
  }
452
+ sourceDependencies(from) {
453
+ const pending = [normalizeModulePath(from)];
454
+ const visited = new Set;
455
+ while (pending.length > 0) {
456
+ const path = pending.pop();
457
+ if (path === undefined || visited.has(path)) {
458
+ continue;
459
+ }
460
+ visited.add(path);
461
+ pending.push(...this.#dependencies.get(path) ?? []);
462
+ }
463
+ return [...visited];
464
+ }
452
465
  clearSourceErrors(path) {
453
466
  const modulePath = normalizeModulePath(path);
454
467
  for (const [message, positions] of this.#sourceErrors) {
@@ -3225,6 +3238,87 @@ var init_dead_code_elimination = __esm(() => {
3225
3238
  ]);
3226
3239
  });
3227
3240
 
3241
+ // src/plugin/transform-client-module.ts
3242
+ import { realpathSync as realpathSync2 } from "fs";
3243
+ import { dirname as dirname7 } from "path";
3244
+ function clientModuleKey(modulePath) {
3245
+ const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
3246
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
3247
+ }
3248
+ function collectClientModuleBindings(program) {
3249
+ const bindings = new Set;
3250
+ for (const statement of program.body) {
3251
+ if (statement.type !== "ImportDeclaration") {
3252
+ continue;
3253
+ }
3254
+ const declaration = statement;
3255
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
3256
+ continue;
3257
+ }
3258
+ for (const specifier of declaration.specifiers) {
3259
+ const imported = specifier.imported;
3260
+ const local = specifier.local;
3261
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
3262
+ bindings.add(local.name);
3263
+ }
3264
+ }
3265
+ }
3266
+ return bindings;
3267
+ }
3268
+ function dynamicImportSpecifier(loader) {
3269
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
3270
+ return null;
3271
+ }
3272
+ const body = loader.body;
3273
+ const source = body.type === "ImportExpression" ? body.source : null;
3274
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
3275
+ }
3276
+ function transformClientModules(source, filename, environment) {
3277
+ if (!source.includes("clientModule")) {
3278
+ return source;
3279
+ }
3280
+ const { program } = parseSource(source, detectLangFromPath(filename));
3281
+ const bindings = collectClientModuleBindings(program);
3282
+ if (bindings.size === 0) {
3283
+ return source;
3284
+ }
3285
+ const transformed = new MagicString(source);
3286
+ walk(program, {
3287
+ CallExpression(node, context) {
3288
+ const call = node;
3289
+ const [loader, ...rest] = call.arguments;
3290
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
3291
+ return;
3292
+ }
3293
+ const unwrapped = unwrapTSExpression(loader);
3294
+ const specifier = dynamicImportSpecifier(unwrapped);
3295
+ if (specifier === null) {
3296
+ return;
3297
+ }
3298
+ let key;
3299
+ try {
3300
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname7(filename))));
3301
+ } catch (error) {
3302
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
3303
+ }
3304
+ if (environment === "client") {
3305
+ transformed.appendLeft(loader.end, `, ${key}`);
3306
+ } else {
3307
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
3308
+ }
3309
+ }
3310
+ });
3311
+ return transformed.toString();
3312
+ }
3313
+ var FURIN_CLIENT_MODULES, SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
3314
+ var init_transform_client_module = __esm(() => {
3315
+ init_dist();
3316
+ init_dist2();
3317
+ init_lang_detect();
3318
+ init_parser();
3319
+ FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
3320
+ });
3321
+
3228
3322
  // src/plugin/transform-isomorphic.ts
3229
3323
  function importedName(specifier) {
3230
3324
  const { imported } = specifier;
@@ -3445,11 +3539,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
3445
3539
  }
3446
3540
  });
3447
3541
  }
3448
- function transformIsomorphicFunctions(source, filename, environment) {
3542
+ function transformIsomorphicFunctions(input, filename, environment) {
3449
3543
  const lang = detectLangFromPath(filename);
3450
3544
  if (lang === "dts") {
3451
- return { code: source, map: null, transformed: false };
3545
+ return { code: input, map: null, transformed: false };
3452
3546
  }
3547
+ const source = transformClientModules(input, filename, environment);
3548
+ const clientModulesTransformed = source !== input;
3453
3549
  const { program, diagnostics } = parseSource(source, lang);
3454
3550
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
3455
3551
  if (firstError) {
@@ -3461,7 +3557,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
3461
3557
  assertNoSplitChains(source, filename, program, builders);
3462
3558
  const candidates = collectCandidates(source, filename, program, bindings);
3463
3559
  if (candidates.length === 0) {
3464
- return { code: source, map: null, transformed: false };
3560
+ return { code: source, map: null, transformed: clientModulesTransformed };
3465
3561
  }
3466
3562
  const transformed = new MagicString(source);
3467
3563
  for (const candidate of candidates) {
@@ -3479,7 +3575,8 @@ function isomorphicTransformPlugin(environment) {
3479
3575
  return {
3480
3576
  name: `furin-isomorphic-${environment}`,
3481
3577
  setup(build) {
3482
- build.onLoad({ filter: SCRIPT_FILE_FILTER }, async ({ path }) => {
3578
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
3579
+ const path = args.path.split("?")[0];
3483
3580
  const source = await Bun.file(path).text();
3484
3581
  const loader = detectLoaderFromPath(path);
3485
3582
  const result = transformIsomorphicFunctions(source, path, environment);
@@ -3498,8 +3595,9 @@ var init_transform_isomorphic = __esm(() => {
3498
3595
  init_lang_detect();
3499
3596
  init_parser();
3500
3597
  init_dead_code_elimination();
3598
+ init_transform_client_module();
3501
3599
  FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
3502
- SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)$/;
3600
+ SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)(?:\?.*)?$/;
3503
3601
  });
3504
3602
 
3505
3603
  // src/server/sync/config.ts
@@ -3579,6 +3677,9 @@ class AutoInvalidateRegistry {
3579
3677
  }
3580
3678
  return [...paths];
3581
3679
  }
3680
+ tagsForPath(path) {
3681
+ return [...this.pathToTags.get(path) ?? []];
3682
+ }
3582
3683
  unregisterPath(urlPath, owner) {
3583
3684
  if (owner === undefined) {
3584
3685
  this.pathOwners.delete(urlPath);
@@ -3632,7 +3733,14 @@ function matchesPath(urlPath, path, type) {
3632
3733
  }
3633
3734
  function createRouteCache(options) {
3634
3735
  const store = new Map;
3736
+ const generations = new Map;
3635
3737
  const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
3738
+ const invalidateGenerations = (key) => {
3739
+ for (const generation of generations.get(key) ?? []) {
3740
+ generation.valid = false;
3741
+ }
3742
+ generations.delete(key);
3743
+ };
3636
3744
  const evictOldest = () => {
3637
3745
  if (options.maxSize === undefined || store.size <= options.maxSize) {
3638
3746
  return;
@@ -3643,6 +3751,7 @@ function createRouteCache(options) {
3643
3751
  }
3644
3752
  };
3645
3753
  const deleteEntry = (key) => {
3754
+ invalidateGenerations(key);
3646
3755
  const entry = store.get(key);
3647
3756
  if (entry === undefined) {
3648
3757
  return false;
@@ -3652,7 +3761,20 @@ function createRouteCache(options) {
3652
3761
  return true;
3653
3762
  };
3654
3763
  return {
3764
+ captureGeneration(key) {
3765
+ const generation = { valid: true };
3766
+ let pending = generations.get(key);
3767
+ if (pending === undefined) {
3768
+ pending = new Set;
3769
+ generations.set(key, pending);
3770
+ }
3771
+ pending.add(generation);
3772
+ return generation;
3773
+ },
3655
3774
  clear() {
3775
+ for (const key of generations.keys()) {
3776
+ invalidateGenerations(key);
3777
+ }
3656
3778
  for (const key of [...store.keys()]) {
3657
3779
  deleteEntry(key);
3658
3780
  }
@@ -3678,14 +3800,15 @@ function createRouteCache(options) {
3678
3800
  invalidatePath(path, type) {
3679
3801
  let deleted = false;
3680
3802
  const purgedPaths = [];
3681
- for (const key of [...store.keys()]) {
3803
+ for (const key of new Set([...store.keys(), ...generations.keys()])) {
3682
3804
  const urlPath = pathFromKey(key);
3683
3805
  if (urlPath === null || !matchesPath(urlPath, path, type)) {
3684
3806
  continue;
3685
3807
  }
3686
- deleteEntry(key);
3687
- deleted = true;
3688
- purgedPaths.push(urlPath);
3808
+ if (deleteEntry(key)) {
3809
+ deleted = true;
3810
+ purgedPaths.push(urlPath);
3811
+ }
3689
3812
  }
3690
3813
  return { deleted, purgedPaths: [...new Set(purgedPaths)] };
3691
3814
  },
@@ -3693,6 +3816,13 @@ function createRouteCache(options) {
3693
3816
  return store.keys();
3694
3817
  },
3695
3818
  name: options.name,
3819
+ releaseGeneration(key, generation) {
3820
+ const pending = generations.get(key);
3821
+ pending?.delete(generation);
3822
+ if (pending?.size === 0) {
3823
+ generations.delete(key);
3824
+ }
3825
+ },
3696
3826
  set(key, entry) {
3697
3827
  const previous = store.get(key);
3698
3828
  if (previous !== undefined) {
@@ -3729,7 +3859,7 @@ var init_registry2 = __esm(() => {
3729
3859
  instanceInvalidators = instanceSlot(() => new Map);
3730
3860
  });
3731
3861
 
3732
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
3862
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
3733
3863
  function elapsedMs(startTime) {
3734
3864
  return Math.max(0, Date.now() - startTime);
3735
3865
  }
@@ -3870,7 +4000,7 @@ var init_utils = __esm(() => {
3870
4000
  _isoDate = /* @__PURE__ */ new Date;
3871
4001
  });
3872
4002
 
3873
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
4003
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
3874
4004
  function normalizeRedactPathPattern(pattern) {
3875
4005
  if (!pattern.includes("*") && !pattern.includes("."))
3876
4006
  return `**.${pattern}`;
@@ -4179,7 +4309,7 @@ var init_redact_C7FmdhwI = __esm(() => {
4179
4309
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
4180
4310
  });
4181
4311
 
4182
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4312
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4183
4313
  function logPluginError(name, hook, err) {
4184
4314
  console.error(`[evlog/${name}] ${hook} failed:`, err);
4185
4315
  }
@@ -4349,7 +4479,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
4349
4479
  globalConfig = getRegistry().config;
4350
4480
  });
4351
4481
 
4352
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4482
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4353
4483
  function pushTreeSpacer(children) {
4354
4484
  children.push(PRETTY_ERROR_TREE_SPACER);
4355
4485
  }
@@ -4650,7 +4780,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
4650
4780
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
4651
4781
  });
4652
4782
 
4653
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4783
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4654
4784
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
4655
4785
  const compact = partial.compact ?? (inDev && pretty);
4656
4786
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -4703,7 +4833,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
4703
4833
  };
4704
4834
  });
4705
4835
 
4706
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4836
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4707
4837
  function hasWideEventPublisher() {
4708
4838
  return publisher !== null;
4709
4839
  }
@@ -4719,7 +4849,7 @@ function publishWideEvent(event) {
4719
4849
  var publisher = null;
4720
4850
  var init_wideEventChannel_BUDW48oP = () => {};
4721
4851
 
4722
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4852
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4723
4853
  function isEvlogError(error) {
4724
4854
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
4725
4855
  }
@@ -4728,7 +4858,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
4728
4858
  evlogErrorBrand = Symbol.for("evlog.error.brand");
4729
4859
  });
4730
4860
 
4731
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
4861
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
4732
4862
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
4733
4863
  var init_error = __esm(() => {
4734
4864
  init_utils();
@@ -4837,7 +4967,7 @@ var init_error = __esm(() => {
4837
4967
  });
4838
4968
  });
4839
4969
 
4840
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4970
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4841
4971
  function extractSafeHeaders(headers) {
4842
4972
  const raw = {};
4843
4973
  headers.forEach((value, key) => {
@@ -4858,7 +4988,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
4858
4988
  init_utils();
4859
4989
  });
4860
4990
 
4861
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
4991
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
4862
4992
  function writePrettyStdout(text) {
4863
4993
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
4864
4994
  }
@@ -5780,12 +5910,12 @@ var init_audit_C8euLMvu = __esm(() => {
5780
5910
  initLogger(__EVLOG_CONFIG__);
5781
5911
  });
5782
5912
 
5783
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
5913
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
5784
5914
  var init_dist3 = __esm(() => {
5785
5915
  init_audit_C8euLMvu();
5786
5916
  });
5787
5917
 
5788
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5918
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5789
5919
  function shouldDeferEmitForResponse(response) {
5790
5920
  if (!response.body)
5791
5921
  return false;
@@ -5865,7 +5995,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
5865
5995
  }
5866
5996
  var init_streamResponse_OlirMA5P = () => {};
5867
5997
 
5868
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
5998
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
5869
5999
  function extractErrorStatus(error) {
5870
6000
  if (error === null || typeof error !== "object")
5871
6001
  return 500;
@@ -5875,7 +6005,7 @@ function extractErrorStatus(error) {
5875
6005
  }
5876
6006
  var init_errors_CL8dDgIi = () => {};
5877
6007
 
5878
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
6008
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
5879
6009
  function shouldLog(path, include, exclude) {
5880
6010
  if (exclude && exclude.length > 0) {
5881
6011
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -5903,7 +6033,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
5903
6033
  init_utils();
5904
6034
  });
5905
6035
 
5906
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
6036
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
5907
6037
  function resolveMiddlewarePluginRunner(options) {
5908
6038
  const global2 = getGlobalPluginRunner();
5909
6039
  const local = options.plugins;
@@ -6098,7 +6228,7 @@ var init_middleware_fam3VyaL = __esm(() => {
6098
6228
  runnerCache = /* @__PURE__ */ new WeakMap;
6099
6229
  });
6100
6230
 
6101
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
6231
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
6102
6232
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
6103
6233
  const log = parent;
6104
6234
  log.fork = (label, fn) => {
@@ -6201,7 +6331,7 @@ var init_integration_CGD18W8r = __esm(() => {
6201
6331
  init_middleware_fam3VyaL();
6202
6332
  });
6203
6333
 
6204
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
6334
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
6205
6335
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6206
6336
  function createLoggerStorage(contextHint, id = contextHint) {
6207
6337
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -6220,7 +6350,7 @@ var init_storage = __esm(() => {
6220
6350
  init_globalRegistry_Bh3bIGwA();
6221
6351
  });
6222
6352
 
6223
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
6353
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
6224
6354
  var init_toolkit = __esm(() => {
6225
6355
  init_integration_CGD18W8r();
6226
6356
  init_storage();
@@ -6589,17 +6719,17 @@ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection",
6589
6719
  var init_plugin2 = () => {};
6590
6720
 
6591
6721
  // src/cli/index.ts
6592
- import { existsSync as existsSync16 } from "fs";
6593
- import { resolve as resolve13 } from "path";
6722
+ import { existsSync as existsSync17 } from "fs";
6723
+ import { resolve as resolve15 } from "path";
6594
6724
  import { parseArgs } from "util";
6595
6725
 
6596
6726
  // src/build/index.ts
6597
- import { existsSync as existsSync13, writeFileSync as writeFileSync9 } from "fs";
6598
- import { join as join15, relative as relative10, resolve as resolve10 } from "path";
6727
+ import { existsSync as existsSync14, writeFileSync as writeFileSync10 } from "fs";
6728
+ import { join as join15, relative as relative10, resolve as resolve12 } from "path";
6599
6729
 
6600
6730
  // src/adapter/bun.ts
6601
- import { existsSync as existsSync8, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
6602
- import { join as join10, resolve as resolve7 } from "path";
6731
+ import { existsSync as existsSync9, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
6732
+ import { join as join10, resolve as resolve9 } from "path";
6603
6733
 
6604
6734
  // src/build/bun-build.ts
6605
6735
  function runBunBuild(config) {
@@ -6669,6 +6799,7 @@ function buildAppContextBlock(app, varPrefix) {
6669
6799
  const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
6670
6800
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
6671
6801
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
6802
+ const preloadManifestLine = app.preloadManifest ? ` preloadManifest: ${JSON.stringify(app.preloadManifest)},` : "";
6672
6803
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
6673
6804
  const contextLines = [
6674
6805
  "__setCompileContext({",
@@ -6688,6 +6819,7 @@ function buildAppContextBlock(app, varPrefix) {
6688
6819
  routeMetadataLine,
6689
6820
  serveAssetsLine,
6690
6821
  ssgCacheLine,
6822
+ preloadManifestLine,
6691
6823
  templateHtmlLine,
6692
6824
  ...app.extraContext ?? [],
6693
6825
  "});"
@@ -6951,9 +7083,9 @@ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from
6951
7083
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
6952
7084
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
6953
7085
  var DEV_RUNTIME_IMPORT = /(?:^|[/\\])server[/\\]dev[/\\](?:browser-events|diagnostics|graph|plugin)(?:\.ts|\.js)?$/;
6954
- var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\]route-config-autofix)(?:\.ts|\.js)?$/;
7086
+ var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\](?:route-config-autofix|transform-client))(?:\.ts|\.js)?$/;
6955
7087
  var HMR_IMPORT = /(?:^|[/\\])server[/\\]router[/\\]hmr(?:\.ts|\.js)?$/;
6956
- var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix)(?:\.ts|\.js)?$/;
7088
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix|transform-client)(?:\.ts|\.js)?$/;
6957
7089
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
6958
7090
  var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
6959
7091
  function isFurinRuntimePath(path) {
@@ -6961,6 +7093,9 @@ function isFurinRuntimePath(path) {
6961
7093
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
6962
7094
  }
6963
7095
  function devBuildExport(path) {
7096
+ if (path.includes("transform-client")) {
7097
+ return "getHmrDataSignature";
7098
+ }
6964
7099
  return path.includes("route-config-autofix") ? "fixRouteConfigLayout" : "writeDevFiles";
6965
7100
  }
6966
7101
  function productionInstrumentationPlugin() {
@@ -7013,13 +7148,24 @@ import {
7013
7148
  statSync as statSync2,
7014
7149
  watch
7015
7150
  } from "fs";
7016
- import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute2, join as join5, relative as relative4, resolve as resolve4, sep } from "path";
7151
+ import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute3, join as join5, relative as relative4, resolve as resolve4, sep } from "path";
7017
7152
  import { pathToFileURL } from "url";
7018
7153
  import { Elysia } from "elysia";
7019
7154
 
7020
7155
  // src/shared/elysia-contract.ts
7021
7156
  import { Validator } from "elysia";
7022
7157
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
7158
+ function getSchemaValidator(schema) {
7159
+ const validator = Validator.create(schema);
7160
+ if (validator === undefined) {
7161
+ return;
7162
+ }
7163
+ return {
7164
+ Check: (value) => validator.Check(value),
7165
+ Errors: (value) => validator.Errors(value),
7166
+ parse: async (value, type) => validator.From ? await validator.From(value, type) : value
7167
+ };
7168
+ }
7023
7169
  function isTypeBoxObjectSchema(schema) {
7024
7170
  if (schema === null || typeof schema !== "object") {
7025
7171
  return false;
@@ -7193,6 +7339,214 @@ function mergeRouteSchemas(routeChain, key) {
7193
7339
  }
7194
7340
 
7195
7341
  // src/server/router/schemas.ts
7342
+ function decodeQueryPart(value) {
7343
+ return new URLSearchParams(`value=${value}`).get("value") ?? "";
7344
+ }
7345
+ function parseArrayQueryValue(raw, decoded, repeated) {
7346
+ const rawBracketed = raw.startsWith("[") && raw.endsWith("]");
7347
+ const decodedBracketed = decoded.startsWith("[") && decoded.endsWith("]");
7348
+ if (repeated && !rawBracketed && !decodedBracketed) {
7349
+ return [decoded];
7350
+ }
7351
+ if (decoded === "[]") {
7352
+ return [];
7353
+ }
7354
+ if (rawBracketed) {
7355
+ return raw.slice(1, -1).split(",").map(decodeQueryPart);
7356
+ }
7357
+ if (decodedBracketed) {
7358
+ return decoded.slice(1, -1).split(",");
7359
+ }
7360
+ return raw.includes(",") ? raw.split(",").map(decodeQueryPart) : [decoded];
7361
+ }
7362
+ function parseQueryFromURL(search, arrayKeys) {
7363
+ const query = Object.create(null);
7364
+ if (!arrayKeys) {
7365
+ for (const [key, value] of new URLSearchParams(search)) {
7366
+ query[key] = value;
7367
+ }
7368
+ return query;
7369
+ }
7370
+ for (const pair of search.slice(1).split("&")) {
7371
+ const entry = new URLSearchParams(pair).entries().next().value;
7372
+ if (!entry) {
7373
+ continue;
7374
+ }
7375
+ const [key, value] = entry;
7376
+ if (!arrayKeys[key]) {
7377
+ query[key] = value;
7378
+ continue;
7379
+ }
7380
+ const equalIndex = pair.indexOf("=");
7381
+ const rawValue = equalIndex === -1 ? "" : pair.slice(equalIndex + 1);
7382
+ const previous = query[key];
7383
+ const values = parseArrayQueryValue(rawValue, value, Array.isArray(previous));
7384
+ if (Array.isArray(previous)) {
7385
+ previous.push(...values);
7386
+ } else {
7387
+ query[key] = values;
7388
+ }
7389
+ }
7390
+ return query;
7391
+ }
7392
+ function isObjectSchema(schema) {
7393
+ return !!schema && typeof schema === "object";
7394
+ }
7395
+ function isStandardSchema(schema) {
7396
+ return isObjectSchema(schema) && "~standard" in schema;
7397
+ }
7398
+ function collectQueryArrayKeys(schema) {
7399
+ return collectQueryKeys(schema, "array");
7400
+ }
7401
+ function collectQueryObjectKeys(schema) {
7402
+ return collectQueryKeys(schema, "object");
7403
+ }
7404
+ function collectQueryKeys(schema, type) {
7405
+ if (!isObjectSchema(schema)) {
7406
+ return;
7407
+ }
7408
+ const keys = {};
7409
+ if (isObjectSchema(schema.properties)) {
7410
+ for (const [key, value] of Object.entries(schema.properties)) {
7411
+ if (hasSchemaType(value, type)) {
7412
+ keys[key] = 1;
7413
+ }
7414
+ }
7415
+ }
7416
+ for (const keyword of ["allOf", "anyOf"]) {
7417
+ const members = schema[keyword];
7418
+ if (!Array.isArray(members)) {
7419
+ continue;
7420
+ }
7421
+ for (const member of members) {
7422
+ Object.assign(keys, collectQueryKeys(member, type));
7423
+ }
7424
+ }
7425
+ return Object.keys(keys).length > 0 ? keys : undefined;
7426
+ }
7427
+ function hasSchemaType(schema, type) {
7428
+ if (!isObjectSchema(schema)) {
7429
+ return false;
7430
+ }
7431
+ if (schema.type === type) {
7432
+ return true;
7433
+ }
7434
+ for (const keyword of ["allOf", "anyOf"]) {
7435
+ const members = schema[keyword];
7436
+ if (Array.isArray(members) && members.some((member) => hasSchemaType(member, type))) {
7437
+ return true;
7438
+ }
7439
+ }
7440
+ return false;
7441
+ }
7442
+ function parseJsonQueryObjects(query, objectKeys) {
7443
+ if (!objectKeys) {
7444
+ return query;
7445
+ }
7446
+ const parsed = { ...query };
7447
+ for (const key of Object.keys(objectKeys)) {
7448
+ const value = parsed[key];
7449
+ if (typeof value !== "string") {
7450
+ continue;
7451
+ }
7452
+ try {
7453
+ parsed[key] = JSON.parse(value);
7454
+ } catch {
7455
+ parsed[key] = value;
7456
+ }
7457
+ }
7458
+ return parsed;
7459
+ }
7460
+ function coerceUnionValue(members, value) {
7461
+ for (const member of members) {
7462
+ const candidate = coerceSchemaValue(member, value);
7463
+ const validator = getSchemaValidator(member);
7464
+ if (validator?.Check(candidate)) {
7465
+ return candidate;
7466
+ }
7467
+ }
7468
+ return value;
7469
+ }
7470
+ function coerceObjectValue(properties, value) {
7471
+ const coerced = { ...value };
7472
+ for (const [key, propertySchema] of Object.entries(properties)) {
7473
+ if (key in coerced) {
7474
+ coerced[key] = coerceSchemaValue(propertySchema, coerced[key]);
7475
+ }
7476
+ }
7477
+ return coerced;
7478
+ }
7479
+ function coerceStringValue(schema, value) {
7480
+ if (value.length === 0) {
7481
+ return value;
7482
+ }
7483
+ if (schema.type === "boolean") {
7484
+ if (value === "true") {
7485
+ return true;
7486
+ }
7487
+ if (value === "false") {
7488
+ return false;
7489
+ }
7490
+ return value;
7491
+ }
7492
+ if (schema.type === "number" || schema.type === "integer") {
7493
+ const number = Number(value);
7494
+ if (Number.isFinite(number) && (schema.type !== "integer" || Number.isInteger(number))) {
7495
+ return number;
7496
+ }
7497
+ }
7498
+ return value;
7499
+ }
7500
+ function coerceSchemaValue(schema, value) {
7501
+ if (!isObjectSchema(schema)) {
7502
+ return value;
7503
+ }
7504
+ if (Array.isArray(schema.anyOf)) {
7505
+ return coerceUnionValue(schema.anyOf, value);
7506
+ }
7507
+ if (Array.isArray(schema.allOf)) {
7508
+ return schema.allOf.reduce((candidate, member) => coerceSchemaValue(member, candidate), value);
7509
+ }
7510
+ if (schema.type === "object" && isObjectSchema(schema.properties) && isObjectSchema(value)) {
7511
+ return coerceObjectValue(schema.properties, value);
7512
+ }
7513
+ if (schema.type === "array" && Array.isArray(value)) {
7514
+ return value.map((entry) => coerceSchemaValue(schema.items, entry));
7515
+ }
7516
+ return typeof value === "string" ? coerceStringValue(schema, value) : value;
7517
+ }
7518
+ function coerceRouteInput(schema, value) {
7519
+ return coerceSchemaValue(schema, value);
7520
+ }
7521
+ async function validateRouteInput(input, schema, type) {
7522
+ const inputWithDefaults = isStandardSchema(schema) ? input : applySchemaDefaults(schema, input);
7523
+ const valueToValidate = isStandardSchema(schema) ? inputWithDefaults : coerceRouteInput(schema, inputWithDefaults);
7524
+ const validator = getSchemaValidator(schema);
7525
+ try {
7526
+ const parsed = await validator?.parse(valueToValidate, type);
7527
+ return {
7528
+ ok: true,
7529
+ value: parsed ?? valueToValidate
7530
+ };
7531
+ } catch {
7532
+ return { errors: [...validator?.Errors(valueToValidate) ?? []], ok: false };
7533
+ }
7534
+ }
7535
+ async function parseRouteQuery(url, schema) {
7536
+ if (!schema) {
7537
+ return { ok: true, query: parseQueryFromURL(url.search) };
7538
+ }
7539
+ const rawQuery = isStandardSchema(schema) ? parseQueryFromURL(url.search) : parseJsonQueryObjects(parseQueryFromURL(url.search, collectQueryArrayKeys(schema)), collectQueryObjectKeys(schema));
7540
+ const result = await validateRouteInput(rawQuery, schema, "query");
7541
+ return result.ok ? { ok: true, query: result.value } : result;
7542
+ }
7543
+ async function parseRouteParams(params, schema) {
7544
+ if (!schema) {
7545
+ return { ok: true, params };
7546
+ }
7547
+ const result = await validateRouteInput(params, schema, "params");
7548
+ return result.ok ? { ok: true, params: result.value } : result;
7549
+ }
7196
7550
  function createSearchRouteMetadata(routes) {
7197
7551
  const metadata = [];
7198
7552
  for (const route of routes) {
@@ -7208,6 +7562,23 @@ function createSearchRouteMetadata(routes) {
7208
7562
  }
7209
7563
  return metadata;
7210
7564
  }
7565
+ function applySchemaDefaults(schema, values) {
7566
+ if (!schema || typeof schema !== "object") {
7567
+ return values;
7568
+ }
7569
+ const s = schema;
7570
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
7571
+ return values;
7572
+ }
7573
+ const result = { ...values };
7574
+ const properties = s.properties;
7575
+ for (const [key, propSchema] of Object.entries(properties)) {
7576
+ if (!(key in result) && propSchema && typeof propSchema === "object" && "default" in propSchema) {
7577
+ result[key] = propSchema.default;
7578
+ }
7579
+ }
7580
+ return result;
7581
+ }
7211
7582
 
7212
7583
  // src/plugin/routes.ts
7213
7584
  init_lang_detect();
@@ -7465,7 +7836,7 @@ function findPackageRoot(sourcePath) {
7465
7836
  }
7466
7837
  function isWithinDirectory(path, directory) {
7467
7838
  const relativePath = relative4(directory, path);
7468
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
7839
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute3(relativePath));
7469
7840
  }
7470
7841
  function isFurinPackageImport(specifier) {
7471
7842
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -7483,7 +7854,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
7483
7854
  }
7484
7855
  try {
7485
7856
  const resolvedImport = realpathSync.native(Bun.resolveSync(imported.path, dirname6(dependencyPath)));
7486
- if (isAbsolute2(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative4(packageRoot, resolvedImport).split(sep).includes("node_modules")) {
7857
+ if (isAbsolute3(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative4(packageRoot, resolvedImport).split(sep).includes("node_modules")) {
7487
7858
  resolvedImports.push(resolvedImport);
7488
7859
  }
7489
7860
  } catch {}
@@ -7557,7 +7928,7 @@ async function clientRoutesSource(instance) {
7557
7928
  const module = await loadRouteModule(routeFile.sourcePath);
7558
7929
  validateRouteParams(routeFile.path, module.route?.schemas);
7559
7930
  return {
7560
- hasLoader: module.route?.loader !== undefined || module.route?.useLoaderData !== undefined,
7931
+ hasLoader: module.route?.loader !== undefined,
7561
7932
  mode: module.route?.mode ?? "ssr",
7562
7933
  pattern: routeFile.path
7563
7934
  };
@@ -7746,13 +8117,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
7746
8117
  }
7747
8118
 
7748
8119
  // src/adapter/runtime-build.ts
7749
- import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
7750
- import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute3, join as join9, relative as relative6, resolve as resolve6 } from "path";
8120
+ import { existsSync as existsSync8, realpathSync as realpathSync4, writeFileSync as writeFileSync5 } from "fs";
8121
+ import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute5, join as join9, relative as relative6, resolve as resolve8 } from "path";
7751
8122
  import { fileURLToPath as fileURLToPath5 } from "url";
7752
8123
 
7753
8124
  // src/build/client.ts
7754
- import { existsSync as existsSync6, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
7755
- import { basename as basename2, dirname as dirname7, join as join7, resolve as resolve5 } from "path";
8125
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
8126
+ import { basename as basename3, dirname as dirname9, join as join7, resolve as resolve7 } from "path";
7756
8127
 
7757
8128
  // src/plugin/transform-client.ts
7758
8129
  init_dist();
@@ -7760,13 +8131,60 @@ init_dist2();
7760
8131
  init_lang_detect();
7761
8132
  init_parser();
7762
8133
  init_dead_code_elimination();
8134
+
8135
+ // src/plugin/hmr-dependencies.ts
8136
+ init_lang_detect();
8137
+ import { readFileSync as readFileSync3 } from "fs";
8138
+ import { dirname as dirname8, isAbsolute as isAbsolute4, resolve as resolve5 } from "path";
8139
+ var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
8140
+ function hmrDependencySignature(imports, filename) {
8141
+ const routePath = resolve5(filename);
8142
+ const visited = new Set;
8143
+ const hash = new Bun.CryptoHasher("sha256");
8144
+ const visit = (specifier, importer) => {
8145
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
8146
+ return true;
8147
+ }
8148
+ const path = Bun.resolveSync(specifier, dirname8(importer));
8149
+ if (path === routePath) {
8150
+ return false;
8151
+ }
8152
+ hash.update(JSON.stringify([specifier, path]));
8153
+ if (!isAbsolute4(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
8154
+ return true;
8155
+ }
8156
+ visited.add(path);
8157
+ const source = readFileSync3(path, "utf8");
8158
+ hash.update(source);
8159
+ if (SCRIPT_FILE.test(path)) {
8160
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
8161
+ for (const dependency of transpiler.scanImports(source)) {
8162
+ if (!visit(dependency.path, path)) {
8163
+ return false;
8164
+ }
8165
+ }
8166
+ }
8167
+ return true;
8168
+ };
8169
+ try {
8170
+ for (const specifier of imports) {
8171
+ if (!visit(specifier, routePath)) {
8172
+ return;
8173
+ }
8174
+ }
8175
+ return hash.digest("hex");
8176
+ } catch {}
8177
+ }
8178
+
8179
+ // src/plugin/transform-client.ts
7763
8180
  init_transform_isomorphic();
7764
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
8181
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
7765
8182
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
7766
8183
  var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
7767
8184
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
7768
8185
  var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
7769
8186
  var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
8187
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
7770
8188
  var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7771
8189
  ["TSAsExpression", ["expression"]],
7772
8190
  ["TSInstantiationExpression", ["expression"]],
@@ -7776,7 +8194,7 @@ var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7776
8194
  ["TSTypeAssertion", ["expression"]]
7777
8195
  ]);
7778
8196
  function isFurinRouteModule(source) {
7779
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
8197
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
7780
8198
  }
7781
8199
  function importedName2(specifier) {
7782
8200
  const { imported } = specifier;
@@ -7876,8 +8294,51 @@ function chainRootIsDefineRoute(node, bindings, ancestors) {
7876
8294
  }
7877
8295
  return false;
7878
8296
  }
7879
- function removeChainedServerCalls(source, program, bindings) {
8297
+ function assertCompleteRouteChains(program, bindings, filename) {
8298
+ const namespaces = new Set;
8299
+ for (const statement of program.body) {
8300
+ if (statement.type !== "ImportDeclaration") {
8301
+ continue;
8302
+ }
8303
+ const declaration = statement;
8304
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
8305
+ continue;
8306
+ }
8307
+ for (const specifier of declaration.specifiers) {
8308
+ const name = localName2(specifier);
8309
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
8310
+ namespaces.add(name);
8311
+ }
8312
+ }
8313
+ }
8314
+ walk(program, {
8315
+ MemberExpression(node, context) {
8316
+ const object = asAstNode(node.object);
8317
+ const property = asAstNode(node.property);
8318
+ const method = property?.type === "Identifier" ? property.name : property?.value;
8319
+ if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
8320
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
8321
+ }
8322
+ if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
8323
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
8324
+ }
8325
+ },
8326
+ VariableDeclarator(node, context) {
8327
+ const initializer = asAstNode(node.init);
8328
+ if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
8329
+ return;
8330
+ }
8331
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
8332
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
8333
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
8334
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
8335
+ }
8336
+ }
8337
+ });
8338
+ }
8339
+ function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
7880
8340
  let transformed = rewriteClientImports(source, program, bindings);
8341
+ const { declarations } = collectModuleBindings(program);
7881
8342
  walk(program, {
7882
8343
  CallExpression(call, context) {
7883
8344
  const callee = asAstNode(call.callee);
@@ -7892,12 +8353,93 @@ function removeChainedServerCalls(source, program, bindings) {
7892
8353
  if (!object) {
7893
8354
  return;
7894
8355
  }
8356
+ if (property.name === "config" && Array.isArray(call.arguments)) {
8357
+ const config = asAstNode(call.arguments[0]);
8358
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8359
+ collectConfigBindings(config, declarations, configBindings);
8360
+ const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
8361
+ if (remount) {
8362
+ source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
8363
+ transformed = true;
8364
+ return;
8365
+ }
8366
+ }
8367
+ }
7895
8368
  source.remove(object.end, call.end);
7896
8369
  transformed = true;
7897
8370
  }
7898
8371
  });
7899
8372
  return transformed;
7900
8373
  }
8374
+ function collectConfigBindings(config, declarations, names) {
8375
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
8376
+ names.add(config.name);
8377
+ const declaration = declarations.get(config.name);
8378
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
8379
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8380
+ for (const property of config.properties) {
8381
+ const entry = asAstNode(property);
8382
+ if (entry?.type === "SpreadElement") {
8383
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
8384
+ }
8385
+ }
8386
+ }
8387
+ }
8388
+ function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
8389
+ if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
8390
+ visiting.add(config.name);
8391
+ configBindings.add(config.name);
8392
+ const declaration = declarations.get(config.name);
8393
+ const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
8394
+ visiting.delete(config.name);
8395
+ return result;
8396
+ }
8397
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
8398
+ throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
8399
+ }
8400
+ for (let index = config.properties.length - 1;index >= 0; index -= 1) {
8401
+ const entry = asAstNode(config.properties[index]);
8402
+ if (entry?.type === "SpreadElement") {
8403
+ const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
8404
+ if (remount) {
8405
+ return remount;
8406
+ }
8407
+ } else if (entry?.type === "Property") {
8408
+ const key = asAstNode(entry.key);
8409
+ if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
8410
+ return entry;
8411
+ }
8412
+ }
8413
+ }
8414
+ return null;
8415
+ }
8416
+ function pruneUnusedConfigBindings(source, filename, names) {
8417
+ let result = source;
8418
+ let pruned = true;
8419
+ while (pruned) {
8420
+ pruned = false;
8421
+ const code = result.toString();
8422
+ const { program } = parseSource(code, detectLangFromPath(filename));
8423
+ const references = new Set;
8424
+ walkWithAncestors(program, [], (node, ancestors) => {
8425
+ if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
8426
+ references.add(node.name);
8427
+ }
8428
+ });
8429
+ result = new MagicString(code);
8430
+ for (const statement of program.body) {
8431
+ if (statement.type !== "VariableDeclaration") {
8432
+ continue;
8433
+ }
8434
+ const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
8435
+ if (retained.length !== statement.declarations.length) {
8436
+ result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
8437
+ pruned = true;
8438
+ }
8439
+ }
8440
+ }
8441
+ return result;
8442
+ }
7901
8443
  function collectBindingNames(pattern, names) {
7902
8444
  const node = asAstNode(pattern);
7903
8445
  if (!node) {
@@ -7949,13 +8491,13 @@ function collectDeclarationBindings(declaration, declarations) {
7949
8491
  }
7950
8492
  function collectModuleBindings(program) {
7951
8493
  const declarations = new Map;
7952
- const imports = new Set;
8494
+ const imports = new Map;
7953
8495
  for (const statement of program.body) {
7954
8496
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
7955
8497
  for (const specifier of statement.specifiers) {
7956
8498
  const local = localName2(specifier);
7957
8499
  if (local) {
7958
- imports.add(local);
8500
+ imports.set(local, statement);
7959
8501
  }
7960
8502
  }
7961
8503
  continue;
@@ -8043,13 +8585,16 @@ function walkWithAncestors(value, ancestors, visitor) {
8043
8585
  }
8044
8586
  }
8045
8587
  function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8046
- if (child.type !== "Identifier" || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8588
+ const parent = ancestors.at(-1);
8589
+ 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);
8590
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8047
8591
  return;
8048
8592
  }
8049
8593
  const declaration = state.moduleBindings.declarations.get(child.name);
8050
8594
  if (!declaration) {
8051
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
8052
- state.hasUnresolvedImport = true;
8595
+ const imported = state.moduleBindings.imports.get(child.name);
8596
+ if (trackImports && imported) {
8597
+ state.imports.add(imported);
8053
8598
  }
8054
8599
  return;
8055
8600
  }
@@ -8070,13 +8615,20 @@ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8070
8615
  function collectDependencies(node, trackImports, state) {
8071
8616
  walkWithAncestors(node, [], (child, ancestors) => {
8072
8617
  collectDependencyIdentifier(child, ancestors, trackImports, state);
8618
+ if (trackImports && child.type === "ImportExpression") {
8619
+ const specifier = asAstNode(child.source)?.value;
8620
+ if (typeof specifier === "string") {
8621
+ state.dynamicImports.add(specifier);
8622
+ }
8623
+ }
8073
8624
  });
8074
8625
  }
8075
- function createHmrDataSignature(code, program, bindings) {
8626
+ function createHmrDataSignature(code, program, bindings, filename) {
8076
8627
  const serverStages = [];
8077
8628
  const dependencyState = {
8078
8629
  dependencies: new Map,
8079
- hasUnresolvedImport: false,
8630
+ dynamicImports: new Set,
8631
+ imports: new Set,
8080
8632
  importTrackedDependencies: new Set,
8081
8633
  moduleBindings: collectModuleBindings(program)
8082
8634
  };
@@ -8110,6 +8662,10 @@ function createHmrDataSignature(code, program, bindings) {
8110
8662
  });
8111
8663
  const dataSource = [
8112
8664
  ...serverStages,
8665
+ ...[...dependencyState.imports].map((imported) => ({
8666
+ source: code.slice(imported.start, imported.end),
8667
+ start: imported.start
8668
+ })),
8113
8669
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
8114
8670
  source: code.slice(dependency.start, dependency.end),
8115
8671
  start: dependency.start
@@ -8117,7 +8673,14 @@ function createHmrDataSignature(code, program, bindings) {
8117
8673
  ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
8118
8674
  `);
8119
8675
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
8120
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
8676
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
8677
+ return hash;
8678
+ }
8679
+ const dependencies = hmrDependencySignature(new Set([
8680
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
8681
+ ...dependencyState.dynamicImports
8682
+ ]), filename);
8683
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
8121
8684
  }
8122
8685
  function calledHookName(call) {
8123
8686
  const callee = asAstNode(call.callee);
@@ -8335,9 +8898,14 @@ function transformForClient(code, filename) {
8335
8898
  }
8336
8899
  let source = new MagicString(clientSource);
8337
8900
  const routeBindings = collectDefineRouteBindings(program);
8338
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
8901
+ assertCompleteRouteChains(program, routeBindings, filename);
8902
+ const configBindings = new Set;
8903
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
8339
8904
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
8340
8905
  if (removedServerCode) {
8906
+ if (configBindings.size > 0) {
8907
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
8908
+ }
8341
8909
  source = deadCodeElimination(source, code, lang);
8342
8910
  }
8343
8911
  const transformedCode = source.toString();
@@ -8356,11 +8924,16 @@ function transformForClient(code, filename) {
8356
8924
  if (originalError) {
8357
8925
  throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
8358
8926
  }
8359
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program));
8927
+ const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
8360
8928
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
8361
8929
  source.append(`
8362
8930
  if (import.meta.hot && route?.component) {
8363
8931
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
8932
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
8933
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
8934
+ configurable: true,
8935
+ value: previousSourceSignature,
8936
+ });
8364
8937
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
8365
8938
  configurable: true,
8366
8939
  value: previousDataSignature,
@@ -8376,10 +8949,14 @@ if (import.meta.hot && route?.component) {
8376
8949
  updatedRoute,
8377
8950
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
8378
8951
  );
8952
+ // An unchanged source can be re-evaluated by Bun after an import edit
8953
+ // without rerunning this transform. Its embedded dependency hash is stale.
8379
8954
  const dataChanged =
8380
8955
  previousDataSignature.startsWith("external:") ||
8381
8956
  typeof updatedDataSignature !== "string" ||
8382
8957
  updatedDataSignature.startsWith("external:") ||
8958
+ (updatedDataSignature.startsWith("imports:") &&
8959
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
8383
8960
  updatedDataSignature !== previousDataSignature;
8384
8961
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
8385
8962
  }
@@ -8503,7 +9080,7 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
8503
9080
  }).join(" ");
8504
9081
  const boundaryResult = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
8505
9082
  const pageComponentKey = JSON.stringify(`page:${resolvedPage}`);
8506
- 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} }; })`;
9083
+ 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} }; })`;
8507
9084
  const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
8508
9085
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
8509
9086
  }
@@ -8737,6 +9314,12 @@ if (__deferred && __deferred._chunks) {
8737
9314
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
8738
9315
  } as any);
8739
9316
  } else {
9317
+ // A removed active route has no match in the new development manifest.
9318
+ // Reload its document so the server can render the current 404 response.
9319
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
9320
+ window.location.reload();
9321
+ return;
9322
+ }
8740
9323
  // No match and no 404 signal \u2014 either the client bundle is out of sync
8741
9324
  // with the server (stale deploy) or the server returned something we
8742
9325
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -8814,9 +9397,65 @@ if (__deferred && __deferred._chunks) {
8814
9397
  `;
8815
9398
  }
8816
9399
 
9400
+ // src/build/preload-manifest.ts
9401
+ init_transform_client_module();
9402
+ import { existsSync as existsSync6, readFileSync as readFileSync4, realpathSync as realpathSync3, writeFileSync as writeFileSync2 } from "fs";
9403
+ import { basename as basename2, resolve as resolve6 } from "path";
9404
+ var CLIENT_MODULE_KEY_RE = /(["'`])(__FURIN_CLIENT_MODULE_[a-z0-9]+__)\1/g;
9405
+ function routeModulePaths(route) {
9406
+ const layouts = (route.routeChain ?? []).slice(1).filter((entry) => entry.layout && entry.sourcePath).map((entry) => entry.sourcePath);
9407
+ const boundaries = (route.segmentBoundaries ?? []).flatMap((segment) => [segment.errorPath, segment.notFoundPath].filter((path) => path !== undefined));
9408
+ return [route.path, ...layouts, ...boundaries];
9409
+ }
9410
+ function realPath(path) {
9411
+ return existsSync6(path) ? realpathSync3(path) : null;
9412
+ }
9413
+ function writeClientPreloadManifest(metafile, outputPaths, entryChunkPath, routes, publicPrefix) {
9414
+ const outputs = new Map(Object.entries(metafile.outputs).map(([path, output]) => [basename2(path), output]));
9415
+ const closure = (file, seen) => {
9416
+ if (!seen.has(file)) {
9417
+ seen.add(file);
9418
+ for (const imported of outputs.get(file)?.imports ?? []) {
9419
+ if (imported.kind === "import-statement") {
9420
+ closure(basename2(imported.path), seen);
9421
+ }
9422
+ }
9423
+ }
9424
+ return seen;
9425
+ };
9426
+ const entryFiles = closure(basename2(entryChunkPath), new Set);
9427
+ const hrefsOf = (file) => [...closure(file, new Set)].filter((chunk) => !entryFiles.has(chunk)).map((chunk) => `${publicPrefix}${chunk}`);
9428
+ const chunkByModule = new Map;
9429
+ for (const [file, output] of outputs) {
9430
+ const modulePath = output.entryPoint ? realPath(resolve6(output.entryPoint)) : null;
9431
+ if (modulePath !== null) {
9432
+ chunkByModule.set(modulePath, file);
9433
+ }
9434
+ }
9435
+ const routeManifest = {};
9436
+ for (const route of routes) {
9437
+ const files = routeModulePaths(route).map((path) => chunkByModule.get(realPath(path) ?? path)).filter((file) => file !== undefined);
9438
+ routeManifest[route.pattern] = [...new Set(files.flatMap(hrefsOf))];
9439
+ }
9440
+ const moduleHrefs = new Map([...chunkByModule].map(([modulePath, file]) => [clientModuleKey(modulePath), file]));
9441
+ const modules = {};
9442
+ for (const path of outputPaths.filter((output) => output.endsWith(".js"))) {
9443
+ const code = readFileSync4(path, "utf8");
9444
+ const rewritten = code.replace(CLIENT_MODULE_KEY_RE, (_match, _quote, key) => {
9445
+ const file = moduleHrefs.get(key);
9446
+ modules[key] = file === undefined ? [] : hrefsOf(file);
9447
+ return JSON.stringify(modules[key]);
9448
+ });
9449
+ if (rewritten !== code) {
9450
+ writeFileSync2(path, rewritten);
9451
+ }
9452
+ }
9453
+ return { modules, routes: routeManifest };
9454
+ }
9455
+
8817
9456
  // src/build/client.ts
8818
9457
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8819
- var ROUTER_PROVIDER_PATH = resolve5(import.meta.dir, "../client/router/provider.tsx");
9458
+ var ROUTER_PROVIDER_PATH = resolve7(import.meta.dir, "../client/router/provider.tsx");
8820
9459
  function resolveClientModuleSpecifiers(code) {
8821
9460
  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));
8822
9461
  }
@@ -8824,6 +9463,7 @@ async function buildClient(routes, {
8824
9463
  outDir,
8825
9464
  rootLayout,
8826
9465
  plugins,
9466
+ preloadRouteChunks,
8827
9467
  publicPath,
8828
9468
  basePath,
8829
9469
  clientLogging,
@@ -8835,10 +9475,10 @@ async function buildClient(routes, {
8835
9475
  }) {
8836
9476
  const dirName = clientDirName ?? "client";
8837
9477
  const clientDir = join7(outDir, dirName);
8838
- if (!existsSync6(outDir)) {
9478
+ if (!existsSync7(outDir)) {
8839
9479
  mkdirSync2(outDir, { recursive: true });
8840
9480
  }
8841
- if (!existsSync6(clientDir)) {
9481
+ if (!existsSync7(clientDir)) {
8842
9482
  mkdirSync2(clientDir, { recursive: true });
8843
9483
  }
8844
9484
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
@@ -8882,6 +9522,7 @@ async function buildClient(routes, {
8882
9522
  files: hydrateEntry.files,
8883
9523
  outdir: clientDir,
8884
9524
  target: "browser",
9525
+ env: "FURIN_PUBLIC_*",
8885
9526
  format: "esm",
8886
9527
  splitting: true,
8887
9528
  optimizeImports,
@@ -8889,7 +9530,7 @@ async function buildClient(routes, {
8889
9530
  reactCompilerOutputMode: "client",
8890
9531
  minify: true,
8891
9532
  sourcemap: "none",
8892
- metafile: metafilePath !== undefined,
9533
+ metafile: true,
8893
9534
  naming: {
8894
9535
  entry: "[name]-[hash].[ext]",
8895
9536
  chunk: "[name]-[hash].[ext]"
@@ -8909,16 +9550,17 @@ async function buildClient(routes, {
8909
9550
  "@teyik0/furin/search": SEARCH_MODULE_PATH
8910
9551
  },
8911
9552
  define: {
9553
+ ...Object.fromEntries(Object.entries(process.env).filter(([name, value]) => name.startsWith("FURIN_PUBLIC_") && value !== undefined).map(([name, value]) => [`process.env.${name}`, JSON.stringify(value)])),
8912
9554
  "process.env.NODE_ENV": JSON.stringify("production")
8913
9555
  }
8914
9556
  };
8915
9557
  const result = await runBunBuild(clientBuildConfig);
9558
+ if (result.metafile === undefined) {
9559
+ throw new Error("[furin] client build did not produce the requested metafile");
9560
+ }
8916
9561
  if (metafilePath !== undefined) {
8917
- if (result.metafile === undefined) {
8918
- throw new Error("[furin] client build did not produce the requested metafile");
8919
- }
8920
- mkdirSync2(dirname7(metafilePath), { recursive: true });
8921
- writeFileSync2(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
9562
+ mkdirSync2(dirname9(metafilePath), { recursive: true });
9563
+ writeFileSync3(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8922
9564
  `);
8923
9565
  console.log(`[furin] Client metafile: ${metafilePath}`);
8924
9566
  }
@@ -8936,10 +9578,11 @@ async function buildClient(routes, {
8936
9578
  } else {
8937
9579
  publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
8938
9580
  }
8939
- const entryChunk = `${publicPrefix}${basename2(entryOutput.path)}`;
8940
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename2(o.path)}`);
9581
+ const entryChunk = `${publicPrefix}${basename3(entryOutput.path)}`;
9582
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename3(o.path)}`);
9583
+ const preloadManifest = writeClientPreloadManifest(result.metafile, result.outputs.map((output) => output.path), entryOutput.path, preloadRouteChunks === false ? [] : routes, publicPrefix);
8941
9584
  console.log("[furin] Production client build complete");
8942
- return { entryChunk, cssChunks };
9585
+ return { entryChunk, cssChunks, preloadManifest };
8943
9586
  }
8944
9587
 
8945
9588
  // src/server/render/assemble.ts
@@ -8968,6 +9611,65 @@ async function streamToString(stream) {
8968
9611
  html += decoder.decode();
8969
9612
  return html;
8970
9613
  }
9614
+ // src/shared/sync-query.ts
9615
+ function mergeQuerySeeds(target, incoming) {
9616
+ for (const seed of incoming) {
9617
+ const index = target.findIndex((existing) => existing.url === seed.url);
9618
+ const previous = target[index];
9619
+ const bindings = [...seed.bindings ?? []];
9620
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
9621
+ for (const binding of previous.bindings ?? []) {
9622
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
9623
+ bindings.push(binding);
9624
+ }
9625
+ }
9626
+ }
9627
+ const merged = { ...seed, bindings };
9628
+ if (index < 0) {
9629
+ target.push(merged);
9630
+ } else {
9631
+ target[index] = merged;
9632
+ }
9633
+ }
9634
+ }
9635
+ function queryTagsFromData(data) {
9636
+ return (data.__furinQueries ?? []).map((seed) => queryTag(seed.identity));
9637
+ }
9638
+ var PREFIX = "__furin.query:";
9639
+ function queryTag(identity) {
9640
+ for (const [key, value] of Object.entries(identity.scope)) {
9641
+ if (value === undefined) {
9642
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
9643
+ }
9644
+ }
9645
+ return PREFIX + JSON.stringify([
9646
+ identity.id,
9647
+ Object.entries(identity.scope).sort(([a], [b]) => {
9648
+ if (a === b) {
9649
+ return 0;
9650
+ }
9651
+ return a < b ? -1 : 1;
9652
+ })
9653
+ ]);
9654
+ }
9655
+ function queryFromTag(tag) {
9656
+ if (!tag.startsWith(PREFIX)) {
9657
+ return;
9658
+ }
9659
+ try {
9660
+ const value = JSON.parse(tag.slice(PREFIX.length));
9661
+ 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"))) {
9662
+ return;
9663
+ }
9664
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
9665
+ } catch {}
9666
+ }
9667
+ function queryUrl(url, origin) {
9668
+ const parsed = new URL(url, origin);
9669
+ parsed.searchParams.sort();
9670
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
9671
+ }
9672
+
8971
9673
  // src/shared/utils/index.ts
8972
9674
  function collectRouteChainFromRoute(route) {
8973
9675
  const chain = [];
@@ -9090,8 +9792,7 @@ function setSSGCache(key, entry) {
9090
9792
  }
9091
9793
 
9092
9794
  // src/server/render/ssr.ts
9093
- import { createElement as createElement6 } from "react";
9094
- import { renderToReadableStream } from "react-dom/server";
9795
+ import { createElement as createElement7 } from "react";
9095
9796
 
9096
9797
  // ../../node_modules/.bun/seroval@1.6.7/node_modules/seroval/dist/dev/index.js
9097
9798
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
@@ -11196,6 +11897,7 @@ function fromCrossJSON(source, options) {
11196
11897
 
11197
11898
  // src/client/document.tsx
11198
11899
  import { createContext, createElement, useContext } from "react";
11900
+ import { preloadModule } from "react-dom";
11199
11901
  import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
11200
11902
  var DocumentContext = createContext(null);
11201
11903
  function serializeJson(value) {
@@ -11210,29 +11912,39 @@ function DocumentProvider({
11210
11912
  children
11211
11913
  }, undefined, false, undefined, this);
11212
11914
  }
11213
- function renderMeta(meta, index) {
11915
+ function renderMeta(meta, key) {
11214
11916
  if ("title" in meta) {
11215
11917
  return /* @__PURE__ */ jsxDEV("title", {
11216
11918
  children: meta.title
11217
- }, `title:${index}`, false, undefined, this);
11919
+ }, key, false, undefined, this);
11218
11920
  }
11219
11921
  if ("script:ld+json" in meta) {
11220
11922
  return /* @__PURE__ */ jsxDEV("script", {
11221
11923
  dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
11222
11924
  type: "application/ld+json"
11223
- }, `json-ld:${index}`, false, undefined, this);
11925
+ }, key, false, undefined, this);
11224
11926
  }
11225
11927
  if ("tagName" in meta) {
11226
11928
  const { tagName, ...attributes } = meta;
11227
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
11929
+ return createElement(tagName, { ...attributes, key });
11228
11930
  }
11229
- return createElement("meta", { ...meta, key: `meta:${index}` });
11931
+ return createElement("meta", { ...meta, key });
11230
11932
  }
11231
11933
  function HeadContent() {
11232
11934
  const state = useContext(DocumentContext);
11233
11935
  if (state === null) {
11234
11936
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
11235
11937
  }
11938
+ for (const href of state.assets.modulePreloads ?? []) {
11939
+ preloadModule(href, { as: "script", nonce: state.nonce });
11940
+ }
11941
+ const occurrences = new Map;
11942
+ const descriptorKey = (descriptor) => {
11943
+ const identity = JSON.stringify(descriptor);
11944
+ const occurrence = occurrences.get(identity) ?? 0;
11945
+ occurrences.set(identity, occurrence + 1);
11946
+ return `${identity}:${occurrence}`;
11947
+ };
11236
11948
  return /* @__PURE__ */ jsxDEV(Fragment, {
11237
11949
  children: [
11238
11950
  state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
@@ -11265,20 +11977,20 @@ function HeadContent() {
11265
11977
  href,
11266
11978
  rel: "stylesheet"
11267
11979
  }, href, false, undefined, this)),
11268
- state.head?.meta?.map(renderMeta),
11269
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV("link", {
11980
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
11981
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV("link", {
11270
11982
  ...link
11271
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
11272
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV("script", {
11983
+ }, descriptorKey(link), false, undefined, this)),
11984
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV("script", {
11273
11985
  ...attributes,
11274
- dangerouslySetInnerHTML: children === undefined ? undefined : { __html: children },
11275
- nonce: state.nonce ?? attributes.nonce
11276
- }, `script:${index}`, false, undefined, this)),
11277
- state.head?.styles?.map(({ children, type }, index) => /* @__PURE__ */ jsxDEV("style", {
11986
+ nonce: state.nonce ?? attributes.nonce,
11987
+ children
11988
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
11989
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV("style", {
11278
11990
  dangerouslySetInnerHTML: { __html: children },
11279
11991
  nonce: state.nonce,
11280
11992
  type
11281
- }, `style:${index}`, false, undefined, this))
11993
+ }, descriptorKey({ children, type }), false, undefined, this))
11282
11994
  ]
11283
11995
  }, undefined, true, undefined, this);
11284
11996
  }
@@ -11347,7 +12059,7 @@ function FurinDocumentFallback({ children }) {
11347
12059
  }
11348
12060
 
11349
12061
  // src/client/router/context.ts
11350
- import { createContext as createContext2, useContext as useContext2 } from "react";
12062
+ import { createContext as createContext2, useCallback, useContext as useContext2, useMemo } from "react";
11351
12063
 
11352
12064
  // src/client/router/link-utils.ts
11353
12065
  function navigationHrefPolicy(href, currentOrigin) {
@@ -11437,7 +12149,7 @@ var CLIENT_FALLBACK_ROUTER = {
11437
12149
  search: {},
11438
12150
  searchRoutes: []
11439
12151
  };
11440
- function useRouter() {
12152
+ function useRouterContext() {
11441
12153
  const ctx = useContext2(RouterContext);
11442
12154
  return ctx ?? CLIENT_FALLBACK_ROUTER;
11443
12155
  }
@@ -11445,7 +12157,7 @@ function useRouter() {
11445
12157
  // src/client/router/search-store.ts
11446
12158
  import { createContext as createContext3 } from "react";
11447
12159
  function searchSnapshotChanged(a, b) {
11448
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
12160
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
11449
12161
  }
11450
12162
  function createSearchStore(initialSnapshot) {
11451
12163
  let snapshot = initialSnapshot;
@@ -11482,6 +12194,7 @@ function createSearchStore(initialSnapshot) {
11482
12194
  function searchSnapshotFromRouterContext(context) {
11483
12195
  return {
11484
12196
  currentHref: context.currentHref,
12197
+ currentPattern: context.currentPattern,
11485
12198
  navigate: context.navigate,
11486
12199
  search: context.search,
11487
12200
  searchRoutes: context.searchRoutes
@@ -11489,6 +12202,7 @@ function searchSnapshotFromRouterContext(context) {
11489
12202
  }
11490
12203
  var FALLBACK_SEARCH_STORE = createSearchStore({
11491
12204
  currentHref: "/",
12205
+ currentPattern: undefined,
11492
12206
  navigate: (href, _opts) => {
11493
12207
  if (typeof window !== "undefined") {
11494
12208
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -11766,9 +12480,292 @@ function serializeRouteFrames(data, deferredKeys) {
11766
12480
  // src/server/render/ssr.ts
11767
12481
  init_context_logger();
11768
12482
  init_instance();
11769
-
11770
12483
  // src/server/render/document.tsx
11771
12484
  import { createElement as createElement3 } from "react";
12485
+
12486
+ // src/client/query.tsx
12487
+ import {
12488
+ createContext as createContext4,
12489
+ useCallback as useCallback2,
12490
+ useContext as useContext3,
12491
+ useEffect,
12492
+ useSyncExternalStore
12493
+ } from "react";
12494
+
12495
+ // src/client/query-store.ts
12496
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
12497
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
12498
+ var environmentGlobal = globalThis;
12499
+ function setServerQueryEnvironment(read) {
12500
+ environmentGlobal[SERVER_ENVIRONMENT] = read;
12501
+ }
12502
+ function currentQueryEnvironment() {
12503
+ return environmentGlobal[SERVER_ENVIRONMENT]?.();
12504
+ }
12505
+ class QueryStore {
12506
+ entries = new Map;
12507
+ listeners = new Set;
12508
+ revisionValue = 0;
12509
+ projections = new Set;
12510
+ session;
12511
+ epoch = 0;
12512
+ origin;
12513
+ constructor(origin) {
12514
+ this.origin = origin;
12515
+ }
12516
+ key(url) {
12517
+ const absolute = new URL(url, this.origin).href;
12518
+ return queryUrl(absolute, undefined);
12519
+ }
12520
+ entry(url) {
12521
+ const key = this.key(url);
12522
+ let entry = this.entries.get(key);
12523
+ if (!entry) {
12524
+ entry = {
12525
+ base: undefined,
12526
+ listeners: new Set,
12527
+ snapshot: { data: undefined, error: null, isFetching: false },
12528
+ stale: true,
12529
+ version: 0
12530
+ };
12531
+ this.entries.set(key, entry);
12532
+ }
12533
+ return entry;
12534
+ }
12535
+ publish(entry) {
12536
+ let data = entry.base;
12537
+ for (const projection of this.projections) {
12538
+ const transform = projection.transforms.get(entry);
12539
+ if (transform && data !== undefined) {
12540
+ data = transform(data);
12541
+ }
12542
+ }
12543
+ entry.snapshot = { ...entry.snapshot, data };
12544
+ for (const listener of entry.listeners) {
12545
+ listener();
12546
+ }
12547
+ this.revisionValue += 1;
12548
+ for (const listener of this.listeners) {
12549
+ listener();
12550
+ }
12551
+ }
12552
+ revision = () => this.revisionValue;
12553
+ subscribeAll = (listener) => {
12554
+ this.listeners.add(listener);
12555
+ return () => this.listeners.delete(listener);
12556
+ };
12557
+ observe(url, result, epoch, version) {
12558
+ const existing = this.entries.get(this.key(url));
12559
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
12560
+ return;
12561
+ }
12562
+ const header = result.response?.headers.get("x-furin-query");
12563
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
12564
+ if (identity) {
12565
+ this.setSession(identity.session);
12566
+ }
12567
+ const entry = this.entry(url);
12568
+ entry.base = result.data;
12569
+ entry.version += 1;
12570
+ entry.identity = identity;
12571
+ entry.local = result.local ?? result.response?.url === "";
12572
+ entry.stale = false;
12573
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
12574
+ for (const projection of this.projections) {
12575
+ if (!projection.pending) {
12576
+ projection.transforms.delete(entry);
12577
+ if (projection.transforms.size === 0) {
12578
+ this.projections.delete(projection);
12579
+ projection.onRemove?.();
12580
+ }
12581
+ }
12582
+ }
12583
+ this.publish(entry);
12584
+ if (this.entries.size > 100) {
12585
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
12586
+ if (oldest) {
12587
+ this.entries.delete(oldest[0]);
12588
+ }
12589
+ }
12590
+ }
12591
+ setSession(session) {
12592
+ if (this.session !== undefined && this.session !== session) {
12593
+ this.epoch += 1;
12594
+ for (const projection of this.projections) {
12595
+ projection.onRemove?.();
12596
+ }
12597
+ this.projections.clear();
12598
+ for (const entry of this.entries.values()) {
12599
+ entry.base = undefined;
12600
+ entry.identity = undefined;
12601
+ entry.stale = true;
12602
+ entry.version += 1;
12603
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12604
+ this.publish(entry);
12605
+ }
12606
+ }
12607
+ this.session = session;
12608
+ }
12609
+ generation() {
12610
+ return this.epoch;
12611
+ }
12612
+ version(url) {
12613
+ return this.entry(url).version;
12614
+ }
12615
+ snapshot(url) {
12616
+ return this.entry(url).snapshot;
12617
+ }
12618
+ subscribe(url, listener) {
12619
+ const entry = this.entry(url);
12620
+ entry.listeners.add(listener);
12621
+ return () => entry.listeners.delete(listener);
12622
+ }
12623
+ bind(url, load, client) {
12624
+ const entry = this.entry(url);
12625
+ if (client && entry.client && client !== entry.client) {
12626
+ entry.base = undefined;
12627
+ entry.identity = undefined;
12628
+ entry.stale = true;
12629
+ entry.version += 1;
12630
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12631
+ for (const projection of this.projections) {
12632
+ projection.transforms.delete(entry);
12633
+ }
12634
+ }
12635
+ entry.client = client ?? entry.client;
12636
+ entry.load = load;
12637
+ }
12638
+ pending(entry) {
12639
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
12640
+ }
12641
+ fetch(url) {
12642
+ const entry = this.entry(url);
12643
+ if (entry.promise) {
12644
+ return entry.promise;
12645
+ }
12646
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
12647
+ return Promise.resolve();
12648
+ }
12649
+ const { version } = entry;
12650
+ const { epoch } = this;
12651
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
12652
+ this.publish(entry);
12653
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
12654
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
12655
+ return;
12656
+ }
12657
+ if (result.error === null) {
12658
+ this.observe(url, result, epoch);
12659
+ } else {
12660
+ entry.snapshot = { ...entry.snapshot, error: result.error };
12661
+ }
12662
+ }).catch((error) => {
12663
+ if (epoch === this.epoch && version === entry.version) {
12664
+ entry.snapshot = { ...entry.snapshot, error };
12665
+ }
12666
+ }).finally(() => {
12667
+ entry.promise = undefined;
12668
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
12669
+ this.publish(entry);
12670
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
12671
+ this.fetch(url);
12672
+ }
12673
+ });
12674
+ return entry.promise;
12675
+ }
12676
+ invalidate(identities) {
12677
+ const tags = new Set(identities.map(queryTag));
12678
+ let affected = false;
12679
+ for (const [url, entry] of this.entries) {
12680
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
12681
+ affected = true;
12682
+ this.invalidateEntry(url, entry);
12683
+ }
12684
+ }
12685
+ return affected;
12686
+ }
12687
+ invalidateEntry(url, entry) {
12688
+ entry.stale = true;
12689
+ entry.version += 1;
12690
+ if (entry.listeners.size > 0) {
12691
+ this.fetch(url);
12692
+ }
12693
+ }
12694
+ invalidateAll() {
12695
+ for (const [url, entry] of this.entries) {
12696
+ this.invalidateEntry(url, entry);
12697
+ }
12698
+ }
12699
+ begin() {
12700
+ return { pending: true, transforms: new Map };
12701
+ }
12702
+ update(projection, url, transform) {
12703
+ const entry = this.entries.get(this.key(url));
12704
+ if (!entry || entry.base === undefined) {
12705
+ return;
12706
+ }
12707
+ const previous = projection.transforms.get(entry);
12708
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
12709
+ entry.version += 1;
12710
+ this.projections.add(projection);
12711
+ this.publish(entry);
12712
+ }
12713
+ finish(projection, outcome) {
12714
+ projection.pending = false;
12715
+ const entries = [...projection.transforms.keys()];
12716
+ if (outcome === "error") {
12717
+ this.projections.delete(projection);
12718
+ projection.onRemove?.();
12719
+ }
12720
+ for (const entry of entries) {
12721
+ this.publish(entry);
12722
+ if (outcome !== "error") {
12723
+ entry.stale = true;
12724
+ }
12725
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
12726
+ if (url && entry.stale) {
12727
+ this.fetch(url);
12728
+ }
12729
+ }
12730
+ }
12731
+ dehydrate() {
12732
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
12733
+ }
12734
+ seedUrl(seed, localOrigin) {
12735
+ const original = new URL(seed.url, this.origin);
12736
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
12737
+ }
12738
+ captureHydration() {
12739
+ const { epoch } = this;
12740
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
12741
+ return (seeds, localOrigin) => {
12742
+ if (epoch === this.epoch) {
12743
+ this.hydrate(seeds.filter((seed) => {
12744
+ const url = this.seedUrl(seed, localOrigin);
12745
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
12746
+ }), localOrigin);
12747
+ }
12748
+ };
12749
+ }
12750
+ hydrate(seeds, localOrigin) {
12751
+ for (const seed of seeds) {
12752
+ const url = this.seedUrl(seed, localOrigin);
12753
+ this.observe(url, {
12754
+ data: seed.data,
12755
+ error: null,
12756
+ identity: seed.identity,
12757
+ local: seed.local ?? false
12758
+ }, this.epoch);
12759
+ }
12760
+ }
12761
+ }
12762
+
12763
+ // src/client/query.tsx
12764
+ var QUERY_CONTEXT = Symbol.for("furin.query.context.v1");
12765
+ var contextGlobal = globalThis;
12766
+ var QueryStoreContext = contextGlobal[QUERY_CONTEXT] ??= createContext4(null);
12767
+
12768
+ // src/server/render/document.tsx
11772
12769
  init_instance();
11773
12770
  init_config();
11774
12771
  function withDocumentState(element, assets, head, data, nonce) {
@@ -11787,11 +12784,13 @@ function withDocumentState(element, assets, head, data, nonce) {
11787
12784
  routeFrames,
11788
12785
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
11789
12786
  };
11790
- return createElement3(DocumentProvider, { value: state }, element);
12787
+ const queries = new QueryStore(undefined);
12788
+ queries.hydrate(data?.__furinQueries ?? []);
12789
+ return createElement3(DocumentProvider, { value: state }, createElement3(QueryStoreContext.Provider, { value: queries }, element));
11791
12790
  }
11792
12791
 
11793
12792
  // src/server/render/element.tsx
11794
- import { createElement as createElement5 } from "react";
12793
+ import { createElement as createElement6 } from "react";
11795
12794
 
11796
12795
  // src/client/boundaries.tsx
11797
12796
  import { Component, Fragment as Fragment2 } from "react";
@@ -11821,7 +12820,57 @@ function isNotFoundError(err) {
11821
12820
  }
11822
12821
 
11823
12822
  // src/client/link.tsx
11824
- import { createElement as createElement4, useCallback, useEffect, useRef } from "react";
12823
+ import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef } from "react";
12824
+
12825
+ // src/shared/page-key.ts
12826
+ function identityValue(value) {
12827
+ return Object.is(value, -0) ? "-0" : String(value);
12828
+ }
12829
+ function pageKey(pattern, data, remountDeps) {
12830
+ const { params, query } = data;
12831
+ if (remountDeps) {
12832
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
12833
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
12834
+ }
12835
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
12836
+ if (left < right) {
12837
+ return -1;
12838
+ }
12839
+ return left > right ? 1 : 0;
12840
+ });
12841
+ return JSON.stringify([
12842
+ pattern,
12843
+ entries.map(([name, value]) => [
12844
+ name,
12845
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
12846
+ ])
12847
+ ]);
12848
+ }
12849
+
12850
+ // src/client/route-api.tsx
12851
+ import { createContext as createContext5, createElement as createElement4, useContext as useContext4 } from "react";
12852
+ var RESERVED_RENDER_KEYS = new Set([
12853
+ "catch",
12854
+ "children",
12855
+ "finally",
12856
+ "key",
12857
+ "ref",
12858
+ "then",
12859
+ "toJSON"
12860
+ ]);
12861
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
12862
+ var contextGlobal2 = globalThis;
12863
+ var RouteContext = contextGlobal2[ROUTE_CONTEXT] ??= createContext5(null);
12864
+ function withRouteSnapshot(element, pattern, props) {
12865
+ const {
12866
+ params,
12867
+ path: _path,
12868
+ query: _query,
12869
+ ...data
12870
+ } = props;
12871
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
12872
+ return createElement4(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
12873
+ }
11825
12874
 
11826
12875
  // src/client/server-error.ts
11827
12876
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
@@ -11839,6 +12888,96 @@ class FurinServerError extends Error {
11839
12888
  function isFurinServerError(err) {
11840
12889
  return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
11841
12890
  }
12891
+
12892
+ // src/shared/query-bindings.ts
12893
+ function isContainer(value) {
12894
+ if (!value || typeof value !== "object") {
12895
+ return false;
12896
+ }
12897
+ const prototype = Object.getPrototypeOf(value);
12898
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
12899
+ }
12900
+ function bindQueryData(data, seeds) {
12901
+ return seeds.map((seed) => {
12902
+ const sources = new WeakMap;
12903
+ const index = (value, path) => {
12904
+ if (!isContainer(value) || sources.has(value)) {
12905
+ return;
12906
+ }
12907
+ sources.set(value, path);
12908
+ if (!Array.isArray(value)) {
12909
+ for (const [key, child] of Object.entries(value)) {
12910
+ index(child, [...path, key]);
12911
+ }
12912
+ }
12913
+ };
12914
+ index(seed.data, []);
12915
+ const bindings = [];
12916
+ const visiting = new WeakSet;
12917
+ const visit = (value, target) => {
12918
+ if (!isContainer(value) || visiting.has(value)) {
12919
+ return;
12920
+ }
12921
+ const source = sources.get(value);
12922
+ if (source) {
12923
+ bindings.push({ source, target });
12924
+ return;
12925
+ }
12926
+ visiting.add(value);
12927
+ for (const [key, child] of Object.entries(value)) {
12928
+ visit(child, [...target, key]);
12929
+ }
12930
+ visiting.delete(value);
12931
+ };
12932
+ visit(data, []);
12933
+ return { ...seed, bindings };
12934
+ });
12935
+ }
12936
+ function replace(value, path, next) {
12937
+ const [key, ...rest] = path;
12938
+ if (key === undefined) {
12939
+ return next;
12940
+ }
12941
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
12942
+ return value;
12943
+ }
12944
+ const child = replace(value[key], rest, next);
12945
+ if (child === value[key]) {
12946
+ return value;
12947
+ }
12948
+ const copy = Array.isArray(value) ? [...value] : { ...value };
12949
+ Object.defineProperty(copy, key, {
12950
+ configurable: true,
12951
+ enumerable: true,
12952
+ value: child,
12953
+ writable: true
12954
+ });
12955
+ return copy;
12956
+ }
12957
+ function isDeferredTarget(data, target) {
12958
+ const [key] = target;
12959
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
12960
+ }
12961
+ function projectQueryData(data, seeds, read) {
12962
+ let projected = data;
12963
+ for (const seed of seeds) {
12964
+ const snapshot = read(seed);
12965
+ if (snapshot === undefined) {
12966
+ continue;
12967
+ }
12968
+ for (const binding of seed.bindings ?? []) {
12969
+ if (isDeferredTarget(data, binding.target)) {
12970
+ continue;
12971
+ }
12972
+ let value = snapshot;
12973
+ for (const key of binding.source) {
12974
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
12975
+ }
12976
+ projected = replace(projected, binding.target, value);
12977
+ }
12978
+ }
12979
+ return projected;
12980
+ }
11842
12981
  // src/client/link.tsx
11843
12982
  function computeLinkView({
11844
12983
  to,
@@ -11888,7 +13027,7 @@ function LinkInteractive({
11888
13027
  href: _href,
11889
13028
  ...anchorProps
11890
13029
  }) {
11891
- const router2 = useRouter();
13030
+ const router2 = useRouterContext();
11892
13031
  const anchorRef = useRef(null);
11893
13032
  const intentTimerRef = useRef(null);
11894
13033
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -11896,15 +13035,15 @@ function LinkInteractive({
11896
13035
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
11897
13036
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
11898
13037
  const { prefetch } = router2;
11899
- const triggerPrefetch = useCallback(() => {
13038
+ const triggerPrefetch = useCallback3(() => {
11900
13039
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
11901
13040
  }, [prefetch, logicalHref, effectiveStaleTime]);
11902
- useEffect(() => {
13041
+ useEffect2(() => {
11903
13042
  if (effectivePreload === "render") {
11904
13043
  triggerPrefetch();
11905
13044
  }
11906
13045
  }, [effectivePreload, triggerPrefetch]);
11907
- useEffect(() => {
13046
+ useEffect2(() => {
11908
13047
  if (effectivePreload !== "viewport" || !anchorRef.current) {
11909
13048
  return;
11910
13049
  }
@@ -11917,7 +13056,7 @@ function LinkInteractive({
11917
13056
  observer.observe(anchorRef.current);
11918
13057
  return () => observer.disconnect();
11919
13058
  }, [effectivePreload, triggerPrefetch]);
11920
- useEffect(() => () => {
13059
+ useEffect2(() => () => {
11921
13060
  if (intentTimerRef.current !== null) {
11922
13061
  clearTimeout(intentTimerRef.current);
11923
13062
  intentTimerRef.current = null;
@@ -11971,7 +13110,7 @@ function LinkInteractive({
11971
13110
  triggerPrefetch();
11972
13111
  }
11973
13112
  };
11974
- return createElement4("a", {
13113
+ return createElement5("a", {
11975
13114
  "data-furin-link": true,
11976
13115
  href,
11977
13116
  onClick: handleClick,
@@ -12022,7 +13161,7 @@ function renderLinkElement(props, router2) {
12022
13161
  href: _href,
12023
13162
  ...anchorProps
12024
13163
  } = props;
12025
- return createElement4("a", {
13164
+ return createElement5("a", {
12026
13165
  "data-furin-link": true,
12027
13166
  href,
12028
13167
  ...isActive ? { "data-status": "active" } : {},
@@ -12033,11 +13172,11 @@ function renderLinkElement(props, router2) {
12033
13172
  }
12034
13173
  function Link(props) {
12035
13174
  if (typeof window === "undefined") {
12036
- return createElement4(RouterContext.Consumer, {
13175
+ return createElement5(RouterContext.Consumer, {
12037
13176
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
12038
13177
  });
12039
13178
  }
12040
- return createElement4(LinkInteractive, props);
13179
+ return createElement5(LinkInteractive, props);
12041
13180
  }
12042
13181
 
12043
13182
  // src/client/default-screens.tsx
@@ -12443,7 +13582,10 @@ function wrapSegmentBoundaries(inner, segment, options) {
12443
13582
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
12444
13583
  function buildElement(route, data, rootLayout) {
12445
13584
  const Component = route.page.component;
12446
- let element = createElement5(Component, data);
13585
+ let element = createElement6(Component, {
13586
+ ...data,
13587
+ key: pageKey(route.pattern, data, route.page._route.remountDeps)
13588
+ });
12447
13589
  const byDepth = new Map;
12448
13590
  const legacyRoute = route;
12449
13591
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
@@ -12454,22 +13596,22 @@ function buildElement(route, data, rootLayout) {
12454
13596
  const routeEntry = route.routeChain[i];
12455
13597
  if (routeEntry?.layout) {
12456
13598
  const Layout = routeEntry.layout;
12457
- element = createElement5(Layout, data, element);
13599
+ element = createElement6(Layout, data, element);
12458
13600
  }
12459
13601
  }
12460
13602
  element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
12461
13603
  if (rootLayout.layout) {
12462
13604
  const RootLayoutComponent = rootLayout.layout;
12463
- element = createElement5(RootLayoutComponent, data, element);
13605
+ element = createElement6(RootLayoutComponent, data, element);
12464
13606
  }
12465
- return element;
13607
+ return withRouteSnapshot(element, route.pattern, data);
12466
13608
  }
12467
13609
  function wrapRootLayout(element, data, rootLayout) {
12468
13610
  if (!rootLayout.layout) {
12469
13611
  return element;
12470
13612
  }
12471
13613
  const RootLayoutComponent = rootLayout.layout;
12472
- return createElement5(RootLayoutComponent, data, element);
13614
+ return createElement6(RootLayoutComponent, data, element);
12473
13615
  }
12474
13616
  function buildNotFoundElement(component, error) {
12475
13617
  const NotFound = component ?? DefaultNotFoundFallback;
@@ -12509,12 +13651,6 @@ function buildErrorElement(component, error, digest, messageOverride, status) {
12509
13651
  }, undefined, false, undefined, this);
12510
13652
  }
12511
13653
 
12512
- // src/client.ts
12513
- var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
12514
- function isDeferred(value) {
12515
- return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
12516
- }
12517
-
12518
13654
  // src/rsc/render-error.ts
12519
13655
  var INTERNAL_STACK_FRAMES = new Set([
12520
13656
  "<anonymous>",
@@ -12578,17 +13714,88 @@ function isFurinRscRenderError(error) {
12578
13714
  return error instanceof FurinRscRenderError || typeof error === "object" && error !== null && error.code === "FURIN_RSC_RENDER_ERROR";
12579
13715
  }
12580
13716
 
13717
+ // src/shared/defer.ts
13718
+ var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
13719
+ function isDeferred(value) {
13720
+ return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
13721
+ }
13722
+
12581
13723
  // src/server/render/loaders.ts
12582
13724
  init_context_logger();
12583
13725
  init_instrumentation();
12584
13726
  init_patterns();
12585
13727
 
13728
+ // src/server/sync/query-context.ts
13729
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
13730
+ init_registry();
13731
+ init_instance();
13732
+ var QUERY_CONTEXT2 = Symbol.for("furin.query.server-context.v1");
13733
+ var contextGlobal3 = globalThis;
13734
+ var contexts = contextGlobal3[QUERY_CONTEXT2] ??= new AsyncLocalStorage6;
13735
+ setServerQueryEnvironment(() => contexts.getStore());
13736
+ var trackedQueryPaths = instanceSlot(() => new Set);
13737
+ var deferredQueries = new WeakMap;
13738
+ function deferredQuerySeeds(promise) {
13739
+ return deferredQueries.get(promise);
13740
+ }
13741
+ function captureQueryReads(ctx, run, owner) {
13742
+ const { origin } = new URL(ctx.request.url);
13743
+ const store = new QueryStore(origin);
13744
+ const registry = getAutoInvalidateRegistry();
13745
+ const trackedPaths = trackedQueryPaths();
13746
+ const requestUrl = new URL(ctx.request.url);
13747
+ const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
13748
+ const onRead = () => {
13749
+ const seeds = store.dehydrate();
13750
+ registry.registerLoaderTags(path, seeds.map((seed) => queryTag(seed.identity)), owner ?? "eden-queries");
13751
+ trackedPaths.delete(path);
13752
+ if (seeds.length > 0) {
13753
+ trackedPaths.add(path);
13754
+ }
13755
+ if (trackedPaths.size > 1000) {
13756
+ const oldest = trackedPaths.values().next().value;
13757
+ if (oldest !== undefined) {
13758
+ trackedPaths.delete(oldest);
13759
+ registry.unregisterPath(oldest, "eden-queries");
13760
+ registry.unregisterPath(oldest, "eden-request-queries");
13761
+ }
13762
+ }
13763
+ };
13764
+ return contexts.run({ origin, store, onRead }, async () => {
13765
+ const result = { ...await run() };
13766
+ const seeds = store.dehydrate();
13767
+ if (result.type === "data" && seeds.length > 0) {
13768
+ const captured = [...result.syncData.__furinQueries ?? []];
13769
+ mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
13770
+ result.syncData = { ...result.syncData, __furinQueries: captured };
13771
+ }
13772
+ if (result.type === "data" && result.deferredPromises) {
13773
+ for (const [key, promise] of Object.entries(result.deferredPromises)) {
13774
+ promise.then((value) => {
13775
+ const completed = store.dehydrate();
13776
+ if (completed.length > 0) {
13777
+ const captured = deferredQueries.get(promise) ?? [];
13778
+ mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
13779
+ deferredQueries.set(promise, captured);
13780
+ }
13781
+ }).catch(() => {
13782
+ return;
13783
+ });
13784
+ }
13785
+ }
13786
+ return result;
13787
+ });
13788
+ }
13789
+
12586
13790
  // src/server/render/mixed-cache.ts
12587
13791
  init_registry();
12588
13792
  init_registry2();
12589
13793
  init_context_logger();
12590
13794
  init_instance();
12591
13795
  init_source_version();
13796
+ function capturedQueryTags() {
13797
+ return currentQueryEnvironment()?.store.dehydrate().map((seed) => queryTag(seed.identity)) ?? [];
13798
+ }
12592
13799
  var mixedCacheKey = Symbol("furin-mixed-loader-cache");
12593
13800
  function cachePathWithSearch(key) {
12594
13801
  const separator = key.indexOf("|");
@@ -12641,7 +13848,11 @@ async function readCachedSegment(entry, revalidate, parentData) {
12641
13848
  return;
12642
13849
  }
12643
13850
  }
12644
- return fromCrossJSON(snapshot.data, {});
13851
+ const environment = currentQueryEnvironment();
13852
+ environment?.store.hydrate(snapshot.queries ?? []);
13853
+ environment?.onRead();
13854
+ const data = fromCrossJSON(snapshot.data, {});
13855
+ return projectQueryData(data, snapshot.queries ?? [], (seed) => seed.data);
12645
13856
  } catch {
12646
13857
  getLogger().warn("Mixed loader cache entry is invalid; loading fresh data");
12647
13858
  }
@@ -12654,7 +13865,8 @@ async function createSegmentSnapshot(data, parentData, parentFieldsRead) {
12654
13865
  })));
12655
13866
  return JSON.stringify({
12656
13867
  data: await toCrossJSONAsync(data),
12657
- dependencies
13868
+ dependencies,
13869
+ queries: bindQueryData(data, currentQueryEnvironment()?.store.dehydrate() ?? []).filter((seed) => (seed.bindings?.length ?? 0) > 0)
12658
13870
  });
12659
13871
  }
12660
13872
  async function acquireSharedSegment(shared, identity) {
@@ -12681,6 +13893,10 @@ async function readSharedSegment(shared, identity, revalidate, parentData) {
12681
13893
  }
12682
13894
  }
12683
13895
  async function commitSharedSegment(shared, identity, lease, cached, revalidate) {
13896
+ const identityTags = new Set(identity.tags);
13897
+ if (capturedQueryTags().some((tag) => !identityTags.has(tag))) {
13898
+ return;
13899
+ }
12684
13900
  try {
12685
13901
  await shared.commit({
12686
13902
  entry: {
@@ -12708,6 +13924,7 @@ function storeLocalSegment(state, generation, key, path, tags, cached) {
12708
13924
  }
12709
13925
  async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, parentFieldsRead, run) {
12710
13926
  const instance = currentInstance();
13927
+ const declaredTags = route.tags ?? [];
12711
13928
  const mode = segment.mode ?? route.mode;
12712
13929
  const revalidate = mode === "isr" ? segment.revalidate ?? 60 : Number.POSITIVE_INFINITY;
12713
13930
  const requestUrl = new URL(ctx.request.url);
@@ -12728,7 +13945,12 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12728
13945
  mode: mode === "isr" ? "isr" : "ssg",
12729
13946
  path,
12730
13947
  scope: instance.prefix,
12731
- tags: route.tags ?? []
13948
+ tags: [
13949
+ ...new Set([
13950
+ ...declaredTags,
13951
+ ...getAutoInvalidateRegistry().tagsForPath(`${path}${requestUrl.search}`)
13952
+ ])
13953
+ ]
12732
13954
  };
12733
13955
  const stored = shared === undefined ? undefined : await readSharedSegment(shared, identity, revalidate, parentData);
12734
13956
  if (stored !== undefined) {
@@ -12744,7 +13966,7 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12744
13966
  cachedAt: Date.now(),
12745
13967
  payload: await createSegmentSnapshot(data, parentData, parentFieldsRead)
12746
13968
  };
12747
- storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, route.tags, cached);
13969
+ storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, [...declaredTags, ...capturedQueryTags()], cached);
12748
13970
  if (shared !== undefined && lease !== null) {
12749
13971
  await commitSharedSegment(shared, identity, lease, cached, revalidate);
12750
13972
  }
@@ -12779,6 +14001,12 @@ function assertPublicLoaderKey(key) {
12779
14001
  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.`);
12780
14002
  }
12781
14003
  }
14004
+ function assertRequestLoaderKey(key, ctx) {
14005
+ assertPublicLoaderKey(key);
14006
+ if (key === "log" || Object.hasOwn(ctx, key) || key in ctx && !Object.hasOwn(Object.prototype, key)) {
14007
+ throw new Error(`[furin] requestLoader data key "${key}" is reserved: it is overwritten by the SSR loader context. Rename this field to avoid conflicts.`);
14008
+ }
14009
+ }
12782
14010
  function isHttpRedirect(res) {
12783
14011
  return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
12784
14012
  }
@@ -12793,7 +14021,7 @@ async function readResponseMessage(res) {
12793
14021
  return res.statusText;
12794
14022
  }
12795
14023
  }
12796
- function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
14024
+ function createLoaderCtx(ctx, accumulatedParentPromise, inheritedRequestFields, onParentFieldAccess) {
12797
14025
  const cache = new Map;
12798
14026
  return new Proxy(ctx, {
12799
14027
  get(target, prop) {
@@ -12806,6 +14034,9 @@ function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
12806
14034
  if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
12807
14035
  return target[prop];
12808
14036
  }
14037
+ if (inheritedRequestFields && Object.hasOwn(inheritedRequestFields, prop)) {
14038
+ return inheritedRequestFields[prop];
14039
+ }
12809
14040
  onParentFieldAccess?.(prop);
12810
14041
  let entry = cache.get(prop);
12811
14042
  if (!entry) {
@@ -12918,6 +14149,8 @@ function runRequestLoaderFields(route, ctx) {
12918
14149
  if (declarations?.length !== route.routeChain.length) {
12919
14150
  throw new Error(`[furin] Missing per-loader request field metadata for ${route.pattern}.`);
12920
14151
  }
14152
+ const declaredKeys = declarations.map((keys) => new Set(keys));
14153
+ const requestKeys = new Set(route.requestKeys);
12921
14154
  const requestContext = createRequestLoaderContext(ctx);
12922
14155
  const results = loaderIndexes.map((index) => {
12923
14156
  const loader = route.routeChain[index]?.requestLoader;
@@ -12928,8 +14161,8 @@ function runRequestLoaderFields(route, ctx) {
12928
14161
  const result = observeLoader(() => invocation, `request:${index}`, ctx.path).then((value) => {
12929
14162
  const data = value;
12930
14163
  for (const key of Object.keys(data)) {
12931
- assertPublicLoaderKey(key);
12932
- if (!declarations[index]?.includes(key)) {
14164
+ assertRequestLoaderKey(key, ctx);
14165
+ if (!declaredKeys[index]?.has(key)) {
12933
14166
  throw new Error(`[furin] requestLoader in ${route.pattern} returned undeclared field "${key}".`);
12934
14167
  }
12935
14168
  }
@@ -12938,27 +14171,36 @@ function runRequestLoaderFields(route, ctx) {
12938
14171
  result.catch(() => {});
12939
14172
  return { index, result };
12940
14173
  });
12941
- const fields = {};
14174
+ let fields = {};
14175
+ const fieldsByLoader = route.routeChain.map((_, boundaryIndex) => {
14176
+ fields = { ...fields };
14177
+ for (const key of declarations[boundaryIndex] ?? []) {
14178
+ if (!requestKeys.has(key)) {
14179
+ continue;
14180
+ }
14181
+ const candidates = results.filter(({ index }) => index <= boundaryIndex && declaredKeys[index]?.has(key));
14182
+ fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
14183
+ for (let index = values.length - 1;index >= 0; index -= 1) {
14184
+ const data = values[index];
14185
+ if (data && Object.hasOwn(data, key)) {
14186
+ return data[key];
14187
+ }
14188
+ }
14189
+ });
14190
+ fields[key].catch(() => {});
14191
+ }
14192
+ return fields;
14193
+ });
12942
14194
  for (const key of route.requestKeys) {
12943
- const candidates = results.filter(({ index }) => declarations[index]?.includes(key));
12944
- if (candidates.length === 0) {
14195
+ if (!Object.hasOwn(fields, key)) {
12945
14196
  throw new Error(`[furin] No requestLoader declares field "${key}" in ${route.pattern}.`);
12946
14197
  }
12947
- fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
12948
- for (let index = values.length - 1;index >= 0; index -= 1) {
12949
- const data = values[index];
12950
- if (data && Object.hasOwn(data, key)) {
12951
- return data[key];
12952
- }
12953
- }
12954
- });
12955
- fields[key].catch(() => {});
12956
14198
  }
12957
14199
  const noFieldCompletion = Promise.all(results.filter(({ index }) => declarations[index]?.length === 0).map(({ result }) => result)).then(() => {
12958
14200
  return;
12959
14201
  });
12960
14202
  noFieldCompletion.catch(() => {});
12961
- return { fields, noFieldCompletion };
14203
+ return { fields, fieldsByLoader, noFieldCompletion };
12962
14204
  }
12963
14205
  function requestFieldPromises(route, fields, syncData, publicDeferred) {
12964
14206
  for (const key of Object.keys(fields)) {
@@ -13039,6 +14281,15 @@ async function normalizeLoaderError(err, headers) {
13039
14281
  const message = body || "Something went wrong";
13040
14282
  return { error: err, headers, message, status, type: "error" };
13041
14283
  }
14284
+ 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") {
14285
+ let message = "Something went wrong";
14286
+ if ("detail" in err.value && typeof err.value.detail === "string") {
14287
+ message = err.value.detail;
14288
+ } else if ("title" in err.value && typeof err.value.title === "string") {
14289
+ message = err.value.title;
14290
+ }
14291
+ return { error: err, headers, message, status: err.status, type: "error" };
14292
+ }
13042
14293
  if (isFurinRscRenderError(err)) {
13043
14294
  getLogger().error(err);
13044
14295
  return {
@@ -13067,10 +14318,10 @@ function mergeParentData(parent, own, path) {
13067
14318
  }
13068
14319
  return { ...parent, ...own };
13069
14320
  }
13070
- function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, ctxRecord, publicCtxRecord, mixed) {
14321
+ function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, inheritedRequestFields, ctxRecord, publicCtxRecord, mixed) {
13071
14322
  const publicSegment = mixed && (segment.mode ?? route.mode) !== "ssr";
13072
14323
  const parentFieldsRead = new Set;
13073
- const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
14324
+ const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? undefined : inheritedRequestFields, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
13074
14325
  return observeLoader(() => {
13075
14326
  const run = async () => await segment.loader?.(loaderCtx) ?? {};
13076
14327
  return publicSegment ? cacheMixedPublicLoader(route, ctx, segment, index, publicParent, parentFieldsRead, run) : run();
@@ -13085,13 +14336,13 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13085
14336
  let accumulatedParentPromise = Promise.resolve({});
13086
14337
  let publicParentPromise = Promise.resolve({});
13087
14338
  let loaderIndex = 0;
13088
- for (const r of route.routeChain) {
14339
+ for (const [routeIndex, r] of route.routeChain.entries()) {
13089
14340
  const parentAccum = accumulatedParentPromise;
13090
14341
  const publicParent = publicParentPromise;
13091
14342
  const privateSegment = mixed && (r.mode ?? route.mode) === "ssr";
13092
14343
  if (r.loader) {
13093
14344
  const index = loaderIndex;
13094
- const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, ctxRecord, publicCtxRecord, mixed);
14345
+ const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, requestFields?.fieldsByLoader[routeIndex - 1], ctxRecord, publicCtxRecord, mixed);
13095
14346
  loaderIndex += 1;
13096
14347
  loaderMap.set(r, loaderPromise);
13097
14348
  accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => mergeParentData(acc, own, ctx.path));
@@ -13105,7 +14356,7 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13105
14356
  }
13106
14357
  }
13107
14358
  }
13108
- const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
14359
+ const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, requestFields?.fields, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
13109
14360
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
13110
14361
  await requestFields?.noFieldCompletion;
13111
14362
  const headers = {};
@@ -13148,10 +14399,10 @@ function createPublicLoaderContext(ctx) {
13148
14399
  return publicContext;
13149
14400
  }
13150
14401
  function runLoaders(route, ctx) {
13151
- return runLoadersInternal(route, ctx, true, false);
14402
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, false));
13152
14403
  }
13153
14404
  function runPublicLoaders(route, ctx) {
13154
- return runLoadersInternal(route, ctx, false, false);
14405
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, false));
13155
14406
  }
13156
14407
  function hasSsrLoaderAncestor(route) {
13157
14408
  return route.routeChain.some((entry) => entry.mode === "ssr" && entry.loader !== undefined);
@@ -13161,26 +14412,53 @@ function hasMixedLoaderModes(route) {
13161
14412
  return route.routeChain.some((entry) => entry.loader !== undefined && entry.mode !== undefined && (entry.mode !== route.mode || entry.mode === "isr" && (entry.revalidate ?? 60) !== pageRevalidate));
13162
14413
  }
13163
14414
  function runMixedLoaders(route, ctx) {
13164
- return runLoadersInternal(route, ctx, true, true);
14415
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, true));
13165
14416
  }
13166
14417
  function runRouteLoaders(route, ctx) {
13167
14418
  return hasMixedLoaderModes(route) ? runMixedLoaders(route, ctx) : runLoaders(route, ctx);
13168
14419
  }
13169
14420
  function runSegmentPublicLoaders(route, ctx) {
13170
- return runLoadersInternal(route, ctx, false, true);
14421
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, true));
13171
14422
  }
13172
14423
  function hasRequestLoader(route) {
13173
14424
  return route.routeChain.some((entry) => entry.requestLoader !== undefined);
13174
14425
  }
13175
14426
 
14427
+ // src/server/render/react-stream.ts
14428
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "async_hooks";
14429
+ import { renderToReadableStream as renderReactStream } from "react-dom/server";
14430
+
14431
+ // src/client/client-module.ts
14432
+ import { preloadModule as preloadModule2 } from "react-dom";
14433
+ var resolveModuleHrefs = () => [];
14434
+ var resolveNonce = () => {
14435
+ return;
14436
+ };
14437
+ function setClientModuleNonceResolver(resolver) {
14438
+ resolveNonce = resolver;
14439
+ }
14440
+ function setClientModuleHrefResolver(resolver) {
14441
+ resolveModuleHrefs = resolver;
14442
+ }
14443
+
14444
+ // src/server/render/react-stream.ts
14445
+ var renderNonces = new AsyncLocalStorage7;
14446
+ setClientModuleNonceResolver(() => renderNonces.getStore());
14447
+ function renderToReadableStream(element, options) {
14448
+ const nonce = options?.nonce;
14449
+ return renderNonces.run(typeof nonce === "string" ? nonce : nonce?.script, () => renderReactStream(element, options));
14450
+ }
14451
+
13176
14452
  // src/server/render/route-frame-transport.ts
13177
14453
  async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13178
14454
  try {
13179
14455
  const { rscFrames, value } = serializeRouteFrameValue(await promise, idPrefix);
14456
+ const queries = deferredQuerySeeds(promise);
13180
14457
  return serializeRouteFrame({
13181
14458
  key,
13182
14459
  type: "defer-resolve",
13183
- value
14460
+ value,
14461
+ ...queries && { queries: toCrossJSON(queries) }
13184
14462
  }) + rscFrames;
13185
14463
  } catch (error) {
13186
14464
  return serializeRouteFrame({
@@ -13192,16 +14470,17 @@ async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13192
14470
  }
13193
14471
 
13194
14472
  // src/server/render/template.ts
14473
+ import { readFileSync as readFileSync5 } from "fs";
13195
14474
  init_plugin();
13196
14475
  init_instrumentation();
13197
14476
  init_instance();
13198
- import { readFileSync as readFileSync3 } from "fs";
13199
14477
  var instanceTemplateState = instanceSlot(() => ({
13200
14478
  devAssets: null,
13201
14479
  devCache: null,
13202
14480
  prodAssets: null,
13203
14481
  prodContent: null,
13204
- prodPath: null
14482
+ prodPath: null,
14483
+ prodPreload: null
13205
14484
  }));
13206
14485
  var DEV_TEMPLATE_TTL_MS = 1000;
13207
14486
  var TAG_ATTRIBUTE_PATTERN = /([A-Za-z][\w:-]*)="([^"]*)"/g;
@@ -13319,7 +14598,7 @@ function readTemplate(state) {
13319
14598
  return null;
13320
14599
  }
13321
14600
  try {
13322
- state.prodContent = readFileSync3(state.prodPath, "utf8");
14601
+ state.prodContent = readFileSync5(state.prodPath, "utf8");
13323
14602
  return state.prodContent;
13324
14603
  } catch {
13325
14604
  return null;
@@ -13336,10 +14615,17 @@ function readDocumentAssets(state) {
13336
14615
  state.prodAssets = documentAssetsFromTemplate(template);
13337
14616
  return state.prodAssets;
13338
14617
  }
14618
+ function setProductionPreloadManifest(manifest, instance) {
14619
+ instanceTemplateState(instance).prodPreload = manifest;
14620
+ }
14621
+ function getProductionPreloadManifest() {
14622
+ return instanceTemplateState().prodPreload ?? instanceTemplateState(defaultInstanceBucket()).prodPreload;
14623
+ }
14624
+ setClientModuleHrefResolver((key) => getProductionPreloadManifest()?.modules[key] ?? []);
13339
14625
 
13340
14626
  // src/server/render/ssr.ts
13341
14627
  function withSSRRouterContext(element, contextValue) {
13342
- return createElement6(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement6(RouterContext.Provider, { value: contextValue }, element));
14628
+ return createElement7(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement7(RouterContext.Provider, { value: contextValue }, element));
13343
14629
  }
13344
14630
  function hasDocumentMarkers(html) {
13345
14631
  return html.includes('data-furin-head=""') && html.includes('data-furin-scripts=""');
@@ -13408,7 +14694,8 @@ async function renderElementWithShellFallback(element, errorComponent, ssrContex
13408
14694
  }
13409
14695
  }
13410
14696
  function assertDeferredModeAllowed(route, deferredPromises) {
13411
- const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !route.requestKeys?.includes(key));
14697
+ const requestKeys = new Set(route.requestKeys);
14698
+ const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !requestKeys.has(key));
13412
14699
  if (deferredKeys.length > 0 && route.mode !== "ssr" && !hasSsrLoaderAncestor(route)) {
13413
14700
  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.");
13414
14701
  }
@@ -13443,6 +14730,10 @@ function resolveDocumentAssets(ctx) {
13443
14730
  }
13444
14731
  return documentAssetsFromTemplate(generateIndexHtml());
13445
14732
  }
14733
+ function withRouteModulePreloads(assets, pattern) {
14734
+ const modulePreloads = getProductionPreloadManifest()?.routes[pattern];
14735
+ return modulePreloads ? { ...assets, modulePreloads } : assets;
14736
+ }
13446
14737
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
13447
14738
  const loaderStart = Date.now();
13448
14739
  const loaderResult = precomputedLoaderResult ?? await runRouteLoaders(route, ctx);
@@ -13450,7 +14741,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13450
14741
  if (loaderResult.type === "redirect") {
13451
14742
  return loaderResult.response;
13452
14743
  }
13453
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
14744
+ if (throwOnFailure && loaderResult.type === "error") {
13454
14745
  throw loaderResult.error;
13455
14746
  }
13456
14747
  const isNotFound = loaderResult.type === "not-found";
@@ -13461,7 +14752,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13461
14752
  assertDeferredModeAllowed(route, deferredPromises);
13462
14753
  const { headers } = loaderResult;
13463
14754
  const componentProps = deferredPromises === undefined ? syncData : { ...syncData, ...deferredPromises };
13464
- const assets = await resolveDocumentAssets(ctx);
14755
+ const assets = withRouteModulePreloads(await resolveDocumentAssets(ctx), route.pattern);
13465
14756
  const errorComponent = route.error ?? root.error;
13466
14757
  let element;
13467
14758
  let headData;
@@ -13489,6 +14780,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13489
14780
  const ssrContext = {
13490
14781
  basePath: resolvedBasePath,
13491
14782
  currentHref: currentHrefFromContext(ctx, resolvedBasePath),
14783
+ currentPattern: route.pattern,
13492
14784
  defaultPreload: "intent",
13493
14785
  defaultPreloadDelay: 50,
13494
14786
  defaultPreloadStaleTime: 30000,
@@ -13519,7 +14811,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13519
14811
  }
13520
14812
  async function renderBufferedResult(prepared, route, root) {
13521
14813
  const { assets, deferredPromises, element, headData, headers, syncData } = prepared;
13522
- 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, {
14814
+ 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, {
13523
14815
  __furinError: { digest, message, status: 500 },
13524
14816
  __furinStatus: 500
13525
14817
  }));
@@ -13544,9 +14836,30 @@ async function renderBufferedResult(prepared, route, root) {
13544
14836
  headers,
13545
14837
  html,
13546
14838
  ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
14839
+ queryTags: queryTagsFromData(syncData),
13547
14840
  status: prepared.status
13548
14841
  };
13549
14842
  }
14843
+ async function normalizePrerenderContext(route, ctx) {
14844
+ const parsedParams = await parseRouteParams(ctx.params, mergeRouteSchemas(route.routeChain, "params"));
14845
+ if (!parsedParams.ok) {
14846
+ throw new Error(`[furin] Invalid prerender params for "${route.pattern}".`, {
14847
+ cause: parsedParams.errors
14848
+ });
14849
+ }
14850
+ ctx.params = parsedParams.params;
14851
+ const querySchema = mergeRouteSchemas(route.routeChain, "query");
14852
+ if (querySchema === undefined) {
14853
+ return;
14854
+ }
14855
+ const parsedQuery = await parseRouteQuery(new URL(ctx.request.url), querySchema);
14856
+ if (!parsedQuery.ok) {
14857
+ throw new Error(`[furin] Invalid prerender query for "${route.pattern}".`, {
14858
+ cause: parsedQuery.errors
14859
+ });
14860
+ }
14861
+ ctx.query = parsedQuery.query;
14862
+ }
13550
14863
  function renderForPath(route, params, root, origin, mode, basePath, searchRoutes, search, requestContext) {
13551
14864
  return runInSyntheticRenderScope(async () => {
13552
14865
  const resolvedPath = resolvePath(route.pattern, params);
@@ -13572,6 +14885,9 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
13572
14885
  request: new Request(requestUrl),
13573
14886
  set: { headers: {} }
13574
14887
  };
14888
+ if (requestContext === undefined) {
14889
+ await normalizePrerenderContext(route, ctx);
14890
+ }
13575
14891
  const loaderResult = await (hasMixedLoaderModes(route) ? runSegmentPublicLoaders(route, ctx) : runPublicLoaders(route, ctx));
13576
14892
  const prepared = await prepareRender(route, ctx, root, basePath, true, loaderResult, searchRoutes);
13577
14893
  if (prepared instanceof Response) {
@@ -13612,7 +14928,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
13612
14928
  }
13613
14929
 
13614
14930
  // src/server/render/static-params.ts
13615
- import { dirname as dirname8, relative as relative5 } from "path";
14931
+ import { dirname as dirname10, relative as relative5 } from "path";
13616
14932
  init_patterns();
13617
14933
  var STATIC_PARAMS_CONCURRENCY = 4;
13618
14934
  function collectStaticParamsStages(route) {
@@ -13633,8 +14949,8 @@ function ancestorPattern(route, ancestors) {
13633
14949
  if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
13634
14950
  return route.pattern;
13635
14951
  }
13636
- const pagesDir = dirname8(rootSourcePath);
13637
- const ancestorDir = dirname8(ancestorSourcePath);
14952
+ const pagesDir = dirname10(rootSourcePath);
14953
+ const ancestorDir = dirname10(ancestorSourcePath);
13638
14954
  if (ancestorDir === pagesDir) {
13639
14955
  return "/";
13640
14956
  }
@@ -13734,25 +15050,44 @@ async function prerenderRoute(route, params, root, origin, mode, basePath, searc
13734
15050
  html: renderResult.html,
13735
15051
  ndjson: renderResult.ndjson,
13736
15052
  status: renderResult.status,
13737
- tags: route.tags
15053
+ tags: [...route.tags ?? [], ...renderResult.queryTags ?? []]
13738
15054
  };
13739
15055
  }
13740
- async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15056
+ async function prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes) {
13741
15057
  const resolvedPath = resolvePath(route.pattern, params);
13742
15058
  const cached = getSSGCache(resolvedPath);
13743
15059
  if (cached) {
13744
15060
  if (cached.tags === route.tags) {
13745
- return cached;
15061
+ return { cacheStored: true, entry: cached };
13746
15062
  }
13747
- const taggedEntry = { ...cached, tags: route.tags };
15063
+ const taggedEntry = {
15064
+ ...cached,
15065
+ tags: [
15066
+ ...route.tags ?? [],
15067
+ ...(cached.tags ?? []).filter((tag) => queryFromTag(tag) !== undefined)
15068
+ ]
15069
+ };
13748
15070
  setSSGCache(resolvedPath, taggedEntry);
13749
- return taggedEntry;
15071
+ return { cacheStored: true, entry: taggedEntry };
13750
15072
  }
13751
- const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
13752
- if (entry instanceof Response) {
13753
- return entry;
15073
+ const cache = ssgRouteCache();
15074
+ const generation = cache.captureGeneration(resolvedPath);
15075
+ try {
15076
+ const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
15077
+ if (entry instanceof Response || entry.status !== 200 || !generation.valid) {
15078
+ return { cacheStored: false, entry };
15079
+ }
15080
+ setSSGCache(resolvedPath, entry);
15081
+ return { cacheStored: true, entry };
15082
+ } finally {
15083
+ cache.releaseGeneration(resolvedPath, generation);
15084
+ }
15085
+ }
15086
+ async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15087
+ const { entry } = await prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes);
15088
+ if (!(entry instanceof Response) && entry.status >= 500) {
15089
+ throw new Error(`[furin] Failed to prerender SSG route "${route.pattern}" (HTTP ${entry.status}).`);
13754
15090
  }
13755
- setSSGCache(resolvedPath, entry);
13756
15091
  return entry;
13757
15092
  }
13758
15093
  // src/build/ssg-cache.ts
@@ -13815,8 +15150,8 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
13815
15150
  }
13816
15151
 
13817
15152
  // src/rsc/build/index.ts
13818
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "fs";
13819
- import { basename as basename3, join as join8 } from "path";
15153
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
15154
+ import { basename as basename4, join as join8 } from "path";
13820
15155
  import { fileURLToPath as fileURLToPath4 } from "url";
13821
15156
  init_transform_isomorphic();
13822
15157
 
@@ -13926,22 +15261,23 @@ ${result.logs.map((log) => log.message).join(`
13926
15261
  ${codecResult.logs.map((log) => log.message).join(`
13927
15262
  `)}`);
13928
15263
  }
13929
- const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
15264
+ const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename4(output.path)}` }));
13930
15265
  const manifest = { buildId, clientReferences: [], css };
13931
- writeFileSync3(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
15266
+ writeFileSync4(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
13932
15267
  return manifest;
13933
15268
  }
13934
15269
 
13935
15270
  // src/adapter/runtime-build.ts
13936
15271
  init_patterns();
13937
- var _pkgRoot2 = dirname9(dirname9(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
13938
- var _pkgSrcDir2 = existsSync7(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
15272
+ var _pkgRoot2 = dirname11(dirname11(fileURLToPath5(import.meta.resolve("@teyik0/furin"))));
15273
+ var _pkgSrcDir2 = existsSync8(join9(_pkgRoot2, "src", "furin.ts")) ? join9(_pkgRoot2, "src") : join9(_pkgRoot2, "dist");
13939
15274
  var _ext2 = ".ts";
13940
15275
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
13941
15276
  var MIXED_CACHE_IMPORT_RE = /mixed-cache(?:\.ts)?$/;
13942
15277
  var ANY_MODULE_RE = /.*/;
13943
15278
  var REACT_SERVER_IMPORT_RE = /^react-dom\/server(?:\.edge)?$/;
13944
15279
  var REACT_STATIC_IMPORT_RE = /^react-dom\/static\.edge$/;
15280
+ var SCRIPT_FILE_RE = /\.[cm]?[jt]sx?$/;
13945
15281
  var BUILD_ID_INPUT_PATHS = [
13946
15282
  `${_pkgSrcDir2}/build/compile-entry${_ext2}`,
13947
15283
  `${_pkgSrcDir2}/build/entry-template${_ext2}`,
@@ -13997,16 +15333,49 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
13997
15333
  }
13998
15334
  }
13999
15335
  }
15336
+ const sources = new Map;
15337
+ const visit = async (inputPath) => {
15338
+ const path = existsSync8(inputPath) ? realpathSync4(inputPath) : inputPath;
15339
+ fingerprintPaths.delete(inputPath);
15340
+ fingerprintPaths.add(path);
15341
+ if (sources.has(path)) {
15342
+ return;
15343
+ }
15344
+ sources.set(path, "");
15345
+ const content = existsSync8(path) ? await Bun.file(path).text() : "";
15346
+ sources.set(path, content);
15347
+ if (!SCRIPT_FILE_RE.test(path)) {
15348
+ return;
15349
+ }
15350
+ const transpiler = new Bun.Transpiler({ loader: path.endsWith("x") ? "tsx" : "ts" });
15351
+ await Promise.all(transpiler.scanImports(content).flatMap(({ path: specifier }) => {
15352
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
15353
+ return [];
15354
+ }
15355
+ let dependency;
15356
+ try {
15357
+ dependency = Bun.resolveSync(specifier, dirname11(path));
15358
+ } catch {
15359
+ return [];
15360
+ }
15361
+ if (!isAbsolute5(dependency) || toPosixPath(dependency).includes("/node_modules/")) {
15362
+ return [];
15363
+ }
15364
+ fingerprintPaths.add(dependency);
15365
+ return [visit(dependency)];
15366
+ }));
15367
+ };
15368
+ await Promise.all([...fingerprintPaths].map(visit));
14000
15369
  for (const path of BUILD_ID_INPUT_PATHS) {
14001
- if (!existsSync7(path)) {
15370
+ if (!existsSync8(path)) {
14002
15371
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
14003
15372
  }
14004
15373
  fingerprintPaths.add(path);
14005
15374
  }
14006
- const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
14007
- const content = existsSync7(path) ? await Bun.file(path).text() : "";
15375
+ const fileParts = (await Promise.all([...fingerprintPaths].map(async (path) => {
15376
+ const content = sources.get(path) ?? (existsSync8(path) ? await Bun.file(path).text() : "");
14008
15377
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
14009
- }));
15378
+ }))).sort(compareCodeUnits);
14010
15379
  const routeParts = routes.map((route) => JSON.stringify({
14011
15380
  mode: route.mode,
14012
15381
  path: stableFingerprintPath(route.path, projectRoot),
@@ -14018,15 +15387,16 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
14018
15387
  `);
14019
15388
  }
14020
15389
  function stableFingerprintPath(path, projectRoot) {
14021
- const projectPath = relative6(projectRoot, path);
14022
- if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
15390
+ const absolutePath = existsSync8(path) ? realpathSync4(path) : path;
15391
+ const projectPath = relative6(realpathSync4(projectRoot), absolutePath);
15392
+ if (!isAbsolute5(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
14023
15393
  return `app/${toPosixPath(projectPath)}`;
14024
15394
  }
14025
- const frameworkPath = relative6(_pkgRoot2, path);
14026
- if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
15395
+ const frameworkPath = relative6(_pkgRoot2, absolutePath);
15396
+ if (!isAbsolute5(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
14027
15397
  return `furin/${toPosixPath(frameworkPath)}`;
14028
15398
  }
14029
- return `external/${basename4(path)}`;
15399
+ return `external/${basename5(path)}`;
14030
15400
  }
14031
15401
  function buildCompileMetadata(root, routes) {
14032
15402
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14050,7 +15420,7 @@ function buildCompileMetadata(root, routes) {
14050
15420
  }
14051
15421
  function pprRuntimePlugin(apps) {
14052
15422
  const enabled = apps.some((app) => app.routes.some((route) => resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route))));
14053
- const pprPath = resolve6(_pkgSrcDir2, "server/render/ppr-route.ts");
15423
+ const pprPath = resolve8(_pkgSrcDir2, "server/render/ppr-route.ts");
14054
15424
  const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
14055
15425
  const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
14056
15426
  return {
@@ -14062,7 +15432,7 @@ function pprRuntimePlugin(apps) {
14062
15432
  return;
14063
15433
  }
14064
15434
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
14065
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15435
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14066
15436
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
14067
15437
  return;
14068
15438
  }
@@ -14080,7 +15450,7 @@ export const runPprPublicLoaders = renderPprRoute;`,
14080
15450
  }
14081
15451
  function mixedRuntimePlugin(apps) {
14082
15452
  const enabled = apps.some((app) => app.routes.some(hasMixedLoaderModes));
14083
- const mixedPath = resolve6(_pkgSrcDir2, "server/render/mixed-cache.ts");
15453
+ const mixedPath = resolve8(_pkgSrcDir2, "server/render/mixed-cache.ts");
14084
15454
  return {
14085
15455
  name: "furin-mixed-runtime",
14086
15456
  setup(build) {
@@ -14088,7 +15458,7 @@ function mixedRuntimePlugin(apps) {
14088
15458
  return;
14089
15459
  }
14090
15460
  build.onResolve({ filter: MIXED_CACHE_IMPORT_RE }, ({ path, importer }) => {
14091
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15461
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14092
15462
  if (absolute !== mixedPath && `${absolute}.ts` !== mixedPath) {
14093
15463
  return;
14094
15464
  }
@@ -14114,15 +15484,16 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
14114
15484
  const modulePaths = routeSourcePaths(app);
14115
15485
  const clientDirName = clientDirNameForPrefix(prefix);
14116
15486
  const label = prefix === "" ? "root app" : `app "${prefix}"`;
14117
- const { entryChunk, cssChunks } = await buildClient(routes, {
15487
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14118
15488
  basePath: prefix,
14119
15489
  clientDirName,
14120
15490
  clientLogging: options.clientLogging ?? false,
14121
- metafilePath: options.analyze ? join9(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
15491
+ metafilePath: options.analyze ? join9(dirname11(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
14122
15492
  optimizeImports: options.optimizeImports,
14123
15493
  outDir: targetDir,
14124
15494
  pagesDir: app.pagesDir,
14125
15495
  plugins: options.plugins,
15496
+ preloadRouteChunks: options.preload?.routeChunks,
14126
15497
  publicPath: `${prefix}/_client/`,
14127
15498
  reactCompiler: options.reactCompiler,
14128
15499
  rootLayout: root.path
@@ -14132,8 +15503,9 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14132
15503
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14133
15504
  const clientDir = join9(targetDir, clientDirName);
14134
15505
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14135
- writeFileSync4(join9(clientDir, "index.html"), indexHtml);
15506
+ writeFileSync5(join9(clientDir, "index.html"), indexHtml);
14136
15507
  setProductionTemplateContent(indexHtml);
15508
+ setProductionPreloadManifest(preloadManifest);
14137
15509
  ssgRouteCache().clear();
14138
15510
  let ssgCache;
14139
15511
  let prerenders = [];
@@ -14157,6 +15529,7 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14157
15529
  modulePaths,
14158
15530
  nativeRoutes: composableRouteModuleSpecifier(app),
14159
15531
  prefix,
15532
+ preloadManifest,
14160
15533
  rootConventions,
14161
15534
  rootPath: root.path,
14162
15535
  routeMetadata,
@@ -14227,7 +15600,7 @@ function writeServerMetafile(build, analyze, buildRoot) {
14227
15600
  const analysisDir = join10(buildRoot, "analysis");
14228
15601
  ensureDir(analysisDir);
14229
15602
  const metafilePath = join10(analysisDir, "bun-server.json");
14230
- writeFileSync5(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
15603
+ writeFileSync6(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
14231
15604
  `);
14232
15605
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
14233
15606
  }
@@ -14259,7 +15632,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
14259
15632
  ...context.extraContext ?? [],
14260
15633
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
14261
15634
  ],
14262
- templateHtml: readFileSync4(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
15635
+ templateHtml: readFileSync6(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
14263
15636
  }));
14264
15637
  return await materializeServerAppEntry({
14265
15638
  apps: contexts,
@@ -14278,14 +15651,14 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14278
15651
  }
14279
15652
  const target = "bun";
14280
15653
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
14281
- const targetDir = resolve7(rootDir, targetManifest.targetDir);
15654
+ const targetDir = resolve9(rootDir, targetManifest.targetDir);
14282
15655
  rmSync2(targetDir, { force: true, recursive: true });
14283
15656
  rmSync2(join10(buildRoot, "private", "server-sourcemaps", "bun"), {
14284
15657
  force: true,
14285
15658
  recursive: true
14286
15659
  });
14287
15660
  ensureDir(targetDir);
14288
- const publicDir = existsSync8(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
15661
+ const publicDir = existsSync9(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
14289
15662
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
14290
15663
  targetManifest.buildId = headlineBuildId;
14291
15664
  if (serverEntry) {
@@ -14362,15 +15735,16 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14362
15735
  }
14363
15736
 
14364
15737
  // src/adapter/package.ts
14365
- import { existsSync as existsSync9, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";
14366
- import { join as join11, relative as relative7, resolve as resolve8 } from "path";
15738
+ import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
15739
+ import { join as join11, relative as relative7, resolve as resolve10 } from "path";
15740
+ init_transform_isomorphic();
14367
15741
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
14368
15742
  const { prefix, root, routes, pagesDir } = app;
14369
15743
  const modulePaths = routeSourcePaths(app);
14370
15744
  const targetDir = join11(buildRoot, "package");
14371
15745
  rmSync3(targetDir, { force: true, recursive: true });
14372
15746
  ensureDir(targetDir);
14373
- const { entryChunk, cssChunks } = await buildClient(routes, {
15747
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14374
15748
  basePath: prefix,
14375
15749
  clientLogging: options.clientLogging ?? false,
14376
15750
  metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
@@ -14378,6 +15752,7 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
14378
15752
  outDir: targetDir,
14379
15753
  pagesDir,
14380
15754
  plugins: options.plugins,
15755
+ preloadRouteChunks: options.preload?.routeChunks,
14381
15756
  publicPath: `${prefix}/_client/`,
14382
15757
  reactCompiler: options.reactCompiler,
14383
15758
  rootLayout: root.path
@@ -14387,12 +15762,13 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14387
15762
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14388
15763
  const clientDir = join11(targetDir, "client");
14389
15764
  const publicDir = join11(rootDir, "public");
14390
- if (existsSync9(publicDir)) {
15765
+ if (existsSync10(publicDir)) {
14391
15766
  copyDirRecursive(publicDir, join11(targetDir, "public"));
14392
15767
  }
14393
15768
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14394
- writeFileSync6(join11(clientDir, "index.html"), indexHtml);
15769
+ writeFileSync7(join11(clientDir, "index.html"), indexHtml);
14395
15770
  setProductionTemplateContent(indexHtml);
15771
+ setProductionPreloadManifest(preloadManifest);
14396
15772
  ssgRouteCache().clear();
14397
15773
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
14398
15774
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14420,6 +15796,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14420
15796
  modulePaths,
14421
15797
  nativeRoutes: composableRouteModuleSpecifier(app),
14422
15798
  prefix,
15799
+ preloadManifest,
14423
15800
  rootConventions,
14424
15801
  rootPath: root.path,
14425
15802
  routeMetadata,
@@ -14442,7 +15819,9 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14442
15819
  plugins: [
14443
15820
  register.plugin,
14444
15821
  ...options.plugins ?? [],
14445
- createRoutesPlugin({ instances: [app], target: "server" })
15822
+ createRoutesPlugin({ instances: [app], target: "server" }),
15823
+ isomorphicTransformPlugin("server"),
15824
+ environmentGuardPlugin("ssr")
14446
15825
  ],
14447
15826
  sourcemap: "none",
14448
15827
  target: "bun"
@@ -14450,7 +15829,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14450
15829
  if (!result.success) {
14451
15830
  throw new AggregateError(result.logs, "[furin] package register build failed");
14452
15831
  }
14453
- const relativePagesDir = toPosixPath(relative7(targetDir, resolve8(rootDir, pagesDir)));
15832
+ const relativePagesDir = toPosixPath(relative7(targetDir, resolve10(rootDir, pagesDir)));
14454
15833
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
14455
15834
  import { fileURLToPath } from "node:url";
14456
15835
  import { furin } from "@teyik0/furin";
@@ -14477,7 +15856,7 @@ export function createFurinApp(options = {}) {
14477
15856
 
14478
15857
  export const prefix = ${JSON.stringify(prefix)};
14479
15858
  `;
14480
- writeFileSync6(join11(targetDir, "index.js"), factorySource);
15859
+ writeFileSync7(join11(targetDir, "index.js"), factorySource);
14481
15860
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
14482
15861
 
14483
15862
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -14485,7 +15864,7 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
14485
15864
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
14486
15865
  export declare const prefix: string;
14487
15866
  `;
14488
- writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
15867
+ writeFileSync7(join11(targetDir, "index.d.ts"), dtsSource);
14489
15868
  console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
14490
15869
  return {
14491
15870
  buildId,
@@ -14496,19 +15875,19 @@ export declare const prefix: string;
14496
15875
  }
14497
15876
 
14498
15877
  // src/adapter/static.ts
14499
- import { cpSync as cpSync2, existsSync as existsSync10, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";
14500
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join12, parse as parse3, relative as relative8, resolve as resolve9, sep as sep2, win32 } from "path";
15878
+ import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
15879
+ import { dirname as dirname12, isAbsolute as isAbsolute6, join as join12, parse as parse3, relative as relative8, resolve as resolve11, sep as sep2, win32 } from "path";
14501
15880
  init_patterns();
14502
15881
  var STATIC_CONCURRENCY = 4;
14503
15882
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
14504
15883
  var TRAILING_SLASHES_RE = /\/+$/;
14505
15884
  var STATIC_RENDER_ORIGIN = "http://localhost";
14506
15885
  function pathToOutputFile(urlPath, outDir, fileName) {
14507
- const normalizedOutDir = resolve9(outDir);
15886
+ const normalizedOutDir = resolve11(outDir);
14508
15887
  if (urlPath === "/" || urlPath === "") {
14509
15888
  return join12(normalizedOutDir, fileName);
14510
15889
  }
14511
- const resolved = resolve9(normalizedOutDir, urlPath.slice(1), fileName);
15890
+ const resolved = resolve11(normalizedOutDir, urlPath.slice(1), fileName);
14512
15891
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
14513
15892
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
14514
15893
  }
@@ -14581,22 +15960,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
14581
15960
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
14582
15961
  }
14583
15962
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
14584
- ensureDir(dirname10(htmlOutputFile));
14585
- writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
15963
+ ensureDir(dirname12(htmlOutputFile));
15964
+ writeFileSync8(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
14586
15965
  if (staticLocation.spa !== null) {
14587
15966
  const serializedRedirect = await toCrossJSONAsync({
14588
15967
  __furinRedirect: staticLocation.spa
14589
15968
  });
14590
- writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
15969
+ writeFileSync8(dataOutputFile, `${JSON.stringify(serializedRedirect)}
14591
15970
  `);
14592
15971
  }
14593
15972
  renderedRoutes.push(urlPath);
14594
15973
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
14595
15974
  return;
14596
15975
  }
14597
- ensureDir(dirname10(htmlOutputFile));
14598
- writeFileSync7(htmlOutputFile, entry.html);
14599
- writeFileSync7(dataOutputFile, entry.ndjson);
15976
+ ensureDir(dirname12(htmlOutputFile));
15977
+ writeFileSync8(htmlOutputFile, entry.html);
15978
+ writeFileSync8(dataOutputFile, entry.ndjson);
14600
15979
  renderedRoutes.push(urlPath);
14601
15980
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
14602
15981
  } catch (err) {
@@ -14703,15 +16082,15 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14703
16082
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
14704
16083
  }
14705
16084
  const rawOutDir = staticConfig.outDir ?? "dist";
14706
- const outDir = resolve9(rootDir, rawOutDir);
14707
- const normalizedRoot = resolve9(rootDir);
14708
- const normalizedBuildRoot = resolve9(buildRoot);
16085
+ const outDir = resolve11(rootDir, rawOutDir);
16086
+ const normalizedRoot = resolve11(rootDir);
16087
+ const normalizedBuildRoot = resolve11(buildRoot);
14709
16088
  if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
14710
16089
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
14711
16090
  }
14712
16091
  function isOutsideOutDir(target) {
14713
16092
  const rel = relative8(outDir, target);
14714
- return rel.startsWith("..") || isAbsolute4(rel);
16093
+ return rel.startsWith("..") || isAbsolute6(rel);
14715
16094
  }
14716
16095
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
14717
16096
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -14730,33 +16109,35 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14730
16109
  const targetDir = join12(buildRoot, "static");
14731
16110
  rmSync4(targetDir, { force: true, recursive: true });
14732
16111
  ensureDir(targetDir);
14733
- const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
16112
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(ssgRoutes, {
14734
16113
  basePath,
14735
16114
  clientLogging: Boolean(options.clientLogging),
14736
16115
  metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
14737
16116
  optimizeImports: options.optimizeImports,
14738
16117
  outDir: targetDir,
14739
- pagesDir: dirname10(root.path),
16118
+ pagesDir: dirname12(root.path),
14740
16119
  plugins: options.plugins,
16120
+ preloadRouteChunks: options.preload?.routeChunks,
14741
16121
  publicPath,
14742
16122
  reactCompiler: options.reactCompiler,
14743
16123
  rootLayout: root.path
14744
16124
  });
14745
16125
  const publicFavicon = join12(rootDir, "public", "favicon.ico");
14746
- const faviconHref = existsSync10(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
16126
+ const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
14747
16127
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
14748
16128
  setProductionTemplateContent(shellHtml);
16129
+ setProductionPreloadManifest(preloadManifest);
14749
16130
  const publicSrcDir = join12(rootDir, "public");
14750
- if (existsSync10(publicSrcDir)) {
16131
+ if (existsSync11(publicSrcDir)) {
14751
16132
  cpSync2(publicSrcDir, outDir, { recursive: true });
14752
16133
  }
14753
16134
  const clientSrcDir = join12(targetDir, "client");
14754
- if (existsSync10(clientSrcDir)) {
16135
+ if (existsSync11(clientSrcDir)) {
14755
16136
  cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
14756
16137
  }
14757
16138
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
14758
16139
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
14759
- writeFileSync7(join12(outDir, "404.html"), shellHtml);
16140
+ writeFileSync8(join12(outDir, "404.html"), shellHtml);
14760
16141
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
14761
16142
  rmSync4(targetDir, { force: true, recursive: true });
14762
16143
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -14770,8 +16151,8 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14770
16151
  }
14771
16152
 
14772
16153
  // src/adapter/vercel.ts
14773
- import { cpSync as cpSync3, existsSync as existsSync11, readFileSync as readFileSync5, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync8 } from "fs";
14774
- import { basename as basename5, dirname as dirname11, extname as extname3, join as join13, relative as relative9 } from "path";
16154
+ import { cpSync as cpSync3, existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync9 } from "fs";
16155
+ import { basename as basename6, dirname as dirname13, extname as extname3, join as join13, relative as relative9 } from "path";
14775
16156
  import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
14776
16157
  init_transform_isomorphic();
14777
16158
  init_patterns();
@@ -14783,7 +16164,7 @@ var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
14783
16164
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
14784
16165
  var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
14785
16166
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
14786
- var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
16167
+ var FURIN_RUNTIME_ROOT2 = dirname13(import.meta.dir);
14787
16168
  function isFurinRuntimeImporter(importer) {
14788
16169
  if (importer === "") {
14789
16170
  return false;
@@ -14814,8 +16195,8 @@ function vercelRuntimePlugin() {
14814
16195
  };
14815
16196
  }
14816
16197
  function frameworkVersion() {
14817
- const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
14818
- const packageJson = JSON.parse(readFileSync5(join13(packageRoot, "package.json"), "utf8"));
16198
+ const packageRoot = dirname13(dirname13(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
16199
+ const packageJson = JSON.parse(readFileSync7(join13(packageRoot, "package.json"), "utf8"));
14819
16200
  return packageJson.version;
14820
16201
  }
14821
16202
  function serverEntryLoader(serverEntry) {
@@ -14833,7 +16214,7 @@ function serverEntryLoader(serverEntry) {
14833
16214
  }
14834
16215
  function assertDefaultServerExport(serverEntry) {
14835
16216
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
14836
- const { exports, imports } = transpiler.scan(readFileSync5(serverEntry, "utf8"));
16217
+ const { exports, imports } = transpiler.scan(readFileSync7(serverEntry, "utf8"));
14837
16218
  if (!exports.includes("default")) {
14838
16219
  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.");
14839
16220
  }
@@ -14913,7 +16294,7 @@ function isPprRoute(app, route) {
14913
16294
  return resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route));
14914
16295
  }
14915
16296
  async function addPrerenderFallback(spec, physicalRoutePath, prerender, functionsDir) {
14916
- const fallback = `${basename5(spec.functionName)}.prerender-fallback.html`;
16297
+ const fallback = `${basename6(spec.functionName)}.prerender-fallback.html`;
14917
16298
  const { result } = prerender;
14918
16299
  if (result === undefined) {
14919
16300
  return;
@@ -14931,9 +16312,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
14931
16312
  body = result.html;
14932
16313
  ({ status } = result);
14933
16314
  }
14934
- const fallbackPath = join13(dirname11(join13(functionsDir, spec.functionName)), fallback);
14935
- ensureDir(dirname11(fallbackPath));
14936
- writeFileSync8(fallbackPath, body);
16315
+ const fallbackPath = join13(dirname13(join13(functionsDir, spec.functionName)), fallback);
16316
+ ensureDir(dirname13(fallbackPath));
16317
+ writeFileSync9(fallbackPath, body);
14937
16318
  spec.config.fallback = fallback;
14938
16319
  spec.config.initialHeaders = {
14939
16320
  "content-type": contentType,
@@ -14945,8 +16326,8 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
14945
16326
  }
14946
16327
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
14947
16328
  const aliasPath = join13(functionsDir, `${functionName}.func`);
14948
- ensureDir(dirname11(aliasPath));
14949
- const target = relative9(dirname11(aliasPath), serverFunctionDir);
16329
+ ensureDir(dirname13(aliasPath));
16330
+ const target = relative9(dirname13(aliasPath), serverFunctionDir);
14950
16331
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
14951
16332
  }
14952
16333
  function createExactPrerenderSpec(prerender, routePath) {
@@ -15199,7 +16580,7 @@ process.exit(0);
15199
16580
  ${stderr}
15200
16581
  ${stdout}`);
15201
16582
  }
15202
- const results = JSON.parse(readFileSync5(resultPath, "utf8"));
16583
+ const results = JSON.parse(readFileSync7(resultPath, "utf8"));
15203
16584
  for (const [index, job] of jobs.entries()) {
15204
16585
  const result = results[index];
15205
16586
  await addPrerenderFallback(job.spec, job.path, {
@@ -15298,14 +16679,14 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15298
16679
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
15299
16680
  cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
15300
16681
  const publicDir = join13(rootDir, "public");
15301
- if (existsSync11(publicDir)) {
16682
+ if (existsSync12(publicDir)) {
15302
16683
  cpSync3(publicDir, staticDir, { recursive: true });
15303
16684
  for (const app of apps) {
15304
16685
  const appStaticDir = join13(staticDir, app.prefix.slice(1));
15305
16686
  const appPublicDir = join13(appStaticDir, "public");
15306
16687
  cpSync3(publicDir, appPublicDir, { recursive: true });
15307
16688
  const favicon = join13(publicDir, "favicon.ico");
15308
- if (app.prefix !== "" && existsSync11(favicon)) {
16689
+ if (app.prefix !== "" && existsSync12(favicon)) {
15309
16690
  cpSync3(favicon, join13(appStaticDir, "favicon.ico"));
15310
16691
  }
15311
16692
  }
@@ -15317,19 +16698,21 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15317
16698
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
15318
16699
  }
15319
16700
  const pprResumeKey = crypto.randomUUID();
15320
- const prerenderSpecs = await createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey);
15321
- const appEntry = await materializeServerAppEntry({
15322
- apps: builds.map(({ entryApp, indexHtml }) => ({
15323
- ...entryApp,
15324
- embed: undefined,
15325
- serveAssets: false,
15326
- templateHtml: indexHtml
15327
- })),
15328
- headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
15329
- instances: apps,
15330
- outDir: serverFunctionDir,
15331
- serverEntry
15332
- });
16701
+ const [prerenderSpecs, appEntry] = await Promise.all([
16702
+ createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey),
16703
+ materializeServerAppEntry({
16704
+ apps: builds.map(({ entryApp, indexHtml }) => ({
16705
+ ...entryApp,
16706
+ embed: undefined,
16707
+ serveAssets: false,
16708
+ templateHtml: indexHtml
16709
+ })),
16710
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
16711
+ instances: apps,
16712
+ outDir: serverFunctionDir,
16713
+ serverEntry
16714
+ })
16715
+ ]);
15333
16716
  const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
15334
16717
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
15335
16718
  const serverBuild = await runBunBuild({
@@ -15365,15 +16748,15 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15365
16748
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
15366
16749
  }
15367
16750
  const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
15368
- ensureDir(dirname11(metafilePath));
15369
- writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
16751
+ ensureDir(dirname13(metafilePath));
16752
+ writeFileSync9(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
15370
16753
  `);
15371
16754
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
15372
16755
  }
15373
16756
  const serverBundleBytes = serverBuild.outputs.filter((output) => output.path.endsWith(".js")).reduce((total, output) => total + output.size, 0);
15374
- writeFileSync8(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
16757
+ writeFileSync9(join13(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
15375
16758
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
15376
- writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
16759
+ writeFileSync9(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
15377
16760
  handler: "index.js",
15378
16761
  launcherType: "Nodejs",
15379
16762
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -15384,7 +16767,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15384
16767
  `);
15385
16768
  for (const spec of prerenderSpecs) {
15386
16769
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
15387
- writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
16770
+ writeFileSync9(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
15388
16771
  `);
15389
16772
  }
15390
16773
  const assetRoutes = apps.map((app) => ({
@@ -15414,7 +16797,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15414
16797
  ],
15415
16798
  version: 3
15416
16799
  };
15417
- writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
16800
+ writeFileSync9(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
15418
16801
  `);
15419
16802
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => resolveDocumentMode(prerender.route) === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
15420
16803
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => resolveDocumentMode(route) === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
@@ -15467,6 +16850,7 @@ var configSchema = t.Object({
15467
16850
  clientLogging: t.Optional(t.Boolean()),
15468
16851
  optimizeImports: t.Optional(t.Array(t.String())),
15469
16852
  pagesDir: t.Optional(t.String()),
16853
+ preload: t.Optional(t.Object({ routeChunks: t.Optional(t.Boolean()) })),
15470
16854
  reactCompiler: t.Optional(t.Boolean()),
15471
16855
  rootDir: t.Optional(t.String()),
15472
16856
  serverEntry: t.Optional(t.String()),
@@ -15490,7 +16874,7 @@ init_transform_isomorphic();
15490
16874
  init_instance();
15491
16875
 
15492
16876
  // src/server/router/discovery.ts
15493
- import { existsSync as existsSync12 } from "fs";
16877
+ import { existsSync as existsSync13 } from "fs";
15494
16878
  import { readdir } from "fs/promises";
15495
16879
  import { join as join14, parse as parse4 } from "path";
15496
16880
 
@@ -15591,6 +16975,7 @@ function adaptDefinedPage(route, parent) {
15591
16975
  params: route.schemas?.params,
15592
16976
  parent,
15593
16977
  query: route.schemas?.query,
16978
+ remountDeps: route.remountDeps,
15594
16979
  requestLoader: route.requestLoader
15595
16980
  },
15596
16981
  component,
@@ -15644,7 +17029,7 @@ async function scanPages(pagesDir) {
15644
17029
  async function scanRootLayout(pagesDir) {
15645
17030
  const rootPath = `${pagesDir}/root.tsx`;
15646
17031
  const ctx = getCompileContext();
15647
- if (!(existsSync12(rootPath) || ctx?.modules[rootPath])) {
17032
+ if (!(existsSync13(rootPath) || ctx?.modules[rootPath])) {
15648
17033
  throw new Error("[furin] root.tsx: not found.");
15649
17034
  }
15650
17035
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -15684,8 +17069,8 @@ function getSourceModuleCandidates(dir, name) {
15684
17069
  async function loadConventionComponent(dir, name) {
15685
17070
  const ctx = getCompileContext();
15686
17071
  for (const filePath of getSourceModuleCandidates(dir, name)) {
15687
- if (existsSync12(filePath) || ctx?.modules[filePath]) {
15688
- const moduleSpecifier = IS_DEV && existsSync12(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
17072
+ if (existsSync13(filePath) || ctx?.modules[filePath]) {
17073
+ const moduleSpecifier = IS_DEV && existsSync13(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15689
17074
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15690
17075
  if (mod.default) {
15691
17076
  return { component: mod.default, path: filePath };
@@ -15768,7 +17153,7 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15768
17153
  for (const segment of segments) {
15769
17154
  directory = `${directory}/${segment}`;
15770
17155
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15771
- if (!existsSync12(candidate)) {
17156
+ if (!existsSync13(candidate)) {
15772
17157
  continue;
15773
17158
  }
15774
17159
  const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
@@ -15888,9 +17273,9 @@ init_instance();
15888
17273
  init_lang_detect();
15889
17274
  init_ast_walk();
15890
17275
  init_parser();
15891
- import { readFileSync as readFileSync6 } from "fs";
17276
+ import { readFileSync as readFileSync8 } from "fs";
15892
17277
  function scanFurinInstances(serverEntryPath) {
15893
- const code = readFileSync6(serverEntryPath, "utf8");
17278
+ const code = readFileSync8(serverEntryPath, "utf8");
15894
17279
  const lang = detectLangFromPath(serverEntryPath);
15895
17280
  if (lang === "dts") {
15896
17281
  return [];
@@ -15971,42 +17356,42 @@ function registerIsomorphicRuntimePlugin() {
15971
17356
  function resolveAppSpecs(options, serverEntry, rootDir) {
15972
17357
  if (options.apps && options.apps.length > 0) {
15973
17358
  return options.apps.map((app) => ({
15974
- pagesDir: resolve10(rootDir, app.pagesDir),
17359
+ pagesDir: resolve12(rootDir, app.pagesDir),
15975
17360
  prefix: normalizePrefix(app.prefix)
15976
17361
  }));
15977
17362
  }
15978
17363
  if (options.pagesDir) {
15979
- return [{ pagesDir: resolve10(rootDir, options.pagesDir), prefix: "" }];
17364
+ return [{ pagesDir: resolve12(rootDir, options.pagesDir), prefix: "" }];
15980
17365
  }
15981
17366
  if (serverEntry) {
15982
17367
  const detected = scanFurinInstances(serverEntry);
15983
17368
  if (detected.length > 0) {
15984
17369
  return detected.map((app) => ({
15985
- pagesDir: resolve10(rootDir, app.pagesDir),
17370
+ pagesDir: resolve12(rootDir, app.pagesDir),
15986
17371
  prefix: app.prefix
15987
17372
  }));
15988
17373
  }
15989
17374
  }
15990
- return [{ pagesDir: resolve10(rootDir, "src/pages"), prefix: "" }];
17375
+ return [{ pagesDir: resolve12(rootDir, "src/pages"), prefix: "" }];
15991
17376
  }
15992
17377
  async function buildApp(options) {
15993
17378
  return withProductionBuild(() => buildAppInternal(options));
15994
17379
  }
15995
17380
  async function buildAppInternal(options) {
15996
- const rootDir = resolve10(options.rootDir ?? process.cwd());
17381
+ const rootDir = resolve12(options.rootDir ?? process.cwd());
15997
17382
  const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
15998
17383
  const serverEntry = (() => {
15999
17384
  if (options.target === "static" || options.target === "package") {
16000
17385
  return null;
16001
17386
  }
16002
17387
  if (options.serverEntry) {
16003
- const resolved = resolve10(rootDir, options.serverEntry);
16004
- if (existsSync13(resolved)) {
17388
+ const resolved = resolve12(rootDir, options.serverEntry);
17389
+ if (existsSync14(resolved)) {
16005
17390
  return resolved;
16006
17391
  }
16007
17392
  }
16008
- const entry = resolve10(rootDir, "src/server.ts");
16009
- if (!existsSync13(entry)) {
17393
+ const entry = resolve12(rootDir, "src/server.ts");
17394
+ if (!existsSync14(entry)) {
16010
17395
  throw new Error("[furin] Entrypoint server.ts not found");
16011
17396
  }
16012
17397
  return entry;
@@ -16087,7 +17472,7 @@ async function buildAppInternal(options) {
16087
17472
  throw new Error(`[furin] Unsupported build target "${target}"`);
16088
17473
  }
16089
17474
  }
16090
- writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
17475
+ writeFileSync10(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
16091
17476
  `);
16092
17477
  return {
16093
17478
  manifest,
@@ -16099,8 +17484,8 @@ async function buildAppInternal(options) {
16099
17484
  init_instance();
16100
17485
 
16101
17486
  // src/cli/config.ts
16102
- import { existsSync as existsSync14 } from "fs";
16103
- import { resolve as resolve11 } from "path";
17487
+ import { existsSync as existsSync15 } from "fs";
17488
+ import { resolve as resolve13 } from "path";
16104
17489
  import { pathToFileURL as pathToFileURL3 } from "url";
16105
17490
  import { Validator as Validator2 } from "elysia";
16106
17491
  var compiledConfigSchema = Validator2.create(configSchema);
@@ -16110,8 +17495,8 @@ var DEFAULT_CONFIG_FILENAMES = [
16110
17495
  "furin.config.mjs"
16111
17496
  ];
16112
17497
  async function loadCliConfig(cwd, explicitConfigPath) {
16113
- const rootDir = resolve11(cwd);
16114
- const configPath = explicitConfigPath ? resolve11(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve11(rootDir, filename)).find((path) => existsSync14(path));
17498
+ const rootDir = resolve13(cwd);
17499
+ const configPath = explicitConfigPath ? resolve13(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve13(rootDir, filename)).find((path) => existsSync15(path));
16115
17500
  if (!configPath) {
16116
17501
  return {
16117
17502
  configPath: null,
@@ -16128,19 +17513,19 @@ async function loadCliConfig(cwd, explicitConfigPath) {
16128
17513
  const [firstError] = compiledConfigSchema.Errors(configToValidate);
16129
17514
  throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.instancePath ?? "/"})`);
16130
17515
  }
16131
- const resolvedRootDir = resolve11(rootDir, configToValidate.rootDir ?? ".");
17516
+ const resolvedRootDir = resolve13(rootDir, configToValidate.rootDir ?? ".");
16132
17517
  return {
16133
17518
  ...configToValidate,
16134
17519
  configPath,
16135
- pagesDir: configToValidate.pagesDir ? resolve11(resolvedRootDir, configToValidate.pagesDir) : undefined,
17520
+ pagesDir: configToValidate.pagesDir ? resolve13(resolvedRootDir, configToValidate.pagesDir) : undefined,
16136
17521
  plugins,
16137
17522
  rootDir: resolvedRootDir
16138
17523
  };
16139
17524
  }
16140
17525
 
16141
17526
  // src/cli/preview.ts
16142
- import { existsSync as existsSync15 } from "fs";
16143
- import { isAbsolute as isAbsolute5, join as join16, relative as relative11, resolve as resolve12 } from "path";
17527
+ import { existsSync as existsSync16 } from "fs";
17528
+ import { isAbsolute as isAbsolute7, join as join16, relative as relative11, resolve as resolve14 } from "path";
16144
17529
  var LEADING_SLASHES_RE = /^\/+/;
16145
17530
  var TRAILING_SLASHES_RE2 = /\/+$/;
16146
17531
  function normalizeStaticPreviewBasePath(basePath) {
@@ -16158,11 +17543,11 @@ function startStaticPreview({
16158
17543
  port
16159
17544
  }) {
16160
17545
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
16161
- const distDir = resolve12(rawDistDir);
17546
+ const distDir = resolve14(rawDistDir);
16162
17547
  const indexPath = join16(distDir, "index.html");
16163
17548
  const notFoundPath = join16(distDir, "404.html");
16164
17549
  const faviconPath = join16(distDir, "favicon.ico");
16165
- if (!(existsSync15(indexPath) && existsSync15(notFoundPath))) {
17550
+ if (!(existsSync16(indexPath) && existsSync16(notFoundPath))) {
16166
17551
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
16167
17552
  }
16168
17553
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
@@ -16179,9 +17564,9 @@ function startStaticPreview({
16179
17564
  return notFound();
16180
17565
  }
16181
17566
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
16182
- const exactPath = resolve12(distDir, logicalPath);
17567
+ const exactPath = resolve14(distDir, logicalPath);
16183
17568
  const relativePath = relative11(distDir, exactPath);
16184
- if (relativePath.startsWith("..") || isAbsolute5(relativePath)) {
17569
+ if (relativePath.startsWith("..") || isAbsolute7(relativePath)) {
16185
17570
  return notFound();
16186
17571
  }
16187
17572
  const exactFile = Bun.file(exactPath);
@@ -16204,7 +17589,7 @@ function startStaticPreview({
16204
17589
  routes: {
16205
17590
  ...entryRoutes,
16206
17591
  [`${basePath}/_client/*`]: { dir: clientDir },
16207
- "/favicon.ico": existsSync15(faviconPath) ? Bun.file(faviconPath) : notFound()
17592
+ "/favicon.ico": existsSync16(faviconPath) ? Bun.file(faviconPath) : notFound()
16208
17593
  }
16209
17594
  });
16210
17595
  }
@@ -16282,7 +17667,7 @@ if (command === "preview") {
16282
17667
  if (values.port !== undefined && !/^\d+$/.test(values.port) || !(Number.isInteger(port) && port >= 0 && port <= 65535)) {
16283
17668
  bail(`Invalid preview port "${values.port}". Expected an integer between 0 and 65535.`);
16284
17669
  }
16285
- const distDir = resolve13(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
17670
+ const distDir = resolve15(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
16286
17671
  const basePath = normalizeStaticPreviewBasePath(values.basePath ?? config.static?.basePath ?? "");
16287
17672
  const server = startStaticPreview({ basePath, distDir, port });
16288
17673
  log("Static preview ready");
@@ -16317,8 +17702,8 @@ if (command === "preview") {
16317
17702
  const config = await loadCliConfig(process.cwd(), values.config);
16318
17703
  const isServerlessTarget = target === "static" || target === "package";
16319
17704
  const resolvedServerEntry = isServerlessTarget ? undefined : (() => {
16320
- const entry = resolve13(config.rootDir, config.serverEntry ?? "src/server.ts");
16321
- if (!existsSync16(entry)) {
17705
+ const entry = resolve15(config.rootDir, config.serverEntry ?? "src/server.ts");
17706
+ if (!existsSync17(entry)) {
16322
17707
  const expected = config.serverEntry ?? "src/server.ts";
16323
17708
  throw new Error(`[furin] Entrypoint ${expected} not found`);
16324
17709
  }
@@ -16338,6 +17723,7 @@ if (command === "preview") {
16338
17723
  optimizeImports: config.optimizeImports,
16339
17724
  pagesDir: undefined,
16340
17725
  plugins: config.plugins,
17726
+ preload: config.preload,
16341
17727
  reactCompiler: config.reactCompiler,
16342
17728
  rootDir: config.rootDir,
16343
17729
  serverEntry: resolvedServerEntry,