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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -1
  2. package/dist/build/client.d.ts +4 -1
  3. package/dist/build/elysia-aot-worker.d.ts +22 -0
  4. package/dist/build/elysia-aot.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -0
  6. package/dist/build/entry-template.ts +7 -0
  7. package/dist/build/hydrate.d.ts +1 -1
  8. package/dist/build/index.js +1880 -401
  9. package/dist/build/preload-manifest.d.ts +17 -0
  10. package/dist/build/types.d.ts +6 -0
  11. package/dist/cli/index.js +1878 -408
  12. package/dist/client/client-module.d.ts +26 -0
  13. package/dist/client/define-route.d.ts +9 -0
  14. package/dist/client/document.d.ts +2 -0
  15. package/dist/client/internal/runtime-types.d.ts +2 -0
  16. package/dist/client/link.js +942 -122
  17. package/dist/client/mutation.d.ts +38 -0
  18. package/dist/client/query-store.d.ts +85 -0
  19. package/dist/client/query.d.ts +14 -0
  20. package/dist/client/route-api.d.ts +11 -0
  21. package/dist/client/router/context.d.ts +3 -2
  22. package/dist/client/router/index.d.ts +1 -1
  23. package/dist/client/router/link-utils.d.ts +8 -1
  24. package/dist/client/router/navigation.d.ts +2 -9
  25. package/dist/client/router/optimistic.d.ts +41 -0
  26. package/dist/client/router/search/index.d.ts +3 -3
  27. package/dist/client/router/search-store.d.ts +1 -0
  28. package/dist/client/router/sync-catch-up.d.ts +3 -0
  29. package/dist/client/router/types.d.ts +51 -7
  30. package/dist/client/sync.d.ts +39 -22
  31. package/dist/client.d.ts +11 -33
  32. package/dist/client.js +1219 -59
  33. package/dist/config.d.ts +7 -0
  34. package/dist/config.js +1 -0
  35. package/dist/define-route.d.ts +78 -32
  36. package/dist/env.d.ts +2 -2
  37. package/dist/furin.d.ts +1 -2
  38. package/dist/furin.js +2484 -708
  39. package/dist/plugin/hmr-dependencies.d.ts +2 -0
  40. package/dist/plugin/index.js +349 -18
  41. package/dist/plugin/transform-client-module.d.ts +16 -0
  42. package/dist/plugin/transform-client.d.ts +2 -0
  43. package/dist/plugin/transform-isomorphic.d.ts +1 -1
  44. package/dist/routes.d.ts +6 -0
  45. package/dist/rsc-client.js +87 -16
  46. package/dist/rsc.js +87 -16
  47. package/dist/server/auto-invalidate/registry.d.ts +1 -0
  48. package/dist/server/auto-invalidate/types.d.ts +2 -0
  49. package/dist/server/cache/isr.d.ts +2 -4
  50. package/dist/server/cache/route-cache.d.ts +5 -0
  51. package/dist/server/dev/graph.d.ts +1 -0
  52. package/dist/server/dev-page-plugin.d.ts +5 -19
  53. package/dist/server/internal.d.ts +3 -0
  54. package/dist/server/internal.js +55 -35
  55. package/dist/server/production-server.js +54 -34
  56. package/dist/server/render/loaders.d.ts +4 -2
  57. package/dist/server/render/react-stream.d.ts +3 -0
  58. package/dist/server/render/ssr.d.ts +2 -1
  59. package/dist/server/render/template.d.ts +4 -0
  60. package/dist/server/router/defined-route.d.ts +2 -0
  61. package/dist/server/router/hmr.d.ts +1 -1
  62. package/dist/server/router/patterns.d.ts +2 -0
  63. package/dist/server/router/types.d.ts +1 -1
  64. package/dist/server/sync/adapter.d.ts +25 -4
  65. package/dist/server/sync/atomic.d.ts +25 -0
  66. package/dist/server/sync/drizzle/index.d.ts +45 -0
  67. package/dist/server/sync/drizzle/index.js +540 -0
  68. package/dist/server/sync/execution-error.d.ts +2 -0
  69. package/dist/server/sync/index.d.ts +2 -1
  70. package/dist/server/sync/index.js +533 -105
  71. package/dist/server/sync/mutation-handler.d.ts +4 -0
  72. package/dist/server/sync/plugin.d.ts +34 -11
  73. package/dist/server/sync/postgres/execute.d.ts +3 -0
  74. package/dist/server/sync/postgres/index.d.ts +12 -1
  75. package/dist/server/sync/postgres/index.js +34 -13
  76. package/dist/server/sync/postgres/sql.d.ts +8 -0
  77. package/dist/server/sync/prisma/index.d.ts +24 -0
  78. package/dist/server/sync/prisma/index.js +340 -0
  79. package/dist/server/sync/queries.d.ts +21 -0
  80. package/dist/server/sync/query-context.d.ts +5 -0
  81. package/dist/server/sync/redis/index.js +3 -3
  82. package/dist/server/sync/redis/scripts.d.ts +1 -1
  83. package/dist/server/sync/response.d.ts +1 -0
  84. package/dist/server/sync/sqlite/index.d.ts +3 -0
  85. package/dist/server/sync/sqlite/index.js +10 -4
  86. package/dist/server/sync/stream.d.ts +2 -5
  87. package/dist/server/sync/validation.d.ts +4 -0
  88. package/dist/shared/defer.d.ts +31 -0
  89. package/dist/shared/error.d.ts +2 -2
  90. package/dist/shared/page-key.d.ts +7 -0
  91. package/dist/shared/query-bindings.d.ts +12 -0
  92. package/dist/shared/route-frame.d.ts +1 -0
  93. package/dist/shared/sync-query.d.ts +40 -0
  94. package/package.json +29 -6
  95. package/src/adapter/package.ts +12 -2
  96. package/src/adapter/runtime-build.ts +63 -12
  97. package/src/adapter/static.ts +7 -2
  98. package/src/adapter/vercel.ts +15 -13
  99. package/src/build/client.ts +23 -5
  100. package/src/build/elysia-aot-worker.ts +51 -0
  101. package/src/build/elysia-aot.ts +83 -19
  102. package/src/build/entry-template.ts +7 -0
  103. package/src/build/hydrate.ts +21 -3
  104. package/src/build/preload-manifest.ts +100 -0
  105. package/src/build/production-instrumentation.ts +6 -3
  106. package/src/build/types.ts +4 -0
  107. package/src/cli/index.ts +1 -0
  108. package/src/client/browser-events-runtime.ts +4 -0
  109. package/src/client/client-module.ts +57 -0
  110. package/src/client/define-route.ts +11 -1
  111. package/src/client/document.tsx +28 -18
  112. package/src/client/hmr.ts +2 -1
  113. package/src/client/internal/runtime-types.ts +2 -0
  114. package/src/client/link.tsx +8 -8
  115. package/src/client/mutation.ts +136 -0
  116. package/src/client/query-store.ts +418 -0
  117. package/src/client/query.tsx +67 -0
  118. package/src/client/route-api.tsx +75 -0
  119. package/src/client/router/boundary-tree.tsx +19 -12
  120. package/src/client/router/context.ts +57 -4
  121. package/src/client/router/index.ts +3 -0
  122. package/src/client/router/link-utils.ts +29 -1
  123. package/src/client/router/navigation.ts +3 -50
  124. package/src/client/router/optimistic.ts +233 -0
  125. package/src/client/router/provider.tsx +306 -46
  126. package/src/client/router/search/index.ts +37 -17
  127. package/src/client/router/search-store.ts +4 -0
  128. package/src/client/router/sync-catch-up.ts +7 -0
  129. package/src/client/router/types.ts +73 -9
  130. package/src/client/sync.ts +438 -65
  131. package/src/client.ts +20 -60
  132. package/src/config.ts +5 -0
  133. package/src/define-route.ts +113 -55
  134. package/src/env.d.ts +2 -2
  135. package/src/furin.ts +75 -13
  136. package/src/plugin/hmr-dependencies.ts +58 -0
  137. package/src/plugin/index.ts +38 -2
  138. package/src/plugin/routes.ts +28 -16
  139. package/src/plugin/transform-client-module.ts +123 -0
  140. package/src/plugin/transform-client.ts +293 -13
  141. package/src/plugin/transform-isomorphic.ts +11 -5
  142. package/src/routes.ts +8 -0
  143. package/src/rsc/shared.tsx +104 -18
  144. package/src/server/auto-invalidate/registry.ts +4 -0
  145. package/src/server/auto-invalidate/runtime.ts +17 -0
  146. package/src/server/auto-invalidate/types.ts +6 -0
  147. package/src/server/cache/isr.ts +6 -34
  148. package/src/server/cache/route-cache.ts +40 -4
  149. package/src/server/dev/graph.ts +16 -2
  150. package/src/server/dev-page-plugin.ts +93 -59
  151. package/src/server/internal.ts +3 -0
  152. package/src/server/render/document.tsx +10 -1
  153. package/src/server/render/element.tsx +21 -11
  154. package/src/server/render/isr.ts +61 -29
  155. package/src/server/render/loaders.ts +118 -47
  156. package/src/server/render/mixed-cache.ts +33 -4
  157. package/src/server/render/not-found.ts +4 -7
  158. package/src/server/render/ppr-document.ts +2 -1
  159. package/src/server/render/ppr-route.ts +30 -10
  160. package/src/server/render/react-stream.ts +17 -0
  161. package/src/server/render/route-frame-transport.ts +3 -0
  162. package/src/server/render/ssg.ts +51 -18
  163. package/src/server/render/ssr.ts +53 -8
  164. package/src/server/render/template.ts +23 -0
  165. package/src/server/router/defined-route.ts +3 -0
  166. package/src/server/router/discovery.ts +25 -9
  167. package/src/server/router/hmr.ts +3 -2
  168. package/src/server/router/patterns.ts +16 -0
  169. package/src/server/router/plugin.ts +27 -12
  170. package/src/server/router/types.ts +1 -1
  171. package/src/server/sync/adapter.ts +41 -4
  172. package/src/server/sync/atomic.ts +303 -0
  173. package/src/server/sync/drizzle/index.ts +145 -0
  174. package/src/server/sync/execution-error.ts +1 -0
  175. package/src/server/sync/fingerprint.ts +2 -6
  176. package/src/server/sync/index.ts +6 -0
  177. package/src/server/sync/mutation-handler.ts +69 -0
  178. package/src/server/sync/plugin.ts +177 -60
  179. package/src/server/sync/postgres/execute.ts +20 -0
  180. package/src/server/sync/postgres/index.ts +52 -16
  181. package/src/server/sync/postgres/sql.ts +20 -0
  182. package/src/server/sync/prisma/index.ts +70 -0
  183. package/src/server/sync/queries.ts +75 -0
  184. package/src/server/sync/query-context.ts +85 -0
  185. package/src/server/sync/redis/index.ts +7 -3
  186. package/src/server/sync/redis/scripts.ts +1 -1
  187. package/src/server/sync/response.ts +21 -0
  188. package/src/server/sync/sqlite/index.ts +19 -8
  189. package/src/server/sync/stream.ts +14 -22
  190. package/src/server/sync/validation.ts +34 -0
  191. package/src/shared/defer.ts +48 -0
  192. package/src/shared/error.ts +2 -2
  193. package/src/shared/page-key.ts +36 -0
  194. package/src/shared/query-bindings.ts +138 -0
  195. package/src/shared/route-frame.ts +13 -1
  196. package/src/shared/route-map.ts +12 -2
  197. package/src/shared/sync-query.ts +138 -0
package/dist/cli/index.js CHANGED
@@ -72,6 +72,12 @@ function routeSegmentToPattern(segment) {
72
72
  }
73
73
  return dynamic.catchAll ? "*" : `:${dynamic.name}`;
74
74
  }
75
+ function isRouteGroup(segment) {
76
+ return ROUTE_GROUP_RE.test(segment);
77
+ }
78
+ function routePatternKey(pattern) {
79
+ return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
80
+ }
75
81
  function filePathToPattern(path) {
76
82
  const parts = path.replaceAll("\\", "/").split("/");
77
83
  const segments = [];
@@ -83,6 +89,9 @@ function filePathToPattern(path) {
83
89
  }
84
90
  const isFile = idx === lastIndex;
85
91
  const name = isFile ? parse(part).name : part;
92
+ if (!isFile && isRouteGroup(name)) {
93
+ continue;
94
+ }
86
95
  if (isFile && name === "index") {
87
96
  continue;
88
97
  }
@@ -177,9 +186,11 @@ function buildRouteMatcher(routes) {
177
186
  return null;
178
187
  };
179
188
  }
180
- var DYNAMIC_PARAMETER_NAME_RE, REGEX_META_CHARS_RE;
189
+ var DYNAMIC_PARAMETER_NAME_RE, ROUTE_GROUP_RE, DYNAMIC_ROUTE_SEGMENT_RE, REGEX_META_CHARS_RE;
181
190
  var init_patterns = __esm(() => {
182
191
  DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
192
+ ROUTE_GROUP_RE = /^\([^()]+\)$/;
193
+ DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
183
194
  REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/;
184
195
  });
185
196
 
@@ -290,7 +301,7 @@ var init_instance = __esm(() => {
290
301
  // src/server/dev/graph.ts
291
302
  import { randomUUID } from "crypto";
292
303
  import { readFileSync, statSync } from "fs";
293
- import { dirname as dirname5, extname, resolve as resolve3 } from "path";
304
+ import { dirname as dirname5, extname, isAbsolute as isAbsolute2, resolve as resolve3 } from "path";
294
305
  function normalizeModulePath(path) {
295
306
  return path.replaceAll("\\", "/");
296
307
  }
@@ -303,7 +314,7 @@ function resolveDevSourceImports(source, path, loader) {
303
314
  const isSourceExtension = [".js", ".jsx", ".ts", ".tsx"].includes(extension);
304
315
  const absolute = imported.path.startsWith(".") && extension && !isSourceExtension ? resolve3(dirname5(path), imported.path) : Bun.resolveSync(imported.path, dirname5(path));
305
316
  const resolved = normalizeModulePath(absolute);
306
- if (!resolved.includes("/node_modules/")) {
317
+ if (isAbsolute2(resolved) && !resolved.includes("/node_modules/")) {
307
318
  imports.push(resolved);
308
319
  }
309
320
  } catch {}
@@ -449,6 +460,19 @@ class DevGraph {
449
460
  const normalizedTo = normalizeModulePath(to);
450
461
  return this.importChain(from, normalizedTo).includes(normalizedTo);
451
462
  }
463
+ sourceDependencies(from) {
464
+ const pending = [normalizeModulePath(from)];
465
+ const visited = new Set;
466
+ while (pending.length > 0) {
467
+ const path = pending.pop();
468
+ if (path === undefined || visited.has(path)) {
469
+ continue;
470
+ }
471
+ visited.add(path);
472
+ pending.push(...this.#dependencies.get(path) ?? []);
473
+ }
474
+ return [...visited];
475
+ }
452
476
  clearSourceErrors(path) {
453
477
  const modulePath = normalizeModulePath(path);
454
478
  for (const [message, positions] of this.#sourceErrors) {
@@ -3225,6 +3249,87 @@ var init_dead_code_elimination = __esm(() => {
3225
3249
  ]);
3226
3250
  });
3227
3251
 
3252
+ // src/plugin/transform-client-module.ts
3253
+ import { realpathSync as realpathSync2 } from "fs";
3254
+ import { dirname as dirname7 } from "path";
3255
+ function clientModuleKey(modulePath) {
3256
+ const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
3257
+ return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
3258
+ }
3259
+ function collectClientModuleBindings(program) {
3260
+ const bindings = new Set;
3261
+ for (const statement of program.body) {
3262
+ if (statement.type !== "ImportDeclaration") {
3263
+ continue;
3264
+ }
3265
+ const declaration = statement;
3266
+ if (declaration.importKind === "type" || !FURIN_CLIENT_MODULES.has(String(declaration.source.value))) {
3267
+ continue;
3268
+ }
3269
+ for (const specifier of declaration.specifiers) {
3270
+ const imported = specifier.imported;
3271
+ const local = specifier.local;
3272
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported?.name === "clientModule" && typeof local?.name === "string") {
3273
+ bindings.add(local.name);
3274
+ }
3275
+ }
3276
+ }
3277
+ return bindings;
3278
+ }
3279
+ function dynamicImportSpecifier(loader) {
3280
+ if (loader.type !== "ArrowFunctionExpression" || loader.params.length > 0) {
3281
+ return null;
3282
+ }
3283
+ const body = loader.body;
3284
+ const source = body.type === "ImportExpression" ? body.source : null;
3285
+ return source?.type === "Literal" && typeof source.value === "string" ? source.value : null;
3286
+ }
3287
+ function transformClientModules(source, filename, environment) {
3288
+ if (!source.includes("clientModule")) {
3289
+ return source;
3290
+ }
3291
+ const { program } = parseSource(source, detectLangFromPath(filename));
3292
+ const bindings = collectClientModuleBindings(program);
3293
+ if (bindings.size === 0) {
3294
+ return source;
3295
+ }
3296
+ const transformed = new MagicString(source);
3297
+ walk(program, {
3298
+ CallExpression(node, context) {
3299
+ const call = node;
3300
+ const [loader, ...rest] = call.arguments;
3301
+ if (call.callee.type !== "Identifier" || !bindings.has(call.callee.name) || hasShadowingDeclaration(call.callee.name, context.ancestors()) || !loader || rest.length > 0) {
3302
+ return;
3303
+ }
3304
+ const unwrapped = unwrapTSExpression(loader);
3305
+ const specifier = dynamicImportSpecifier(unwrapped);
3306
+ if (specifier === null) {
3307
+ return;
3308
+ }
3309
+ let key;
3310
+ try {
3311
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname7(filename))));
3312
+ } catch (error) {
3313
+ throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
3314
+ }
3315
+ if (environment === "client") {
3316
+ transformed.appendLeft(loader.end, `, ${key}`);
3317
+ } else {
3318
+ transformed.overwrite(loader.start, loader.end, `${SERVER_LOAD}, ${key}`);
3319
+ }
3320
+ }
3321
+ });
3322
+ return transformed.toString();
3323
+ }
3324
+ var FURIN_CLIENT_MODULES, SERVER_LOAD = '() => Promise.reject(new Error("[furin] clientModule() can only be loaded in the browser."))';
3325
+ var init_transform_client_module = __esm(() => {
3326
+ init_dist();
3327
+ init_dist2();
3328
+ init_lang_detect();
3329
+ init_parser();
3330
+ FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
3331
+ });
3332
+
3228
3333
  // src/plugin/transform-isomorphic.ts
3229
3334
  function importedName(specifier) {
3230
3335
  const { imported } = specifier;
@@ -3445,11 +3550,13 @@ function assertStaticEnvironmentMethods(source, filename, program, bindings, bui
3445
3550
  }
3446
3551
  });
3447
3552
  }
3448
- function transformIsomorphicFunctions(source, filename, environment) {
3553
+ function transformIsomorphicFunctions(input, filename, environment) {
3449
3554
  const lang = detectLangFromPath(filename);
3450
3555
  if (lang === "dts") {
3451
- return { code: source, map: null, transformed: false };
3556
+ return { code: input, map: null, transformed: false };
3452
3557
  }
3558
+ const source = transformClientModules(input, filename, environment);
3559
+ const clientModulesTransformed = source !== input;
3453
3560
  const { program, diagnostics } = parseSource(source, lang);
3454
3561
  const firstError = diagnostics.find((diagnostic) => diagnostic.severity === "error");
3455
3562
  if (firstError) {
@@ -3461,7 +3568,7 @@ function transformIsomorphicFunctions(source, filename, environment) {
3461
3568
  assertNoSplitChains(source, filename, program, builders);
3462
3569
  const candidates = collectCandidates(source, filename, program, bindings);
3463
3570
  if (candidates.length === 0) {
3464
- return { code: source, map: null, transformed: false };
3571
+ return { code: source, map: null, transformed: clientModulesTransformed };
3465
3572
  }
3466
3573
  const transformed = new MagicString(source);
3467
3574
  for (const candidate of candidates) {
@@ -3479,7 +3586,8 @@ function isomorphicTransformPlugin(environment) {
3479
3586
  return {
3480
3587
  name: `furin-isomorphic-${environment}`,
3481
3588
  setup(build) {
3482
- build.onLoad({ filter: SCRIPT_FILE_FILTER }, async ({ path }) => {
3589
+ build.onLoad({ filter: SCRIPT_FILE_FILTER }, async (args) => {
3590
+ const path = args.path.split("?")[0];
3483
3591
  const source = await Bun.file(path).text();
3484
3592
  const loader = detectLoaderFromPath(path);
3485
3593
  const result = transformIsomorphicFunctions(source, path, environment);
@@ -3498,8 +3606,9 @@ var init_transform_isomorphic = __esm(() => {
3498
3606
  init_lang_detect();
3499
3607
  init_parser();
3500
3608
  init_dead_code_elimination();
3609
+ init_transform_client_module();
3501
3610
  FURIN_MODULES = new Set(["@teyik0/furin", "furin"]);
3502
- SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)$/;
3611
+ SCRIPT_FILE_FILTER = /^(?!.*(?:node_modules|[\\/]\.furin[\\/]build[\\/])).*\.(tsx?|jsx?)(?:\?.*)?$/;
3503
3612
  });
3504
3613
 
3505
3614
  // src/server/sync/config.ts
@@ -3579,6 +3688,9 @@ class AutoInvalidateRegistry {
3579
3688
  }
3580
3689
  return [...paths];
3581
3690
  }
3691
+ tagsForPath(path) {
3692
+ return [...this.pathToTags.get(path) ?? []];
3693
+ }
3582
3694
  unregisterPath(urlPath, owner) {
3583
3695
  if (owner === undefined) {
3584
3696
  this.pathOwners.delete(urlPath);
@@ -3632,7 +3744,14 @@ function matchesPath(urlPath, path, type) {
3632
3744
  }
3633
3745
  function createRouteCache(options) {
3634
3746
  const store = new Map;
3747
+ const generations = new Map;
3635
3748
  const pathFromKey = options.pathFromKey ?? defaultPathFromKey;
3749
+ const invalidateGenerations = (key) => {
3750
+ for (const generation of generations.get(key) ?? []) {
3751
+ generation.valid = false;
3752
+ }
3753
+ generations.delete(key);
3754
+ };
3636
3755
  const evictOldest = () => {
3637
3756
  if (options.maxSize === undefined || store.size <= options.maxSize) {
3638
3757
  return;
@@ -3643,6 +3762,7 @@ function createRouteCache(options) {
3643
3762
  }
3644
3763
  };
3645
3764
  const deleteEntry = (key) => {
3765
+ invalidateGenerations(key);
3646
3766
  const entry = store.get(key);
3647
3767
  if (entry === undefined) {
3648
3768
  return false;
@@ -3652,7 +3772,20 @@ function createRouteCache(options) {
3652
3772
  return true;
3653
3773
  };
3654
3774
  return {
3775
+ captureGeneration(key) {
3776
+ const generation = { valid: true };
3777
+ let pending = generations.get(key);
3778
+ if (pending === undefined) {
3779
+ pending = new Set;
3780
+ generations.set(key, pending);
3781
+ }
3782
+ pending.add(generation);
3783
+ return generation;
3784
+ },
3655
3785
  clear() {
3786
+ for (const key of generations.keys()) {
3787
+ invalidateGenerations(key);
3788
+ }
3656
3789
  for (const key of [...store.keys()]) {
3657
3790
  deleteEntry(key);
3658
3791
  }
@@ -3678,14 +3811,15 @@ function createRouteCache(options) {
3678
3811
  invalidatePath(path, type) {
3679
3812
  let deleted = false;
3680
3813
  const purgedPaths = [];
3681
- for (const key of [...store.keys()]) {
3814
+ for (const key of new Set([...store.keys(), ...generations.keys()])) {
3682
3815
  const urlPath = pathFromKey(key);
3683
3816
  if (urlPath === null || !matchesPath(urlPath, path, type)) {
3684
3817
  continue;
3685
3818
  }
3686
- deleteEntry(key);
3687
- deleted = true;
3688
- purgedPaths.push(urlPath);
3819
+ if (deleteEntry(key)) {
3820
+ deleted = true;
3821
+ purgedPaths.push(urlPath);
3822
+ }
3689
3823
  }
3690
3824
  return { deleted, purgedPaths: [...new Set(purgedPaths)] };
3691
3825
  },
@@ -3693,6 +3827,13 @@ function createRouteCache(options) {
3693
3827
  return store.keys();
3694
3828
  },
3695
3829
  name: options.name,
3830
+ releaseGeneration(key, generation) {
3831
+ const pending = generations.get(key);
3832
+ pending?.delete(generation);
3833
+ if (pending?.size === 0) {
3834
+ generations.delete(key);
3835
+ }
3836
+ },
3696
3837
  set(key, entry) {
3697
3838
  const previous = store.get(key);
3698
3839
  if (previous !== undefined) {
@@ -3729,7 +3870,7 @@ var init_registry2 = __esm(() => {
3729
3870
  instanceInvalidators = instanceSlot(() => new Map);
3730
3871
  });
3731
3872
 
3732
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/utils.mjs
3873
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/utils.mjs
3733
3874
  function elapsedMs(startTime) {
3734
3875
  return Math.max(0, Date.now() - startTime);
3735
3876
  }
@@ -3870,7 +4011,7 @@ var init_utils = __esm(() => {
3870
4011
  _isoDate = /* @__PURE__ */ new Date;
3871
4012
  });
3872
4013
 
3873
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/redact-C7FmdhwI.mjs
4014
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/redact-C7FmdhwI.mjs
3874
4015
  function normalizeRedactPathPattern(pattern) {
3875
4016
  if (!pattern.includes("*") && !pattern.includes("."))
3876
4017
  return `**.${pattern}`;
@@ -4179,7 +4320,7 @@ var init_redact_C7FmdhwI = __esm(() => {
4179
4320
  globallyRedacted = Symbol.for("evlog.globallyRedacted");
4180
4321
  });
4181
4322
 
4182
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4323
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/globalRegistry-Bh3bIGwA.mjs
4183
4324
  function logPluginError(name, hook, err) {
4184
4325
  console.error(`[evlog/${name}] ${hook} failed:`, err);
4185
4326
  }
@@ -4349,7 +4490,7 @@ var init_globalRegistry_Bh3bIGwA = __esm(() => {
4349
4490
  globalConfig = getRegistry().config;
4350
4491
  });
4351
4492
 
4352
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4493
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/pretty-error-D8rlWNL1.mjs
4353
4494
  function pushTreeSpacer(children) {
4354
4495
  children.push(PRETTY_ERROR_TREE_SPACER);
4355
4496
  }
@@ -4650,7 +4791,7 @@ var init_pretty_error_D8rlWNL1 = __esm(() => {
4650
4791
  SKIP_FRAME_FN_RE = /^(?:createError|EvlogError|new EvlogError)$/;
4651
4792
  });
4652
4793
 
4653
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4794
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/dev-terminal-Brarc6vc.mjs
4654
4795
  function finalizePrettyError(partial, frameworkOverlay, pretty, inDev) {
4655
4796
  const compact = partial.compact ?? (inDev && pretty);
4656
4797
  const detail = partial.detail ?? (frameworkOverlay ? "guidance" : "full");
@@ -4703,7 +4844,7 @@ var init_dev_terminal_Brarc6vc = __esm(() => {
4703
4844
  };
4704
4845
  });
4705
4846
 
4706
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4847
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/wideEventChannel-BUDW48oP.mjs
4707
4848
  function hasWideEventPublisher() {
4708
4849
  return publisher !== null;
4709
4850
  }
@@ -4719,7 +4860,7 @@ function publishWideEvent(event) {
4719
4860
  var publisher = null;
4720
4861
  var init_wideEventChannel_BUDW48oP = () => {};
4721
4862
 
4722
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4863
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error-brand-D0-DCPvr.mjs
4723
4864
  function isEvlogError(error) {
4724
4865
  return typeof error === "object" && error !== null && error[evlogErrorBrand] === true;
4725
4866
  }
@@ -4728,7 +4869,7 @@ var init_error_brand_D0_DCPvr = __esm(() => {
4728
4869
  evlogErrorBrand = Symbol.for("evlog.error.brand");
4729
4870
  });
4730
4871
 
4731
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/error.mjs
4872
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/error.mjs
4732
4873
  var evlogErrorInternalKey, evlogErrorDataKey, EvlogError;
4733
4874
  var init_error = __esm(() => {
4734
4875
  init_utils();
@@ -4837,7 +4978,7 @@ var init_error = __esm(() => {
4837
4978
  });
4838
4979
  });
4839
4980
 
4840
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4981
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/headers-Bx1ieR-m.mjs
4841
4982
  function extractSafeHeaders(headers) {
4842
4983
  const raw = {};
4843
4984
  headers.forEach((value, key) => {
@@ -4858,7 +4999,7 @@ var init_headers_Bx1ieR_m = __esm(() => {
4858
4999
  init_utils();
4859
5000
  });
4860
5001
 
4861
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/audit-C8euLMvu.mjs
5002
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/audit-C8euLMvu.mjs
4862
5003
  function writePrettyStdout(text) {
4863
5004
  (globalThis.__evlogNativeStdoutWrite ?? nativeStdoutWrite)?.(text);
4864
5005
  }
@@ -5780,12 +5921,12 @@ var init_audit_C8euLMvu = __esm(() => {
5780
5921
  initLogger(__EVLOG_CONFIG__);
5781
5922
  });
5782
5923
 
5783
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/index.mjs
5924
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/index.mjs
5784
5925
  var init_dist3 = __esm(() => {
5785
5926
  init_audit_C8euLMvu();
5786
5927
  });
5787
5928
 
5788
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5929
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/streamResponse-OlirMA5P.mjs
5789
5930
  function shouldDeferEmitForResponse(response) {
5790
5931
  if (!response.body)
5791
5932
  return false;
@@ -5865,7 +6006,7 @@ function bindStreamingResponseLifecycle(response, onComplete) {
5865
6006
  }
5866
6007
  var init_streamResponse_OlirMA5P = () => {};
5867
6008
 
5868
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/errors-CL8dDgIi.mjs
6009
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/errors-CL8dDgIi.mjs
5869
6010
  function extractErrorStatus(error) {
5870
6011
  if (error === null || typeof error !== "object")
5871
6012
  return 500;
@@ -5875,7 +6016,7 @@ function extractErrorStatus(error) {
5875
6016
  }
5876
6017
  var init_errors_CL8dDgIi = () => {};
5877
6018
 
5878
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
6019
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/deferred-drain-CfRYimo5.mjs
5879
6020
  function shouldLog(path, include, exclude) {
5880
6021
  if (exclude && exclude.length > 0) {
5881
6022
  if (exclude.some((pattern) => matchesPattern(path, pattern)))
@@ -5903,7 +6044,7 @@ var init_deferred_drain_CfRYimo5 = __esm(() => {
5903
6044
  init_utils();
5904
6045
  });
5905
6046
 
5906
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/middleware-fam3VyaL.mjs
6047
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/middleware-fam3VyaL.mjs
5907
6048
  function resolveMiddlewarePluginRunner(options) {
5908
6049
  const global2 = getGlobalPluginRunner();
5909
6050
  const local = options.plugins;
@@ -6098,7 +6239,7 @@ var init_middleware_fam3VyaL = __esm(() => {
6098
6239
  runnerCache = /* @__PURE__ */ new WeakMap;
6099
6240
  });
6100
6241
 
6101
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/integration-CGD18W8r.mjs
6242
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/integration-CGD18W8r.mjs
6102
6243
  function attachForkToLogger(storage, parent, middlewareOptions, lifecycle) {
6103
6244
  const log = parent;
6104
6245
  log.fork = (label, fn) => {
@@ -6201,7 +6342,7 @@ var init_integration_CGD18W8r = __esm(() => {
6201
6342
  init_middleware_fam3VyaL();
6202
6343
  });
6203
6344
 
6204
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit/storage.mjs
6345
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit/storage.mjs
6205
6346
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
6206
6347
  function createLoggerStorage(contextHint, id = contextHint) {
6207
6348
  const storage = getSharedStorage(id, () => new AsyncLocalStorage3);
@@ -6220,7 +6361,7 @@ var init_storage = __esm(() => {
6220
6361
  init_globalRegistry_Bh3bIGwA();
6221
6362
  });
6222
6363
 
6223
- // ../../node_modules/.bun/evlog@2.29.0+dbd53f8719b7cf53/node_modules/evlog/dist/toolkit.mjs
6364
+ // ../../node_modules/.bun/evlog@2.29.0+e419d84a67dec76a/node_modules/evlog/dist/toolkit.mjs
6224
6365
  var init_toolkit = __esm(() => {
6225
6366
  init_integration_CGD18W8r();
6226
6367
  init_storage();
@@ -6589,17 +6730,17 @@ var extensionErrorFilterScript = `window.addEventListener("unhandledrejection",
6589
6730
  var init_plugin2 = () => {};
6590
6731
 
6591
6732
  // src/cli/index.ts
6592
- import { existsSync as existsSync16 } from "fs";
6593
- import { resolve as resolve13 } from "path";
6733
+ import { existsSync as existsSync17 } from "fs";
6734
+ import { resolve as resolve15 } from "path";
6594
6735
  import { parseArgs } from "util";
6595
6736
 
6596
6737
  // 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";
6738
+ import { existsSync as existsSync14, writeFileSync as writeFileSync10 } from "fs";
6739
+ import { join as join16, relative as relative10, resolve as resolve12 } from "path";
6599
6740
 
6600
6741
  // 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";
6742
+ import { existsSync as existsSync9, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync6 } from "fs";
6743
+ import { join as join11, resolve as resolve9 } from "path";
6603
6744
 
6604
6745
  // src/build/bun-build.ts
6605
6746
  function runBunBuild(config) {
@@ -6669,6 +6810,7 @@ function buildAppContextBlock(app, varPrefix) {
6669
6810
  const deploymentTargetLine = app.deploymentTarget === undefined ? "" : ` deploymentTarget: ${JSON.stringify(app.deploymentTarget)},`;
6670
6811
  const serveAssetsLine = app.serveAssets === undefined ? "" : ` serveAssets: ${JSON.stringify(app.serveAssets)},`;
6671
6812
  const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
6813
+ const preloadManifestLine = app.preloadManifest ? ` preloadManifest: ${JSON.stringify(app.preloadManifest)},` : "";
6672
6814
  const templateHtmlLine = app.templateHtml === undefined ? "" : ` templateHtml: ${JSON.stringify(app.templateHtml)},`;
6673
6815
  const contextLines = [
6674
6816
  "__setCompileContext({",
@@ -6688,6 +6830,7 @@ function buildAppContextBlock(app, varPrefix) {
6688
6830
  routeMetadataLine,
6689
6831
  serveAssetsLine,
6690
6832
  ssgCacheLine,
6833
+ preloadManifestLine,
6691
6834
  templateHtmlLine,
6692
6835
  ...app.extraContext ?? [],
6693
6836
  "});"
@@ -6846,11 +6989,16 @@ function prepareCompileEntryApps(options) {
6846
6989
  }
6847
6990
 
6848
6991
  // src/build/elysia-aot.ts
6849
- import { dirname as dirname2, resolve } from "path";
6850
- import { aotFactory } from "elysia/plugin/aot/unplugin";
6992
+ import { dirname as dirname2, join as join4, resolve } from "path";
6993
+ import { fileURLToPath as fileURLToPath3 } from "url";
6994
+ import { Worker } from "worker_threads";
6851
6995
  var AOT_NAMESPACE = "furin-elysia-aot";
6852
6996
  var ELYSIA_RESOLVE_DIR = dirname2(Bun.resolveSync("elysia", import.meta.dir));
6997
+ var AOT_WORKER_PATH = join4(dirname2(dirname2(fileURLToPath3(import.meta.resolve("@teyik0/furin")))), "src/build/elysia-aot-worker.ts");
6853
6998
  var SOURCE_FILTER = /\.[cm]?[jt]sx?$/;
6999
+ var ELYSIA_IMPORT_FILTER = /^elysia(?:\/(?!compiled$|type$).*)?$/;
7000
+ var ELYSIA_VIRTUAL_IMPORT_FILTER = /^elysia\/(?:compiled|type)$/;
7001
+ var ANY_MODULE_FILTER = /.*/;
6854
7002
  var WEBSOCKET_STUB_MARKER = "[elysia-aot] WebSocket route builder was stripped (strip mode) but a WS route was used.";
6855
7003
  function loaderFor(path) {
6856
7004
  const extension = path.slice(path.lastIndexOf("."));
@@ -6878,44 +7026,88 @@ export function handleWSResponse(){return e()}
6878
7026
  }
6879
7027
  function elysiaAot(entry) {
6880
7028
  const entryPath = resolve(entry);
6881
- const hooks = aotFactory({ entry, strip: false, target: "bun" });
6882
7029
  return {
6883
7030
  name: "elysia-aot",
6884
7031
  async setup(build) {
7032
+ const worker = new Worker(AOT_WORKER_PATH, { workerData: { entry: entryPath } });
7033
+ const pending = new Map;
7034
+ let nextId = 0;
7035
+ let workerFailure;
7036
+ const fail = (error) => {
7037
+ workerFailure = error;
7038
+ for (const request of pending.values()) {
7039
+ request.reject(error);
7040
+ }
7041
+ pending.clear();
7042
+ };
7043
+ worker.on("message", (response) => {
7044
+ const request = pending.get(response.id);
7045
+ pending.delete(response.id);
7046
+ if (response.ok) {
7047
+ request?.resolve(response);
7048
+ } else {
7049
+ request?.reject(response.error);
7050
+ }
7051
+ });
7052
+ worker.on("error", fail);
7053
+ worker.on("exit", (code) => fail(new Error(`[furin] Elysia AOT worker exited (${code}).`)));
7054
+ const request = (payload) => new Promise((resolveResponse, reject) => {
7055
+ if (workerFailure) {
7056
+ reject(workerFailure);
7057
+ return;
7058
+ }
7059
+ const id = nextId;
7060
+ nextId += 1;
7061
+ pending.set(id, { reject, resolve: resolveResponse });
7062
+ worker.postMessage({ ...payload, id });
7063
+ });
7064
+ let compiled;
7065
+ let virtualType;
6885
7066
  try {
6886
- await hooks.buildStart?.();
7067
+ ({ code: compiled, virtualType } = await request({ method: "start" }));
6887
7068
  } catch (error) {
7069
+ await worker.terminate();
6888
7070
  if (error instanceof Error && error.message.startsWith("[elysia-aot]") && error.message.includes("mounts a sub-app")) {
6889
7071
  console.warn("[furin] Elysia AOT skipped because the app uses .mount().");
6890
7072
  return;
6891
7073
  }
6892
7074
  throw error;
6893
7075
  }
7076
+ build.onEnd(async () => {
7077
+ try {
7078
+ await request({ method: "end" });
7079
+ } finally {
7080
+ await worker.terminate();
7081
+ }
7082
+ });
6894
7083
  const entrySource = await Bun.file(entryPath).text();
6895
- const transformedEntry = await hooks.transform?.(entrySource, entryPath);
7084
+ const { code: transformedEntry } = await request({
7085
+ code: entrySource,
7086
+ method: "transform",
7087
+ path: entryPath
7088
+ });
6896
7089
  if (transformedEntry !== undefined) {
6897
7090
  await Bun.write(entryPath, transformedEntry);
6898
7091
  }
6899
- build.onResolve({ filter: /^elysia(?:\/(?!compiled$|type$).*)?$/ }, ({ path }) => ({
7092
+ build.onResolve({ filter: ELYSIA_IMPORT_FILTER }, ({ path }) => ({
6900
7093
  path: Bun.resolveSync(path, ELYSIA_RESOLVE_DIR)
6901
7094
  }));
6902
- build.onResolve({ filter: /^elysia\/(?:compiled|type)$/ }, ({ path }) => {
6903
- const resolved = hooks.resolveId?.(path);
6904
- return resolved === undefined ? undefined : { namespace: AOT_NAMESPACE, path: resolved };
7095
+ build.onResolve({ filter: ELYSIA_VIRTUAL_IMPORT_FILTER }, ({ path }) => {
7096
+ if (path === "elysia/type" && virtualType === undefined) {
7097
+ return;
7098
+ }
7099
+ return { namespace: AOT_NAMESPACE, path };
6905
7100
  });
6906
- build.onLoad({ filter: /.*/, namespace: AOT_NAMESPACE }, ({ path }) => {
6907
- const contents = hooks.load?.(path);
7101
+ build.onLoad({ filter: ANY_MODULE_FILTER, namespace: AOT_NAMESPACE }, ({ path }) => {
7102
+ const contents = path === "elysia/compiled" ? compiled : virtualType;
6908
7103
  return contents === undefined ? undefined : { contents, loader: "js", resolveDir: ELYSIA_RESOLVE_DIR };
6909
7104
  });
6910
7105
  build.onLoad({ filter: SOURCE_FILTER }, async ({ path }) => {
6911
7106
  if (resolve(path) === entryPath) {
6912
7107
  return;
6913
7108
  }
6914
- if (hooks.transformInclude?.(path) === false) {
6915
- return;
6916
- }
6917
7109
  const original = await Bun.file(path).text();
6918
- const transformed = await hooks.transform?.(original, path);
7110
+ const { code: transformed } = await request({ code: original, method: "transform", path });
6919
7111
  if (transformed === undefined) {
6920
7112
  return;
6921
7113
  }
@@ -6924,23 +7116,20 @@ function elysiaAot(entry) {
6924
7116
  loader: loaderFor(path)
6925
7117
  };
6926
7118
  });
6927
- build.onEnd(() => {
6928
- hooks.buildEnd?.();
6929
- });
6930
7119
  }
6931
7120
  };
6932
7121
  }
6933
7122
 
6934
7123
  // src/build/private-server-sourcemaps.ts
6935
7124
  import { existsSync as existsSync4, renameSync } from "fs";
6936
- import { dirname as dirname3, isAbsolute, join as join4, relative as relative2 } from "path";
7125
+ import { dirname as dirname3, isAbsolute, join as join5, relative as relative2 } from "path";
6937
7126
  function movePrivateServerSourceMaps(outputDir, privateDir, filenames) {
6938
7127
  for (const filename of filenames) {
6939
- const source = isAbsolute(filename) ? filename : join4(outputDir, filename);
7128
+ const source = isAbsolute(filename) ? filename : join5(outputDir, filename);
6940
7129
  if (!existsSync4(source)) {
6941
7130
  continue;
6942
7131
  }
6943
- const destination = join4(privateDir, relative2(outputDir, source));
7132
+ const destination = join5(privateDir, relative2(outputDir, source));
6944
7133
  ensureDir(dirname3(destination));
6945
7134
  renameSync(source, destination);
6946
7135
  }
@@ -6951,9 +7140,9 @@ import { dirname as dirname4, relative as relative3, resolve as resolve2 } from
6951
7140
  var INSTRUMENTATION_IMPORT = /(?:^|[/\\])devtools[/\\]instrumentation(?:\.ts|\.js)?$/;
6952
7141
  var DEV_PAGE_PLUGIN_IMPORT = /(?:^|[/\\])server[/\\]dev-page-plugin(?:\.ts|\.js)?$/;
6953
7142
  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)?$/;
7143
+ var DEV_BUILD_IMPORT = /(?:^|[/\\])(?:build[/\\]hydrate|plugin[/\\](?:route-config-autofix|transform-client))(?:\.ts|\.js)?$/;
6955
7144
  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)?$/;
7145
+ var PRODUCTION_BOUNDARY_IMPORT = /(?:browser-events|instrumentation|dev-page-plugin|diagnostics|graph|plugin|hmr|hydrate|route-config-autofix|transform-client)(?:\.ts|\.js)?$/;
6957
7146
  var PRODUCTION_STUB_NAMESPACE = "furin-production-runtime-stub";
6958
7147
  var FURIN_RUNTIME_ROOT = resolve2(import.meta.dir, "..");
6959
7148
  function isFurinRuntimePath(path) {
@@ -6961,6 +7150,9 @@ function isFurinRuntimePath(path) {
6961
7150
  return fromRuntimeRoot !== ".." && !fromRuntimeRoot.startsWith("../") && !fromRuntimeRoot.startsWith("..\\");
6962
7151
  }
6963
7152
  function devBuildExport(path) {
7153
+ if (path.includes("transform-client")) {
7154
+ return "getHmrDataSignature";
7155
+ }
6964
7156
  return path.includes("route-config-autofix") ? "fixRouteConfigLayout" : "writeDevFiles";
6965
7157
  }
6966
7158
  function productionInstrumentationPlugin() {
@@ -7002,7 +7194,7 @@ function productionInstrumentationPlugin() {
7002
7194
 
7003
7195
  // src/build/server-app-entry.ts
7004
7196
  import { writeFileSync } from "fs";
7005
- import { join as join6 } from "path";
7197
+ import { join as join7 } from "path";
7006
7198
 
7007
7199
  // src/plugin/routes.ts
7008
7200
  import {
@@ -7013,13 +7205,24 @@ import {
7013
7205
  statSync as statSync2,
7014
7206
  watch
7015
7207
  } 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";
7208
+ import { dirname as dirname6, extname as extname2, isAbsolute as isAbsolute3, join as join6, relative as relative4, resolve as resolve4, sep } from "path";
7017
7209
  import { pathToFileURL } from "url";
7018
7210
  import { Elysia } from "elysia";
7019
7211
 
7020
7212
  // src/shared/elysia-contract.ts
7021
7213
  import { Validator } from "elysia";
7022
7214
  var TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
7215
+ function getSchemaValidator(schema) {
7216
+ const validator = Validator.create(schema);
7217
+ if (validator === undefined) {
7218
+ return;
7219
+ }
7220
+ return {
7221
+ Check: (value) => validator.Check(value),
7222
+ Errors: (value) => validator.Errors(value),
7223
+ parse: async (value, type) => validator.From ? await validator.From(value, type) : value
7224
+ };
7225
+ }
7023
7226
  function isTypeBoxObjectSchema(schema) {
7024
7227
  if (schema === null || typeof schema !== "object") {
7025
7228
  return false;
@@ -7193,6 +7396,214 @@ function mergeRouteSchemas(routeChain, key) {
7193
7396
  }
7194
7397
 
7195
7398
  // src/server/router/schemas.ts
7399
+ function decodeQueryPart(value) {
7400
+ return new URLSearchParams(`value=${value}`).get("value") ?? "";
7401
+ }
7402
+ function parseArrayQueryValue(raw, decoded, repeated) {
7403
+ const rawBracketed = raw.startsWith("[") && raw.endsWith("]");
7404
+ const decodedBracketed = decoded.startsWith("[") && decoded.endsWith("]");
7405
+ if (repeated && !rawBracketed && !decodedBracketed) {
7406
+ return [decoded];
7407
+ }
7408
+ if (decoded === "[]") {
7409
+ return [];
7410
+ }
7411
+ if (rawBracketed) {
7412
+ return raw.slice(1, -1).split(",").map(decodeQueryPart);
7413
+ }
7414
+ if (decodedBracketed) {
7415
+ return decoded.slice(1, -1).split(",");
7416
+ }
7417
+ return raw.includes(",") ? raw.split(",").map(decodeQueryPart) : [decoded];
7418
+ }
7419
+ function parseQueryFromURL(search, arrayKeys) {
7420
+ const query = Object.create(null);
7421
+ if (!arrayKeys) {
7422
+ for (const [key, value] of new URLSearchParams(search)) {
7423
+ query[key] = value;
7424
+ }
7425
+ return query;
7426
+ }
7427
+ for (const pair of search.slice(1).split("&")) {
7428
+ const entry = new URLSearchParams(pair).entries().next().value;
7429
+ if (!entry) {
7430
+ continue;
7431
+ }
7432
+ const [key, value] = entry;
7433
+ if (!arrayKeys[key]) {
7434
+ query[key] = value;
7435
+ continue;
7436
+ }
7437
+ const equalIndex = pair.indexOf("=");
7438
+ const rawValue = equalIndex === -1 ? "" : pair.slice(equalIndex + 1);
7439
+ const previous = query[key];
7440
+ const values = parseArrayQueryValue(rawValue, value, Array.isArray(previous));
7441
+ if (Array.isArray(previous)) {
7442
+ previous.push(...values);
7443
+ } else {
7444
+ query[key] = values;
7445
+ }
7446
+ }
7447
+ return query;
7448
+ }
7449
+ function isObjectSchema(schema) {
7450
+ return !!schema && typeof schema === "object";
7451
+ }
7452
+ function isStandardSchema(schema) {
7453
+ return isObjectSchema(schema) && "~standard" in schema;
7454
+ }
7455
+ function collectQueryArrayKeys(schema) {
7456
+ return collectQueryKeys(schema, "array");
7457
+ }
7458
+ function collectQueryObjectKeys(schema) {
7459
+ return collectQueryKeys(schema, "object");
7460
+ }
7461
+ function collectQueryKeys(schema, type) {
7462
+ if (!isObjectSchema(schema)) {
7463
+ return;
7464
+ }
7465
+ const keys = {};
7466
+ if (isObjectSchema(schema.properties)) {
7467
+ for (const [key, value] of Object.entries(schema.properties)) {
7468
+ if (hasSchemaType(value, type)) {
7469
+ keys[key] = 1;
7470
+ }
7471
+ }
7472
+ }
7473
+ for (const keyword of ["allOf", "anyOf"]) {
7474
+ const members = schema[keyword];
7475
+ if (!Array.isArray(members)) {
7476
+ continue;
7477
+ }
7478
+ for (const member of members) {
7479
+ Object.assign(keys, collectQueryKeys(member, type));
7480
+ }
7481
+ }
7482
+ return Object.keys(keys).length > 0 ? keys : undefined;
7483
+ }
7484
+ function hasSchemaType(schema, type) {
7485
+ if (!isObjectSchema(schema)) {
7486
+ return false;
7487
+ }
7488
+ if (schema.type === type) {
7489
+ return true;
7490
+ }
7491
+ for (const keyword of ["allOf", "anyOf"]) {
7492
+ const members = schema[keyword];
7493
+ if (Array.isArray(members) && members.some((member) => hasSchemaType(member, type))) {
7494
+ return true;
7495
+ }
7496
+ }
7497
+ return false;
7498
+ }
7499
+ function parseJsonQueryObjects(query, objectKeys) {
7500
+ if (!objectKeys) {
7501
+ return query;
7502
+ }
7503
+ const parsed = { ...query };
7504
+ for (const key of Object.keys(objectKeys)) {
7505
+ const value = parsed[key];
7506
+ if (typeof value !== "string") {
7507
+ continue;
7508
+ }
7509
+ try {
7510
+ parsed[key] = JSON.parse(value);
7511
+ } catch {
7512
+ parsed[key] = value;
7513
+ }
7514
+ }
7515
+ return parsed;
7516
+ }
7517
+ function coerceUnionValue(members, value) {
7518
+ for (const member of members) {
7519
+ const candidate = coerceSchemaValue(member, value);
7520
+ const validator = getSchemaValidator(member);
7521
+ if (validator?.Check(candidate)) {
7522
+ return candidate;
7523
+ }
7524
+ }
7525
+ return value;
7526
+ }
7527
+ function coerceObjectValue(properties, value) {
7528
+ const coerced = { ...value };
7529
+ for (const [key, propertySchema] of Object.entries(properties)) {
7530
+ if (key in coerced) {
7531
+ coerced[key] = coerceSchemaValue(propertySchema, coerced[key]);
7532
+ }
7533
+ }
7534
+ return coerced;
7535
+ }
7536
+ function coerceStringValue(schema, value) {
7537
+ if (value.length === 0) {
7538
+ return value;
7539
+ }
7540
+ if (schema.type === "boolean") {
7541
+ if (value === "true") {
7542
+ return true;
7543
+ }
7544
+ if (value === "false") {
7545
+ return false;
7546
+ }
7547
+ return value;
7548
+ }
7549
+ if (schema.type === "number" || schema.type === "integer") {
7550
+ const number = Number(value);
7551
+ if (Number.isFinite(number) && (schema.type !== "integer" || Number.isInteger(number))) {
7552
+ return number;
7553
+ }
7554
+ }
7555
+ return value;
7556
+ }
7557
+ function coerceSchemaValue(schema, value) {
7558
+ if (!isObjectSchema(schema)) {
7559
+ return value;
7560
+ }
7561
+ if (Array.isArray(schema.anyOf)) {
7562
+ return coerceUnionValue(schema.anyOf, value);
7563
+ }
7564
+ if (Array.isArray(schema.allOf)) {
7565
+ return schema.allOf.reduce((candidate, member) => coerceSchemaValue(member, candidate), value);
7566
+ }
7567
+ if (schema.type === "object" && isObjectSchema(schema.properties) && isObjectSchema(value)) {
7568
+ return coerceObjectValue(schema.properties, value);
7569
+ }
7570
+ if (schema.type === "array" && Array.isArray(value)) {
7571
+ return value.map((entry) => coerceSchemaValue(schema.items, entry));
7572
+ }
7573
+ return typeof value === "string" ? coerceStringValue(schema, value) : value;
7574
+ }
7575
+ function coerceRouteInput(schema, value) {
7576
+ return coerceSchemaValue(schema, value);
7577
+ }
7578
+ async function validateRouteInput(input, schema, type) {
7579
+ const inputWithDefaults = isStandardSchema(schema) ? input : applySchemaDefaults(schema, input);
7580
+ const valueToValidate = isStandardSchema(schema) ? inputWithDefaults : coerceRouteInput(schema, inputWithDefaults);
7581
+ const validator = getSchemaValidator(schema);
7582
+ try {
7583
+ const parsed = await validator?.parse(valueToValidate, type);
7584
+ return {
7585
+ ok: true,
7586
+ value: parsed ?? valueToValidate
7587
+ };
7588
+ } catch {
7589
+ return { errors: [...validator?.Errors(valueToValidate) ?? []], ok: false };
7590
+ }
7591
+ }
7592
+ async function parseRouteQuery(url, schema) {
7593
+ if (!schema) {
7594
+ return { ok: true, query: parseQueryFromURL(url.search) };
7595
+ }
7596
+ const rawQuery = isStandardSchema(schema) ? parseQueryFromURL(url.search) : parseJsonQueryObjects(parseQueryFromURL(url.search, collectQueryArrayKeys(schema)), collectQueryObjectKeys(schema));
7597
+ const result = await validateRouteInput(rawQuery, schema, "query");
7598
+ return result.ok ? { ok: true, query: result.value } : result;
7599
+ }
7600
+ async function parseRouteParams(params, schema) {
7601
+ if (!schema) {
7602
+ return { ok: true, params };
7603
+ }
7604
+ const result = await validateRouteInput(params, schema, "params");
7605
+ return result.ok ? { ok: true, params: result.value } : result;
7606
+ }
7196
7607
  function createSearchRouteMetadata(routes) {
7197
7608
  const metadata = [];
7198
7609
  for (const route of routes) {
@@ -7208,6 +7619,23 @@ function createSearchRouteMetadata(routes) {
7208
7619
  }
7209
7620
  return metadata;
7210
7621
  }
7622
+ function applySchemaDefaults(schema, values) {
7623
+ if (!schema || typeof schema !== "object") {
7624
+ return values;
7625
+ }
7626
+ const s = schema;
7627
+ if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
7628
+ return values;
7629
+ }
7630
+ const result = { ...values };
7631
+ const properties = s.properties;
7632
+ for (const [key, propSchema] of Object.entries(properties)) {
7633
+ if (!(key in result) && propSchema && typeof propSchema === "object" && "default" in propSchema) {
7634
+ result[key] = propSchema.default;
7635
+ }
7636
+ }
7637
+ return result;
7638
+ }
7211
7639
 
7212
7640
  // src/plugin/routes.ts
7213
7641
  init_lang_detect();
@@ -7241,12 +7669,13 @@ function instanceNamespace(instance) {
7241
7669
  return `${ROUTES_NAMESPACE_PREFIX}-${Bun.hash(instanceKey(instance)).toString(16)}`;
7242
7670
  }
7243
7671
  function scanRouteFiles(directory, directorySegments, files) {
7244
- for (const entry of readdirSync2(directory, { withFileTypes: true })) {
7672
+ const entries = readdirSync2(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
7673
+ for (const entry of entries) {
7245
7674
  if (entry.isDirectory()) {
7246
7675
  if (entry.name.startsWith("_")) {
7247
7676
  continue;
7248
7677
  }
7249
- scanRouteFiles(join5(directory, entry.name), [...directorySegments, entry.name], files);
7678
+ scanRouteFiles(join6(directory, entry.name), [...directorySegments, entry.name], files);
7250
7679
  continue;
7251
7680
  }
7252
7681
  const extension = extname2(entry.name);
@@ -7254,7 +7683,7 @@ function scanRouteFiles(directory, directorySegments, files) {
7254
7683
  continue;
7255
7684
  }
7256
7685
  const base = entry.name.slice(0, -extension.length);
7257
- const sourcePath = join5(directory, entry.name);
7686
+ const sourcePath = join6(directory, entry.name);
7258
7687
  for (const segment of [...directorySegments, base]) {
7259
7688
  parseDynamicRouteSegment(segment, sourcePath);
7260
7689
  }
@@ -7274,9 +7703,6 @@ function scanRouteFiles(directory, directorySegments, files) {
7274
7703
  function segmentPath(segment) {
7275
7704
  return routeSegmentToPattern(segment);
7276
7705
  }
7277
- function routePath(segments) {
7278
- return segments.length === 0 ? "/" : `/${segments.map(segmentPath).join("/")}`;
7279
- }
7280
7706
  function routeId(instanceId, path) {
7281
7707
  const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
7282
7708
  return `_route_${instanceId}_${encodedPath}`;
@@ -7305,14 +7731,22 @@ function buildRouteTree(pagesDir, instanceId) {
7305
7731
  return node;
7306
7732
  };
7307
7733
  const root = ensureNode([]);
7734
+ const seenPatterns = new Map;
7308
7735
  for (const file of scannedFiles) {
7309
7736
  const node = ensureNode(file.directorySegments);
7310
7737
  if (file.base === "_route") {
7311
- const path = `${routePath(file.directorySegments)}#layout`;
7738
+ const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
7312
7739
  node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
7313
7740
  continue;
7314
7741
  }
7315
- const path = file.base === "index" ? routePath(file.directorySegments) : routePath([...file.directorySegments, file.base]);
7742
+ const path = filePathToPattern(relative4(pagesDir, file.sourcePath));
7743
+ const patternKey = routePatternKey(path);
7744
+ const relativePath = relative4(pagesDir, file.sourcePath).replaceAll("\\", "/");
7745
+ const previousPath = seenPatterns.get(patternKey);
7746
+ if (previousPath !== undefined) {
7747
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
7748
+ }
7749
+ seenPatterns.set(patternKey, relativePath);
7316
7750
  const route = { id: routeId(instanceId, path), path, sourcePath: file.sourcePath };
7317
7751
  if (file.base === "index") {
7318
7752
  node.indexRoute = route;
@@ -7347,7 +7781,7 @@ function routeSourcePaths(instance) {
7347
7781
  }
7348
7782
  function emitRouteNode(node, indentation, includeRootCatchAll) {
7349
7783
  const childIndentation = `${indentation} `;
7350
- const prefix = node.name ? `/${segmentPath(node.name)}` : "";
7784
+ const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
7351
7785
  const head = `new Elysia({ prefix: ${JSON.stringify(prefix)} })`;
7352
7786
  const content = [];
7353
7787
  if (node.indexRoute) {
@@ -7456,16 +7890,16 @@ function findPackageRoot(sourcePath) {
7456
7890
  const fallback = dirname6(sourcePath);
7457
7891
  let directory = fallback;
7458
7892
  while (dirname6(directory) !== directory) {
7459
- if (existsSync5(join5(directory, "package.json"))) {
7893
+ if (existsSync5(join6(directory, "package.json"))) {
7460
7894
  return directory;
7461
7895
  }
7462
7896
  directory = dirname6(directory);
7463
7897
  }
7464
- return existsSync5(join5(directory, "package.json")) ? directory : fallback;
7898
+ return existsSync5(join6(directory, "package.json")) ? directory : fallback;
7465
7899
  }
7466
7900
  function isWithinDirectory(path, directory) {
7467
7901
  const relativePath = relative4(directory, path);
7468
- return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute2(relativePath));
7902
+ return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute3(relativePath));
7469
7903
  }
7470
7904
  function isFurinPackageImport(specifier) {
7471
7905
  return specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/");
@@ -7483,7 +7917,7 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
7483
7917
  }
7484
7918
  try {
7485
7919
  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")) {
7920
+ if (isAbsolute3(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative4(packageRoot, resolvedImport).split(sep).includes("node_modules")) {
7487
7921
  resolvedImports.push(resolvedImport);
7488
7922
  }
7489
7923
  } catch {}
@@ -7557,7 +7991,7 @@ async function clientRoutesSource(instance) {
7557
7991
  const module = await loadRouteModule(routeFile.sourcePath);
7558
7992
  validateRouteParams(routeFile.path, module.route?.schemas);
7559
7993
  return {
7560
- hasLoader: module.route?.loader !== undefined || module.route?.useLoaderData !== undefined,
7994
+ hasLoader: module.route?.loader !== undefined,
7561
7995
  mode: module.route?.mode ?? "ssr",
7562
7996
  pattern: routeFile.path
7563
7997
  };
@@ -7581,8 +8015,8 @@ function serverProxySource(instance, includeRootCatchAll) {
7581
8015
  function createRoutesPlugin(options) {
7582
8016
  const routeFilesBySpecifier = new Map;
7583
8017
  const routeFilesByResolvedPath = new Map;
7584
- const registryVirtualPath = join5(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
7585
- const composableRegistryVirtualPath = join5(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
8018
+ const registryVirtualPath = join6(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry.ts?furin-virtual");
8019
+ const composableRegistryVirtualPath = join6(resolve4(primaryInstance(options.instances).pagesDir), ".furin-routes-registry-composable.ts?furin-virtual");
7586
8020
  const instancesBySpecifier = new Map(options.instances.flatMap((instance) => [
7587
8021
  [
7588
8022
  routeModuleSpecifier(instance),
@@ -7663,11 +8097,11 @@ async function materializeServerAppEntry(options) {
7663
8097
  if (!instance) {
7664
8098
  throw new Error(`[furin] Missing route instance for server app ${index}.`);
7665
8099
  }
7666
- const routePath = join6(options.outDir, `_furin-routes-${index}.ts`);
8100
+ const routePath = join7(options.outDir, `_furin-routes-${index}.ts`);
7667
8101
  writeFileSync(routePath, await materializedRouteModuleSource(instance));
7668
8102
  return { ...app, nativeRoutes: toPosixPath(routePath) };
7669
8103
  }));
7670
- const entryPath = join6(options.outDir, "_furin-app.ts");
8104
+ const entryPath = join7(options.outDir, "_furin-app.ts");
7671
8105
  writeFileSync(entryPath, buildEntrySource({
7672
8106
  apps,
7673
8107
  headerComment: options.headerComment,
@@ -7697,7 +8131,7 @@ if (typeof startServer === "function") {
7697
8131
  init_transform_isomorphic();
7698
8132
 
7699
8133
  // src/rsc/build/environment.ts
7700
- import { fileURLToPath as fileURLToPath3 } from "url";
8134
+ import { fileURLToPath as fileURLToPath4 } from "url";
7701
8135
  var SERVER_ONLY_RE = /^(?:@teyik0\/)?furin\/server-only$/;
7702
8136
  var CLIENT_ONLY_RE = /^(?:@teyik0\/)?furin\/client-only$/;
7703
8137
  function environmentGuardPlugin(graph) {
@@ -7708,13 +8142,13 @@ function environmentGuardPlugin(graph) {
7708
8142
  if (graph === "client") {
7709
8143
  throw new Error(`[furin] ${args.importer} imports furin/server-only from the client graph.`);
7710
8144
  }
7711
- return { path: fileURLToPath3(import.meta.resolve("../../server-only.ts")) };
8145
+ return { path: fileURLToPath4(import.meta.resolve("../../server-only.ts")) };
7712
8146
  });
7713
8147
  build.onResolve({ filter: CLIENT_ONLY_RE }, (args) => {
7714
8148
  if (graph !== "client") {
7715
8149
  throw new Error(`[furin] ${args.importer} imports furin/client-only from the ${graph} graph.`);
7716
8150
  }
7717
- return { path: fileURLToPath3(import.meta.resolve("../../client-only.ts")) };
8151
+ return { path: fileURLToPath4(import.meta.resolve("../../client-only.ts")) };
7718
8152
  });
7719
8153
  }
7720
8154
  };
@@ -7746,13 +8180,13 @@ function assertNoPrefixSlugCollisions(prefixes) {
7746
8180
  }
7747
8181
 
7748
8182
  // 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";
7751
- import { fileURLToPath as fileURLToPath5 } from "url";
8183
+ import { existsSync as existsSync8, realpathSync as realpathSync4, writeFileSync as writeFileSync5 } from "fs";
8184
+ import { basename as basename5, dirname as dirname11, isAbsolute as isAbsolute5, join as join10, relative as relative6, resolve as resolve8 } from "path";
8185
+ import { fileURLToPath as fileURLToPath6 } from "url";
7752
8186
 
7753
8187
  // 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";
8188
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, writeFileSync as writeFileSync3 } from "fs";
8189
+ import { basename as basename3, dirname as dirname9, join as join8, resolve as resolve7 } from "path";
7756
8190
 
7757
8191
  // src/plugin/transform-client.ts
7758
8192
  init_dist();
@@ -7760,13 +8194,60 @@ init_dist2();
7760
8194
  init_lang_detect();
7761
8195
  init_parser();
7762
8196
  init_dead_code_elimination();
8197
+
8198
+ // src/plugin/hmr-dependencies.ts
8199
+ init_lang_detect();
8200
+ import { readFileSync as readFileSync3 } from "fs";
8201
+ import { dirname as dirname8, isAbsolute as isAbsolute4, resolve as resolve5 } from "path";
8202
+ var SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
8203
+ function hmrDependencySignature(imports, filename) {
8204
+ const routePath = resolve5(filename);
8205
+ const visited = new Set;
8206
+ const hash = new Bun.CryptoHasher("sha256");
8207
+ const visit = (specifier, importer) => {
8208
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
8209
+ return true;
8210
+ }
8211
+ const path = Bun.resolveSync(specifier, dirname8(importer));
8212
+ if (path === routePath) {
8213
+ return false;
8214
+ }
8215
+ hash.update(JSON.stringify([specifier, path]));
8216
+ if (!isAbsolute4(path) || path.replaceAll("\\", "/").includes("/node_modules/") || visited.has(path)) {
8217
+ return true;
8218
+ }
8219
+ visited.add(path);
8220
+ const source = readFileSync3(path, "utf8");
8221
+ hash.update(source);
8222
+ if (SCRIPT_FILE.test(path)) {
8223
+ const transpiler = new Bun.Transpiler({ loader: detectLoaderFromPath(path) });
8224
+ for (const dependency of transpiler.scanImports(source)) {
8225
+ if (!visit(dependency.path, path)) {
8226
+ return false;
8227
+ }
8228
+ }
8229
+ }
8230
+ return true;
8231
+ };
8232
+ try {
8233
+ for (const specifier of imports) {
8234
+ if (!visit(specifier, routePath)) {
8235
+ return;
8236
+ }
8237
+ }
8238
+ return hash.digest("hex");
8239
+ } catch {}
8240
+ }
8241
+
8242
+ // src/plugin/transform-client.ts
7763
8243
  init_transform_isomorphic();
7764
- var FURIN_CLIENT_MODULES = new Set(["@teyik0/furin/client", "furin/client"]);
8244
+ var FURIN_CLIENT_MODULES2 = new Set(["@teyik0/furin/client", "furin/client"]);
7765
8245
  var FURIN_SERVER_MODULES = new Set(["@teyik0/furin", "furin"]);
7766
8246
  var REACT_COMPONENT_WRAPPERS = new Set(["forwardRef", "memo"]);
7767
8247
  var SERVER_ONLY_METHODS = new Set(["config", "head", "loader", "requestLoader", "staticParams"]);
7768
8248
  var REACT_HOOK_NAME_RE = /^use[A-Z0-9]/;
7769
8249
  var HMR_DATA_SIGNATURE = "furin.hmr.data-signature";
8250
+ var HMR_SOURCE_SIGNATURE = "furin.hmr.source-signature";
7770
8251
  var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7771
8252
  ["TSAsExpression", ["expression"]],
7772
8253
  ["TSInstantiationExpression", ["expression"]],
@@ -7776,7 +8257,7 @@ var TYPESCRIPT_RUNTIME_WRAPPERS = new Map([
7776
8257
  ["TSTypeAssertion", ["expression"]]
7777
8258
  ]);
7778
8259
  function isFurinRouteModule(source) {
7779
- return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES.has(source));
8260
+ return typeof source === "string" && (FURIN_SERVER_MODULES.has(source) || FURIN_CLIENT_MODULES2.has(source));
7780
8261
  }
7781
8262
  function importedName2(specifier) {
7782
8263
  const { imported } = specifier;
@@ -7876,8 +8357,51 @@ function chainRootIsDefineRoute(node, bindings, ancestors) {
7876
8357
  }
7877
8358
  return false;
7878
8359
  }
7879
- function removeChainedServerCalls(source, program, bindings) {
8360
+ function assertCompleteRouteChains(program, bindings, filename) {
8361
+ const namespaces = new Set;
8362
+ for (const statement of program.body) {
8363
+ if (statement.type !== "ImportDeclaration") {
8364
+ continue;
8365
+ }
8366
+ const declaration = statement;
8367
+ if (!isFurinRouteModule(declaration.source.value) || declaration.importKind === "type") {
8368
+ continue;
8369
+ }
8370
+ for (const specifier of declaration.specifiers) {
8371
+ const name = localName2(specifier);
8372
+ if (name && specifier.type === "ImportNamespaceSpecifier") {
8373
+ namespaces.add(name);
8374
+ }
8375
+ }
8376
+ }
8377
+ walk(program, {
8378
+ MemberExpression(node, context) {
8379
+ const object = asAstNode(node.object);
8380
+ const property = asAstNode(node.property);
8381
+ const method = property?.type === "Identifier" ? property.name : property?.value;
8382
+ if (object?.type === "Identifier" && typeof object.name === "string" && namespaces.has(object.name) && (method === "defineRoute" || method === "defineRootRoute") && !hasShadowingDeclaration(object.name, context.ancestors())) {
8383
+ throw new Error(`[furin] ${filename}: route builders require a named import.`);
8384
+ }
8385
+ if (node.computed && context.parent?.type === "CallExpression" && chainRootIsDefineRoute(node.object, bindings, context.ancestors())) {
8386
+ throw new Error(`[furin] ${filename}: route builders require static builder methods.`);
8387
+ }
8388
+ },
8389
+ VariableDeclarator(node, context) {
8390
+ const initializer = asAstNode(node.init);
8391
+ if (!(initializer && chainRootIsDefineRoute(initializer, bindings, context.ancestors()))) {
8392
+ return;
8393
+ }
8394
+ const callee = initializer.type === "CallExpression" ? asAstNode(initializer.callee) : null;
8395
+ const method = callee?.type === "MemberExpression" ? asAstNode(callee.property) : null;
8396
+ if (method?.type !== "Identifier" || method.name !== "page" && method.name !== "layout") {
8397
+ throw new Error(`[furin] ${filename}: route builders must use one fluent chain ending in .page() or .layout().`);
8398
+ }
8399
+ }
8400
+ });
8401
+ }
8402
+ function removeChainedServerCalls(source, program, bindings, configBindings, filename) {
7880
8403
  let transformed = rewriteClientImports(source, program, bindings);
8404
+ const { declarations } = collectModuleBindings(program);
7881
8405
  walk(program, {
7882
8406
  CallExpression(call, context) {
7883
8407
  const callee = asAstNode(call.callee);
@@ -7892,22 +8416,103 @@ function removeChainedServerCalls(source, program, bindings) {
7892
8416
  if (!object) {
7893
8417
  return;
7894
8418
  }
8419
+ if (property.name === "config" && Array.isArray(call.arguments)) {
8420
+ const config = asAstNode(call.arguments[0]);
8421
+ if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8422
+ collectConfigBindings(config, declarations, configBindings);
8423
+ const remount = resolveRemountProperty(config, declarations, configBindings, new Set, filename);
8424
+ if (remount) {
8425
+ source.update(object.end, call.end, `.config({ ${source.original.slice(remount.start, remount.end)} })`);
8426
+ transformed = true;
8427
+ return;
8428
+ }
8429
+ }
8430
+ }
7895
8431
  source.remove(object.end, call.end);
7896
8432
  transformed = true;
7897
8433
  }
7898
8434
  });
7899
8435
  return transformed;
7900
8436
  }
7901
- function collectBindingNames(pattern, names) {
7902
- const node = asAstNode(pattern);
7903
- if (!node) {
7904
- return;
8437
+ function collectConfigBindings(config, declarations, names) {
8438
+ if (config?.type === "Identifier" && typeof config.name === "string" && !names.has(config.name)) {
8439
+ names.add(config.name);
8440
+ const declaration = declarations.get(config.name);
8441
+ collectConfigBindings(asAstNode(declaration?.init), declarations, names);
8442
+ } else if (config?.type === "ObjectExpression" && Array.isArray(config.properties)) {
8443
+ for (const property of config.properties) {
8444
+ const entry = asAstNode(property);
8445
+ if (entry?.type === "SpreadElement") {
8446
+ collectConfigBindings(asAstNode(entry.argument), declarations, names);
8447
+ }
8448
+ }
7905
8449
  }
7906
- if (node.type === "Identifier" && typeof node.name === "string") {
7907
- names.push(node.name);
7908
- return;
8450
+ }
8451
+ function resolveRemountProperty(config, declarations, configBindings, visiting, filename) {
8452
+ if (config?.type === "Identifier" && typeof config.name === "string" && !visiting.has(config.name)) {
8453
+ visiting.add(config.name);
8454
+ configBindings.add(config.name);
8455
+ const declaration = declarations.get(config.name);
8456
+ const result = resolveRemountProperty(asAstNode(declaration?.init), declarations, configBindings, visiting, filename);
8457
+ visiting.delete(config.name);
8458
+ return result;
7909
8459
  }
7910
- if (node.type === "AssignmentPattern") {
8460
+ if (config?.type !== "ObjectExpression" || !Array.isArray(config.properties)) {
8461
+ throw new Error(`[furin] ${filename}: route config spreads must resolve to local object literals; declare remountDeps after dynamic spreads.`);
8462
+ }
8463
+ for (let index = config.properties.length - 1;index >= 0; index -= 1) {
8464
+ const entry = asAstNode(config.properties[index]);
8465
+ if (entry?.type === "SpreadElement") {
8466
+ const remount = resolveRemountProperty(asAstNode(entry.argument), declarations, configBindings, visiting, filename);
8467
+ if (remount) {
8468
+ return remount;
8469
+ }
8470
+ } else if (entry?.type === "Property") {
8471
+ const key = asAstNode(entry.key);
8472
+ if (key?.type === "Identifier" && entry.computed !== true && key.name === "remountDeps" || key?.type === "Literal" && key.value === "remountDeps") {
8473
+ return entry;
8474
+ }
8475
+ }
8476
+ }
8477
+ return null;
8478
+ }
8479
+ function pruneUnusedConfigBindings(source, filename, names) {
8480
+ let result = source;
8481
+ let pruned = true;
8482
+ while (pruned) {
8483
+ pruned = false;
8484
+ const code = result.toString();
8485
+ const { program } = parseSource(code, detectLangFromPath(filename));
8486
+ const references = new Set;
8487
+ walkWithAncestors(program, [], (node, ancestors) => {
8488
+ if (node.type === "Identifier" && typeof node.name === "string" && isReferenceIdentifier(node, ancestors)) {
8489
+ references.add(node.name);
8490
+ }
8491
+ });
8492
+ result = new MagicString(code);
8493
+ for (const statement of program.body) {
8494
+ if (statement.type !== "VariableDeclaration") {
8495
+ continue;
8496
+ }
8497
+ const retained = statement.declarations.filter((declaration) => declaration.id.type !== "Identifier" || !names.has(declaration.id.name) || references.has(declaration.id.name));
8498
+ if (retained.length !== statement.declarations.length) {
8499
+ result.update(statement.start, statement.end, retained.length ? `${statement.kind} ${retained.map((node) => code.slice(node.start, node.end)).join(", ")};` : "");
8500
+ pruned = true;
8501
+ }
8502
+ }
8503
+ }
8504
+ return result;
8505
+ }
8506
+ function collectBindingNames(pattern, names) {
8507
+ const node = asAstNode(pattern);
8508
+ if (!node) {
8509
+ return;
8510
+ }
8511
+ if (node.type === "Identifier" && typeof node.name === "string") {
8512
+ names.push(node.name);
8513
+ return;
8514
+ }
8515
+ if (node.type === "AssignmentPattern") {
7911
8516
  collectBindingNames(node.left, names);
7912
8517
  return;
7913
8518
  }
@@ -7949,13 +8554,13 @@ function collectDeclarationBindings(declaration, declarations) {
7949
8554
  }
7950
8555
  function collectModuleBindings(program) {
7951
8556
  const declarations = new Map;
7952
- const imports = new Set;
8557
+ const imports = new Map;
7953
8558
  for (const statement of program.body) {
7954
8559
  if (statement.type === "ImportDeclaration" && Array.isArray(statement.specifiers)) {
7955
8560
  for (const specifier of statement.specifiers) {
7956
8561
  const local = localName2(specifier);
7957
8562
  if (local) {
7958
- imports.add(local);
8563
+ imports.set(local, statement);
7959
8564
  }
7960
8565
  }
7961
8566
  continue;
@@ -8043,13 +8648,16 @@ function walkWithAncestors(value, ancestors, visitor) {
8043
8648
  }
8044
8649
  }
8045
8650
  function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8046
- if (child.type !== "Identifier" || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8651
+ const parent = ancestors.at(-1);
8652
+ 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);
8653
+ if (!(child.type === "Identifier" || jsxReference) || typeof child.name !== "string" || !isReferenceIdentifier(child, ancestors) || hasShadowingDeclaration(child.name, ancestors)) {
8047
8654
  return;
8048
8655
  }
8049
8656
  const declaration = state.moduleBindings.declarations.get(child.name);
8050
8657
  if (!declaration) {
8051
- if (trackImports && state.moduleBindings.imports.has(child.name)) {
8052
- state.hasUnresolvedImport = true;
8658
+ const imported = state.moduleBindings.imports.get(child.name);
8659
+ if (trackImports && imported) {
8660
+ state.imports.add(imported);
8053
8661
  }
8054
8662
  return;
8055
8663
  }
@@ -8070,13 +8678,20 @@ function collectDependencyIdentifier(child, ancestors, trackImports, state) {
8070
8678
  function collectDependencies(node, trackImports, state) {
8071
8679
  walkWithAncestors(node, [], (child, ancestors) => {
8072
8680
  collectDependencyIdentifier(child, ancestors, trackImports, state);
8681
+ if (trackImports && child.type === "ImportExpression") {
8682
+ const specifier = asAstNode(child.source)?.value;
8683
+ if (typeof specifier === "string") {
8684
+ state.dynamicImports.add(specifier);
8685
+ }
8686
+ }
8073
8687
  });
8074
8688
  }
8075
- function createHmrDataSignature(code, program, bindings) {
8689
+ function createHmrDataSignature(code, program, bindings, filename) {
8076
8690
  const serverStages = [];
8077
8691
  const dependencyState = {
8078
8692
  dependencies: new Map,
8079
- hasUnresolvedImport: false,
8693
+ dynamicImports: new Set,
8694
+ imports: new Set,
8080
8695
  importTrackedDependencies: new Set,
8081
8696
  moduleBindings: collectModuleBindings(program)
8082
8697
  };
@@ -8110,6 +8725,10 @@ function createHmrDataSignature(code, program, bindings) {
8110
8725
  });
8111
8726
  const dataSource = [
8112
8727
  ...serverStages,
8728
+ ...[...dependencyState.imports].map((imported) => ({
8729
+ source: code.slice(imported.start, imported.end),
8730
+ start: imported.start
8731
+ })),
8113
8732
  ...[...dependencyState.dependencies.values()].map((dependency) => ({
8114
8733
  source: code.slice(dependency.start, dependency.end),
8115
8734
  start: dependency.start
@@ -8117,7 +8736,14 @@ function createHmrDataSignature(code, program, bindings) {
8117
8736
  ].sort((left, right) => left.start - right.start).map((entry) => entry.source).join(`
8118
8737
  `);
8119
8738
  const hash = new Bun.CryptoHasher("sha256").update(dataSource).digest("hex");
8120
- return dependencyState.hasUnresolvedImport ? `external:${hash}` : hash;
8739
+ if (dependencyState.imports.size === 0 && dependencyState.dynamicImports.size === 0) {
8740
+ return hash;
8741
+ }
8742
+ const dependencies = hmrDependencySignature(new Set([
8743
+ ...[...dependencyState.imports].map((imported) => imported.source.value),
8744
+ ...dependencyState.dynamicImports
8745
+ ]), filename);
8746
+ return dependencies === undefined ? `external:${hash}` : `imports:${hash}:${dependencies}`;
8121
8747
  }
8122
8748
  function calledHookName(call) {
8123
8749
  const callee = asAstNode(call.callee);
@@ -8335,9 +8961,14 @@ function transformForClient(code, filename) {
8335
8961
  }
8336
8962
  let source = new MagicString(clientSource);
8337
8963
  const routeBindings = collectDefineRouteBindings(program);
8338
- const removedRouteCode = removeChainedServerCalls(source, program, routeBindings);
8964
+ assertCompleteRouteChains(program, routeBindings, filename);
8965
+ const configBindings = new Set;
8966
+ const removedRouteCode = removeChainedServerCalls(source, program, routeBindings, configBindings, filename);
8339
8967
  const removedServerCode = isomorphicResult.transformed || removedRouteCode;
8340
8968
  if (removedServerCode) {
8969
+ if (configBindings.size > 0) {
8970
+ source = pruneUnusedConfigBindings(source, filename, configBindings);
8971
+ }
8341
8972
  source = deadCodeElimination(source, code, lang);
8342
8973
  }
8343
8974
  const transformedCode = source.toString();
@@ -8356,11 +8987,16 @@ function transformForClient(code, filename) {
8356
8987
  if (originalError) {
8357
8988
  throw new Error(`Failed to parse ${filename}: ${originalError.message}`);
8358
8989
  }
8359
- const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program));
8990
+ const hmrDataSignature = createHmrDataSignature(code, originalParse.program, collectDefineRouteBindings(originalParse.program), filename);
8360
8991
  const signatureValue = Array.isArray(hookSignature) ? JSON.stringify(hookSignature) : 'route.component[Symbol.for("furin.hmr.hook-signature")] ?? [String(route.component)]';
8361
8992
  source.append(`
8362
8993
  if (import.meta.hot && route?.component) {
8363
8994
  const previousDataSignature = ${JSON.stringify(hmrDataSignature)};
8995
+ const previousSourceSignature = ${JSON.stringify(Bun.hash(code).toString(16))};
8996
+ Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)}), {
8997
+ configurable: true,
8998
+ value: previousSourceSignature,
8999
+ });
8364
9000
  Object.defineProperty(route, Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)}), {
8365
9001
  configurable: true,
8366
9002
  value: previousDataSignature,
@@ -8376,10 +9012,14 @@ if (import.meta.hot && route?.component) {
8376
9012
  updatedRoute,
8377
9013
  Symbol.for(${JSON.stringify(HMR_DATA_SIGNATURE)})
8378
9014
  );
9015
+ // An unchanged source can be re-evaluated by Bun after an import edit
9016
+ // without rerunning this transform. Its embedded dependency hash is stale.
8379
9017
  const dataChanged =
8380
9018
  previousDataSignature.startsWith("external:") ||
8381
9019
  typeof updatedDataSignature !== "string" ||
8382
9020
  updatedDataSignature.startsWith("external:") ||
9021
+ (updatedDataSignature.startsWith("imports:") &&
9022
+ Reflect.get(updatedRoute, Symbol.for(${JSON.stringify(HMR_SOURCE_SIGNATURE)})) === previousSourceSignature) ||
8383
9023
  updatedDataSignature !== previousDataSignature;
8384
9024
  window.__FURIN_HMR_UPDATE__?.(${JSON.stringify(filename)}, updatedRoute.component, dataChanged);
8385
9025
  }
@@ -8448,6 +9088,7 @@ ${buildIdMeta}${modeMeta}${faviconLink}${cssLinks ? `${cssLinks}
8448
9088
  // src/build/hydrate.ts
8449
9089
  init_patterns();
8450
9090
  function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
9091
+ const rootDirectory = rootLayout.replaceAll("\\", "/").split("/").slice(0, -1).join("/");
8451
9092
  const getBoundaryIdent = (idents, filePath) => {
8452
9093
  if (!filePath) {
8453
9094
  return;
@@ -8488,6 +9129,9 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
8488
9129
  if (notFoundIdent) {
8489
9130
  parts.push(`notFound: ${notFoundIdent}.default`);
8490
9131
  }
9132
+ if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
9133
+ parts.push("isRoot: false");
9134
+ }
8491
9135
  boundaryLiterals.push(`{ ${parts.join(", ")} }`);
8492
9136
  }
8493
9137
  const lazyImports = [
@@ -8503,7 +9147,7 @@ function generateHydrateEntry(routes, rootLayout, basePath, clientLogging) {
8503
9147
  }).join(" ");
8504
9148
  const boundaryResult = boundaryLiterals.length > 0 ? `, segmentBoundaries: [${boundaryLiterals.join(", ")}]` : "";
8505
9149
  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} }; })`;
9150
+ 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
9151
  const searchDefaultsEntry = searchDefaults ? `, searchDefaults: ${JSON.stringify(searchDefaults)}` : "";
8508
9152
  routeEntries.push(` { pattern: "${route.pattern}", regex: new RegExp(${JSON.stringify(regexPattern)}), load: () => ${loadBody}${searchDefaultsEntry} }`);
8509
9153
  }
@@ -8737,6 +9381,12 @@ if (__deferred && __deferred._chunks) {
8737
9381
  initialNotFound: loaderData.__furinNotFound ?? {},${routerProviderDefaults}
8738
9382
  } as any);
8739
9383
  } else {
9384
+ // A removed active route has no match in the new development manifest.
9385
+ // Reload its document so the server can render the current 404 response.
9386
+ if (import.meta.hot && (window as unknown as { __FURIN_ROOT__?: unknown }).__FURIN_ROOT__) {
9387
+ window.location.reload();
9388
+ return;
9389
+ }
8740
9390
  // No match and no 404 signal \u2014 either the client bundle is out of sync
8741
9391
  // with the server (stale deploy) or the server returned something we
8742
9392
  // don't know how to hydrate. Bail loudly; the page stays static.
@@ -8814,9 +9464,65 @@ if (__deferred && __deferred._chunks) {
8814
9464
  `;
8815
9465
  }
8816
9466
 
9467
+ // src/build/preload-manifest.ts
9468
+ init_transform_client_module();
9469
+ import { existsSync as existsSync6, readFileSync as readFileSync4, realpathSync as realpathSync3, writeFileSync as writeFileSync2 } from "fs";
9470
+ import { basename as basename2, resolve as resolve6 } from "path";
9471
+ var CLIENT_MODULE_KEY_RE = /(["'`])(__FURIN_CLIENT_MODULE_[a-z0-9]+__)\1/g;
9472
+ function routeModulePaths(route) {
9473
+ const layouts = (route.routeChain ?? []).slice(1).filter((entry) => entry.layout && entry.sourcePath).map((entry) => entry.sourcePath);
9474
+ const boundaries = (route.segmentBoundaries ?? []).flatMap((segment) => [segment.errorPath, segment.notFoundPath].filter((path) => path !== undefined));
9475
+ return [route.path, ...layouts, ...boundaries];
9476
+ }
9477
+ function realPath(path) {
9478
+ return existsSync6(path) ? realpathSync3(path) : null;
9479
+ }
9480
+ function writeClientPreloadManifest(metafile, outputPaths, entryChunkPath, routes, publicPrefix) {
9481
+ const outputs = new Map(Object.entries(metafile.outputs).map(([path, output]) => [basename2(path), output]));
9482
+ const closure = (file, seen) => {
9483
+ if (!seen.has(file)) {
9484
+ seen.add(file);
9485
+ for (const imported of outputs.get(file)?.imports ?? []) {
9486
+ if (imported.kind === "import-statement") {
9487
+ closure(basename2(imported.path), seen);
9488
+ }
9489
+ }
9490
+ }
9491
+ return seen;
9492
+ };
9493
+ const entryFiles = closure(basename2(entryChunkPath), new Set);
9494
+ const hrefsOf = (file) => [...closure(file, new Set)].filter((chunk) => !entryFiles.has(chunk)).map((chunk) => `${publicPrefix}${chunk}`);
9495
+ const chunkByModule = new Map;
9496
+ for (const [file, output] of outputs) {
9497
+ const modulePath = output.entryPoint ? realPath(resolve6(output.entryPoint)) : null;
9498
+ if (modulePath !== null) {
9499
+ chunkByModule.set(modulePath, file);
9500
+ }
9501
+ }
9502
+ const routeManifest = {};
9503
+ for (const route of routes) {
9504
+ const files = routeModulePaths(route).map((path) => chunkByModule.get(realPath(path) ?? path)).filter((file) => file !== undefined);
9505
+ routeManifest[route.pattern] = [...new Set(files.flatMap(hrefsOf))];
9506
+ }
9507
+ const moduleHrefs = new Map([...chunkByModule].map(([modulePath, file]) => [clientModuleKey(modulePath), file]));
9508
+ const modules = {};
9509
+ for (const path of outputPaths.filter((output) => output.endsWith(".js"))) {
9510
+ const code = readFileSync4(path, "utf8");
9511
+ const rewritten = code.replace(CLIENT_MODULE_KEY_RE, (_match, _quote, key) => {
9512
+ const file = moduleHrefs.get(key);
9513
+ modules[key] = file === undefined ? [] : hrefsOf(file);
9514
+ return JSON.stringify(modules[key]);
9515
+ });
9516
+ if (rewritten !== code) {
9517
+ writeFileSync2(path, rewritten);
9518
+ }
9519
+ }
9520
+ return { modules, routes: routeManifest };
9521
+ }
9522
+
8817
9523
  // src/build/client.ts
8818
9524
  var SCRIPT_FILE_FILTER2 = /\.(tsx?|jsx?)$/;
8819
- var ROUTER_PROVIDER_PATH = resolve5(import.meta.dir, "../client/router/provider.tsx");
9525
+ var ROUTER_PROVIDER_PATH = resolve7(import.meta.dir, "../client/router/provider.tsx");
8820
9526
  function resolveClientModuleSpecifiers(code) {
8821
9527
  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
9528
  }
@@ -8824,6 +9530,7 @@ async function buildClient(routes, {
8824
9530
  outDir,
8825
9531
  rootLayout,
8826
9532
  plugins,
9533
+ preloadRouteChunks,
8827
9534
  publicPath,
8828
9535
  basePath,
8829
9536
  clientLogging,
@@ -8834,15 +9541,15 @@ async function buildClient(routes, {
8834
9541
  pagesDir
8835
9542
  }) {
8836
9543
  const dirName = clientDirName ?? "client";
8837
- const clientDir = join7(outDir, dirName);
8838
- if (!existsSync6(outDir)) {
9544
+ const clientDir = join8(outDir, dirName);
9545
+ if (!existsSync7(outDir)) {
8839
9546
  mkdirSync2(outDir, { recursive: true });
8840
9547
  }
8841
- if (!existsSync6(clientDir)) {
9548
+ if (!existsSync7(clientDir)) {
8842
9549
  mkdirSync2(clientDir, { recursive: true });
8843
9550
  }
8844
9551
  const hydrateCode = resolveClientModuleSpecifiers(generateHydrateEntry(routes, rootLayout, basePath, clientLogging));
8845
- const hydratePath = join7(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
9552
+ const hydratePath = join8(outDir, dirName === "client" ? "_hydrate.tsx" : `_hydrate-${dirName}.tsx`);
8846
9553
  const hydrateEntry = createVirtualBuildEntry(hydratePath, hydrateCode, "tsx");
8847
9554
  console.log("[furin] Building production client bundle\u2026");
8848
9555
  const transformPlugin = {
@@ -8882,6 +9589,7 @@ async function buildClient(routes, {
8882
9589
  files: hydrateEntry.files,
8883
9590
  outdir: clientDir,
8884
9591
  target: "browser",
9592
+ env: "FURIN_PUBLIC_*",
8885
9593
  format: "esm",
8886
9594
  splitting: true,
8887
9595
  optimizeImports,
@@ -8889,7 +9597,7 @@ async function buildClient(routes, {
8889
9597
  reactCompilerOutputMode: "client",
8890
9598
  minify: true,
8891
9599
  sourcemap: "none",
8892
- metafile: metafilePath !== undefined,
9600
+ metafile: true,
8893
9601
  naming: {
8894
9602
  entry: "[name]-[hash].[ext]",
8895
9603
  chunk: "[name]-[hash].[ext]"
@@ -8909,16 +9617,17 @@ async function buildClient(routes, {
8909
9617
  "@teyik0/furin/search": SEARCH_MODULE_PATH
8910
9618
  },
8911
9619
  define: {
9620
+ ...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
9621
  "process.env.NODE_ENV": JSON.stringify("production")
8913
9622
  }
8914
9623
  };
8915
9624
  const result = await runBunBuild(clientBuildConfig);
9625
+ if (result.metafile === undefined) {
9626
+ throw new Error("[furin] client build did not produce the requested metafile");
9627
+ }
8916
9628
  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)}
9629
+ mkdirSync2(dirname9(metafilePath), { recursive: true });
9630
+ writeFileSync3(metafilePath, `${JSON.stringify(result.metafile, null, 2)}
8922
9631
  `);
8923
9632
  console.log(`[furin] Client metafile: ${metafilePath}`);
8924
9633
  }
@@ -8936,10 +9645,11 @@ async function buildClient(routes, {
8936
9645
  } else {
8937
9646
  publicPrefix = publicPath.endsWith("/") ? publicPath : `${publicPath}/`;
8938
9647
  }
8939
- const entryChunk = `${publicPrefix}${basename2(entryOutput.path)}`;
8940
- const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename2(o.path)}`);
9648
+ const entryChunk = `${publicPrefix}${basename3(entryOutput.path)}`;
9649
+ const cssChunks = cssOutputs.map((o) => `${publicPrefix}${basename3(o.path)}`);
9650
+ const preloadManifest = writeClientPreloadManifest(result.metafile, result.outputs.map((output) => output.path), entryOutput.path, preloadRouteChunks === false ? [] : routes, publicPrefix);
8941
9651
  console.log("[furin] Production client build complete");
8942
- return { entryChunk, cssChunks };
9652
+ return { entryChunk, cssChunks, preloadManifest };
8943
9653
  }
8944
9654
 
8945
9655
  // src/server/render/assemble.ts
@@ -8968,6 +9678,65 @@ async function streamToString(stream) {
8968
9678
  html += decoder.decode();
8969
9679
  return html;
8970
9680
  }
9681
+ // src/shared/sync-query.ts
9682
+ function mergeQuerySeeds(target, incoming) {
9683
+ for (const seed of incoming) {
9684
+ const index = target.findIndex((existing) => existing.url === seed.url);
9685
+ const previous = target[index];
9686
+ const bindings = [...seed.bindings ?? []];
9687
+ if (previous?.identity.session === seed.identity.session && queryTag(previous.identity) === queryTag(seed.identity)) {
9688
+ for (const binding of previous.bindings ?? []) {
9689
+ if (!bindings.some((next) => JSON.stringify(next.target) === JSON.stringify(binding.target))) {
9690
+ bindings.push(binding);
9691
+ }
9692
+ }
9693
+ }
9694
+ const merged = { ...seed, bindings };
9695
+ if (index < 0) {
9696
+ target.push(merged);
9697
+ } else {
9698
+ target[index] = merged;
9699
+ }
9700
+ }
9701
+ }
9702
+ function queryTagsFromData(data) {
9703
+ return (data.__furinQueries ?? []).map((seed) => queryTag(seed.identity));
9704
+ }
9705
+ var PREFIX = "__furin.query:";
9706
+ function queryTag(identity) {
9707
+ for (const [key, value] of Object.entries(identity.scope)) {
9708
+ if (value === undefined) {
9709
+ throw new Error(`[furin] Query scope "${key}" is undefined for "${identity.id}".`);
9710
+ }
9711
+ }
9712
+ return PREFIX + JSON.stringify([
9713
+ identity.id,
9714
+ Object.entries(identity.scope).sort(([a], [b]) => {
9715
+ if (a === b) {
9716
+ return 0;
9717
+ }
9718
+ return a < b ? -1 : 1;
9719
+ })
9720
+ ]);
9721
+ }
9722
+ function queryFromTag(tag) {
9723
+ if (!tag.startsWith(PREFIX)) {
9724
+ return;
9725
+ }
9726
+ try {
9727
+ const value = JSON.parse(tag.slice(PREFIX.length));
9728
+ 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"))) {
9729
+ return;
9730
+ }
9731
+ return { id: value[0], scope: Object.fromEntries(value[1]) };
9732
+ } catch {}
9733
+ }
9734
+ function queryUrl(url, origin) {
9735
+ const parsed = new URL(url, origin);
9736
+ parsed.searchParams.sort();
9737
+ return (parsed.origin === origin ? "" : parsed.origin) + parsed.pathname + parsed.search;
9738
+ }
9739
+
8971
9740
  // src/shared/utils/index.ts
8972
9741
  function collectRouteChainFromRoute(route) {
8973
9742
  const chain = [];
@@ -9090,8 +9859,7 @@ function setSSGCache(key, entry) {
9090
9859
  }
9091
9860
 
9092
9861
  // src/server/render/ssr.ts
9093
- import { createElement as createElement6 } from "react";
9094
- import { renderToReadableStream } from "react-dom/server";
9862
+ import { createElement as createElement7 } from "react";
9095
9863
 
9096
9864
  // ../../node_modules/.bun/seroval@1.6.7/node_modules/seroval/dist/dev/index.js
9097
9865
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
@@ -11196,6 +11964,7 @@ function fromCrossJSON(source, options) {
11196
11964
 
11197
11965
  // src/client/document.tsx
11198
11966
  import { createContext, createElement, useContext } from "react";
11967
+ import { preloadModule } from "react-dom";
11199
11968
  import { jsxDEV, Fragment } from "react/jsx-dev-runtime";
11200
11969
  var DocumentContext = createContext(null);
11201
11970
  function serializeJson(value) {
@@ -11210,29 +11979,39 @@ function DocumentProvider({
11210
11979
  children
11211
11980
  }, undefined, false, undefined, this);
11212
11981
  }
11213
- function renderMeta(meta, index) {
11982
+ function renderMeta(meta, key) {
11214
11983
  if ("title" in meta) {
11215
11984
  return /* @__PURE__ */ jsxDEV("title", {
11216
11985
  children: meta.title
11217
- }, `title:${index}`, false, undefined, this);
11986
+ }, key, false, undefined, this);
11218
11987
  }
11219
11988
  if ("script:ld+json" in meta) {
11220
11989
  return /* @__PURE__ */ jsxDEV("script", {
11221
11990
  dangerouslySetInnerHTML: { __html: serializeJson(meta["script:ld+json"]) },
11222
11991
  type: "application/ld+json"
11223
- }, `json-ld:${index}`, false, undefined, this);
11992
+ }, key, false, undefined, this);
11224
11993
  }
11225
11994
  if ("tagName" in meta) {
11226
11995
  const { tagName, ...attributes } = meta;
11227
- return createElement(tagName, { ...attributes, key: `${tagName}:${index}` });
11996
+ return createElement(tagName, { ...attributes, key });
11228
11997
  }
11229
- return createElement("meta", { ...meta, key: `meta:${index}` });
11998
+ return createElement("meta", { ...meta, key });
11230
11999
  }
11231
12000
  function HeadContent() {
11232
12001
  const state = useContext(DocumentContext);
11233
12002
  if (state === null) {
11234
12003
  throw new Error("[furin] <HeadContent /> must be rendered inside the root layout.");
11235
12004
  }
12005
+ for (const href of state.assets.modulePreloads ?? []) {
12006
+ preloadModule(href, { as: "script", nonce: state.nonce });
12007
+ }
12008
+ const occurrences = new Map;
12009
+ const descriptorKey = (descriptor) => {
12010
+ const identity = JSON.stringify(descriptor);
12011
+ const occurrence = occurrences.get(identity) ?? 0;
12012
+ occurrences.set(identity, occurrence + 1);
12013
+ return `${identity}:${occurrence}`;
12014
+ };
11236
12015
  return /* @__PURE__ */ jsxDEV(Fragment, {
11237
12016
  children: [
11238
12017
  state.assets.extensionErrorFilterScript === undefined ? null : /* @__PURE__ */ jsxDEV("script", {
@@ -11265,20 +12044,20 @@ function HeadContent() {
11265
12044
  href,
11266
12045
  rel: "stylesheet"
11267
12046
  }, href, false, undefined, this)),
11268
- state.head?.meta?.map(renderMeta),
11269
- state.head?.links?.map((link, index) => /* @__PURE__ */ jsxDEV("link", {
12047
+ state.head?.meta?.map((meta) => renderMeta(meta, descriptorKey(meta))),
12048
+ state.head?.links?.map((link) => /* @__PURE__ */ jsxDEV("link", {
11270
12049
  ...link
11271
- }, `${link.rel}:${link.href}:${index}`, false, undefined, this)),
11272
- state.head?.scripts?.map(({ children, ...attributes }, index) => /* @__PURE__ */ jsxDEV("script", {
12050
+ }, descriptorKey(link), false, undefined, this)),
12051
+ state.head?.scripts?.map(({ children, ...attributes }) => /* @__PURE__ */ jsxDEV("script", {
11273
12052
  ...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", {
12053
+ nonce: state.nonce ?? attributes.nonce,
12054
+ children
12055
+ }, descriptorKey({ children, ...attributes }), false, undefined, this)),
12056
+ state.head?.styles?.map(({ children, type }) => /* @__PURE__ */ jsxDEV("style", {
11278
12057
  dangerouslySetInnerHTML: { __html: children },
11279
12058
  nonce: state.nonce,
11280
12059
  type
11281
- }, `style:${index}`, false, undefined, this))
12060
+ }, descriptorKey({ children, type }), false, undefined, this))
11282
12061
  ]
11283
12062
  }, undefined, true, undefined, this);
11284
12063
  }
@@ -11347,7 +12126,7 @@ function FurinDocumentFallback({ children }) {
11347
12126
  }
11348
12127
 
11349
12128
  // src/client/router/context.ts
11350
- import { createContext as createContext2, useContext as useContext2 } from "react";
12129
+ import { createContext as createContext2, useCallback, useContext as useContext2, useMemo } from "react";
11351
12130
 
11352
12131
  // src/client/router/link-utils.ts
11353
12132
  function navigationHrefPolicy(href, currentOrigin) {
@@ -11437,7 +12216,7 @@ var CLIENT_FALLBACK_ROUTER = {
11437
12216
  search: {},
11438
12217
  searchRoutes: []
11439
12218
  };
11440
- function useRouter() {
12219
+ function useRouterContext() {
11441
12220
  const ctx = useContext2(RouterContext);
11442
12221
  return ctx ?? CLIENT_FALLBACK_ROUTER;
11443
12222
  }
@@ -11445,7 +12224,7 @@ function useRouter() {
11445
12224
  // src/client/router/search-store.ts
11446
12225
  import { createContext as createContext3 } from "react";
11447
12226
  function searchSnapshotChanged(a, b) {
11448
- return a.currentHref !== b.currentHref || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
12227
+ return a.currentHref !== b.currentHref || a.currentPattern !== b.currentPattern || a.navigate !== b.navigate || a.search !== b.search || a.searchRoutes !== b.searchRoutes;
11449
12228
  }
11450
12229
  function createSearchStore(initialSnapshot) {
11451
12230
  let snapshot = initialSnapshot;
@@ -11482,6 +12261,7 @@ function createSearchStore(initialSnapshot) {
11482
12261
  function searchSnapshotFromRouterContext(context) {
11483
12262
  return {
11484
12263
  currentHref: context.currentHref,
12264
+ currentPattern: context.currentPattern,
11485
12265
  navigate: context.navigate,
11486
12266
  search: context.search,
11487
12267
  searchRoutes: context.searchRoutes
@@ -11489,6 +12269,7 @@ function searchSnapshotFromRouterContext(context) {
11489
12269
  }
11490
12270
  var FALLBACK_SEARCH_STORE = createSearchStore({
11491
12271
  currentHref: "/",
12272
+ currentPattern: undefined,
11492
12273
  navigate: (href, _opts) => {
11493
12274
  if (typeof window !== "undefined") {
11494
12275
  if (navigationHrefPolicy(href, window.location.origin) === "blocked") {
@@ -11766,9 +12547,292 @@ function serializeRouteFrames(data, deferredKeys) {
11766
12547
  // src/server/render/ssr.ts
11767
12548
  init_context_logger();
11768
12549
  init_instance();
11769
-
11770
12550
  // src/server/render/document.tsx
11771
12551
  import { createElement as createElement3 } from "react";
12552
+
12553
+ // src/client/query.tsx
12554
+ import {
12555
+ createContext as createContext4,
12556
+ useCallback as useCallback2,
12557
+ useContext as useContext3,
12558
+ useEffect,
12559
+ useSyncExternalStore
12560
+ } from "react";
12561
+
12562
+ // src/client/query-store.ts
12563
+ var QUERY_REFERENCE = Symbol.for("furin.query.reference.v1");
12564
+ var SERVER_ENVIRONMENT = Symbol.for("furin.query.environment.v1");
12565
+ var environmentGlobal = globalThis;
12566
+ function setServerQueryEnvironment(read) {
12567
+ environmentGlobal[SERVER_ENVIRONMENT] = read;
12568
+ }
12569
+ function currentQueryEnvironment() {
12570
+ return environmentGlobal[SERVER_ENVIRONMENT]?.();
12571
+ }
12572
+ class QueryStore {
12573
+ entries = new Map;
12574
+ listeners = new Set;
12575
+ revisionValue = 0;
12576
+ projections = new Set;
12577
+ session;
12578
+ epoch = 0;
12579
+ origin;
12580
+ constructor(origin) {
12581
+ this.origin = origin;
12582
+ }
12583
+ key(url) {
12584
+ const absolute = new URL(url, this.origin).href;
12585
+ return queryUrl(absolute, undefined);
12586
+ }
12587
+ entry(url) {
12588
+ const key = this.key(url);
12589
+ let entry = this.entries.get(key);
12590
+ if (!entry) {
12591
+ entry = {
12592
+ base: undefined,
12593
+ listeners: new Set,
12594
+ snapshot: { data: undefined, error: null, isFetching: false },
12595
+ stale: true,
12596
+ version: 0
12597
+ };
12598
+ this.entries.set(key, entry);
12599
+ }
12600
+ return entry;
12601
+ }
12602
+ publish(entry) {
12603
+ let data = entry.base;
12604
+ for (const projection of this.projections) {
12605
+ const transform = projection.transforms.get(entry);
12606
+ if (transform && data !== undefined) {
12607
+ data = transform(data);
12608
+ }
12609
+ }
12610
+ entry.snapshot = { ...entry.snapshot, data };
12611
+ for (const listener of entry.listeners) {
12612
+ listener();
12613
+ }
12614
+ this.revisionValue += 1;
12615
+ for (const listener of this.listeners) {
12616
+ listener();
12617
+ }
12618
+ }
12619
+ revision = () => this.revisionValue;
12620
+ subscribeAll = (listener) => {
12621
+ this.listeners.add(listener);
12622
+ return () => this.listeners.delete(listener);
12623
+ };
12624
+ observe(url, result, epoch, version) {
12625
+ const existing = this.entries.get(this.key(url));
12626
+ if (epoch !== this.epoch || result.error !== null || existing && (this.pending(existing) || version !== undefined && existing.version !== version)) {
12627
+ return;
12628
+ }
12629
+ const header = result.response?.headers.get("x-furin-query");
12630
+ const identity = result.identity ?? (header ? JSON.parse(header) : undefined);
12631
+ if (identity) {
12632
+ this.setSession(identity.session);
12633
+ }
12634
+ const entry = this.entry(url);
12635
+ entry.base = result.data;
12636
+ entry.version += 1;
12637
+ entry.identity = identity;
12638
+ entry.local = result.local ?? result.response?.url === "";
12639
+ entry.stale = false;
12640
+ entry.snapshot = { data: result.data, error: null, isFetching: false };
12641
+ for (const projection of this.projections) {
12642
+ if (!projection.pending) {
12643
+ projection.transforms.delete(entry);
12644
+ if (projection.transforms.size === 0) {
12645
+ this.projections.delete(projection);
12646
+ projection.onRemove?.();
12647
+ }
12648
+ }
12649
+ }
12650
+ this.publish(entry);
12651
+ if (this.entries.size > 100) {
12652
+ const oldest = [...this.entries].find(([, item]) => item !== entry && item.listeners.size === 0 && !item.promise && !this.pending(item));
12653
+ if (oldest) {
12654
+ this.entries.delete(oldest[0]);
12655
+ }
12656
+ }
12657
+ }
12658
+ setSession(session) {
12659
+ if (this.session !== undefined && this.session !== session) {
12660
+ this.epoch += 1;
12661
+ for (const projection of this.projections) {
12662
+ projection.onRemove?.();
12663
+ }
12664
+ this.projections.clear();
12665
+ for (const entry of this.entries.values()) {
12666
+ entry.base = undefined;
12667
+ entry.identity = undefined;
12668
+ entry.stale = true;
12669
+ entry.version += 1;
12670
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12671
+ this.publish(entry);
12672
+ }
12673
+ }
12674
+ this.session = session;
12675
+ }
12676
+ generation() {
12677
+ return this.epoch;
12678
+ }
12679
+ version(url) {
12680
+ return this.entry(url).version;
12681
+ }
12682
+ snapshot(url) {
12683
+ return this.entry(url).snapshot;
12684
+ }
12685
+ subscribe(url, listener) {
12686
+ const entry = this.entry(url);
12687
+ entry.listeners.add(listener);
12688
+ return () => entry.listeners.delete(listener);
12689
+ }
12690
+ bind(url, load, client) {
12691
+ const entry = this.entry(url);
12692
+ if (client && entry.client && client !== entry.client) {
12693
+ entry.base = undefined;
12694
+ entry.identity = undefined;
12695
+ entry.stale = true;
12696
+ entry.version += 1;
12697
+ entry.snapshot = { data: undefined, error: null, isFetching: false };
12698
+ for (const projection of this.projections) {
12699
+ projection.transforms.delete(entry);
12700
+ }
12701
+ }
12702
+ entry.client = client ?? entry.client;
12703
+ entry.load = load;
12704
+ }
12705
+ pending(entry) {
12706
+ return [...this.projections].some((projection) => projection.pending && projection.transforms.has(entry));
12707
+ }
12708
+ fetch(url) {
12709
+ const entry = this.entry(url);
12710
+ if (entry.promise) {
12711
+ return entry.promise;
12712
+ }
12713
+ if (!(entry.stale && entry.load) || this.pending(entry)) {
12714
+ return Promise.resolve();
12715
+ }
12716
+ const { version } = entry;
12717
+ const { epoch } = this;
12718
+ entry.snapshot = { ...entry.snapshot, isFetching: true };
12719
+ this.publish(entry);
12720
+ entry.promise = Promise.resolve().then(() => entry.load?.()).then((result) => {
12721
+ if (!result || epoch !== this.epoch || version !== entry.version || this.pending(entry)) {
12722
+ return;
12723
+ }
12724
+ if (result.error === null) {
12725
+ this.observe(url, result, epoch);
12726
+ } else {
12727
+ entry.snapshot = { ...entry.snapshot, error: result.error };
12728
+ }
12729
+ }).catch((error) => {
12730
+ if (epoch === this.epoch && version === entry.version) {
12731
+ entry.snapshot = { ...entry.snapshot, error };
12732
+ }
12733
+ }).finally(() => {
12734
+ entry.promise = undefined;
12735
+ entry.snapshot = { ...entry.snapshot, isFetching: false };
12736
+ this.publish(entry);
12737
+ if (entry.stale && version !== entry.version && entry.listeners.size > 0) {
12738
+ this.fetch(url);
12739
+ }
12740
+ });
12741
+ return entry.promise;
12742
+ }
12743
+ invalidate(identities) {
12744
+ const tags = new Set(identities.map(queryTag));
12745
+ let affected = false;
12746
+ for (const [url, entry] of this.entries) {
12747
+ if (entry.identity && tags.has(queryTag(entry.identity))) {
12748
+ affected = true;
12749
+ this.invalidateEntry(url, entry);
12750
+ }
12751
+ }
12752
+ return affected;
12753
+ }
12754
+ invalidateEntry(url, entry) {
12755
+ entry.stale = true;
12756
+ entry.version += 1;
12757
+ if (entry.listeners.size > 0) {
12758
+ this.fetch(url);
12759
+ }
12760
+ }
12761
+ invalidateAll() {
12762
+ for (const [url, entry] of this.entries) {
12763
+ this.invalidateEntry(url, entry);
12764
+ }
12765
+ }
12766
+ begin() {
12767
+ return { pending: true, transforms: new Map };
12768
+ }
12769
+ update(projection, url, transform) {
12770
+ const entry = this.entries.get(this.key(url));
12771
+ if (!entry || entry.base === undefined) {
12772
+ return;
12773
+ }
12774
+ const previous = projection.transforms.get(entry);
12775
+ projection.transforms.set(entry, previous ? (data) => transform(previous(data)) : transform);
12776
+ entry.version += 1;
12777
+ this.projections.add(projection);
12778
+ this.publish(entry);
12779
+ }
12780
+ finish(projection, outcome) {
12781
+ projection.pending = false;
12782
+ const entries = [...projection.transforms.keys()];
12783
+ if (outcome === "error") {
12784
+ this.projections.delete(projection);
12785
+ projection.onRemove?.();
12786
+ }
12787
+ for (const entry of entries) {
12788
+ this.publish(entry);
12789
+ if (outcome !== "error") {
12790
+ entry.stale = true;
12791
+ }
12792
+ const url = [...this.entries].find(([, candidate]) => candidate === entry)?.[0];
12793
+ if (url && entry.stale) {
12794
+ this.fetch(url);
12795
+ }
12796
+ }
12797
+ }
12798
+ dehydrate() {
12799
+ return [...this.entries].flatMap(([url, entry]) => entry.identity && entry.base !== undefined ? [{ url, data: entry.base, identity: entry.identity, local: entry.local }] : []);
12800
+ }
12801
+ seedUrl(seed, localOrigin) {
12802
+ const original = new URL(seed.url, this.origin);
12803
+ return seed.local && localOrigin ? new URL(original.pathname + original.search, localOrigin).href : original.href;
12804
+ }
12805
+ captureHydration() {
12806
+ const { epoch } = this;
12807
+ const versions = new Map([...this.entries].map(([key, entry]) => [key, entry.version]));
12808
+ return (seeds, localOrigin) => {
12809
+ if (epoch === this.epoch) {
12810
+ this.hydrate(seeds.filter((seed) => {
12811
+ const url = this.seedUrl(seed, localOrigin);
12812
+ return this.version(url) === (versions.get(this.key(url)) ?? 0);
12813
+ }), localOrigin);
12814
+ }
12815
+ };
12816
+ }
12817
+ hydrate(seeds, localOrigin) {
12818
+ for (const seed of seeds) {
12819
+ const url = this.seedUrl(seed, localOrigin);
12820
+ this.observe(url, {
12821
+ data: seed.data,
12822
+ error: null,
12823
+ identity: seed.identity,
12824
+ local: seed.local ?? false
12825
+ }, this.epoch);
12826
+ }
12827
+ }
12828
+ }
12829
+
12830
+ // src/client/query.tsx
12831
+ var QUERY_CONTEXT = Symbol.for("furin.query.context.v1");
12832
+ var contextGlobal = globalThis;
12833
+ var QueryStoreContext = contextGlobal[QUERY_CONTEXT] ??= createContext4(null);
12834
+
12835
+ // src/server/render/document.tsx
11772
12836
  init_instance();
11773
12837
  init_config();
11774
12838
  function withDocumentState(element, assets, head, data, nonce) {
@@ -11787,11 +12851,13 @@ function withDocumentState(element, assets, head, data, nonce) {
11787
12851
  routeFrames,
11788
12852
  syncJson: syncPath === undefined ? undefined : safeJson({ path: syncPath })
11789
12853
  };
11790
- return createElement3(DocumentProvider, { value: state }, element);
12854
+ const queries = new QueryStore(undefined);
12855
+ queries.hydrate(data?.__furinQueries ?? []);
12856
+ return createElement3(DocumentProvider, { value: state }, createElement3(QueryStoreContext.Provider, { value: queries }, element));
11791
12857
  }
11792
12858
 
11793
12859
  // src/server/render/element.tsx
11794
- import { createElement as createElement5 } from "react";
12860
+ import { createElement as createElement6 } from "react";
11795
12861
 
11796
12862
  // src/client/boundaries.tsx
11797
12863
  import { Component, Fragment as Fragment2 } from "react";
@@ -11821,7 +12887,57 @@ function isNotFoundError(err) {
11821
12887
  }
11822
12888
 
11823
12889
  // src/client/link.tsx
11824
- import { createElement as createElement4, useCallback, useEffect, useRef } from "react";
12890
+ import { createElement as createElement5, useCallback as useCallback3, useEffect as useEffect2, useRef } from "react";
12891
+
12892
+ // src/shared/page-key.ts
12893
+ function identityValue(value) {
12894
+ return Object.is(value, -0) ? "-0" : String(value);
12895
+ }
12896
+ function pageKey(pattern, data, remountDeps) {
12897
+ const { params, query } = data;
12898
+ if (remountDeps) {
12899
+ const deps = remountDeps({ params: params ?? {}, query: query ?? {} });
12900
+ return JSON.stringify([pattern, deps.map((value) => [typeof value, identityValue(value)])]);
12901
+ }
12902
+ const entries = Object.entries(params ?? {}).sort(([left], [right]) => {
12903
+ if (left < right) {
12904
+ return -1;
12905
+ }
12906
+ return left > right ? 1 : 0;
12907
+ });
12908
+ return JSON.stringify([
12909
+ pattern,
12910
+ entries.map(([name, value]) => [
12911
+ name,
12912
+ Array.isArray(value) ? value.map(identityValue) : identityValue(value)
12913
+ ])
12914
+ ]);
12915
+ }
12916
+
12917
+ // src/client/route-api.tsx
12918
+ import { createContext as createContext5, createElement as createElement4, useContext as useContext4 } from "react";
12919
+ var RESERVED_RENDER_KEYS = new Set([
12920
+ "catch",
12921
+ "children",
12922
+ "finally",
12923
+ "key",
12924
+ "ref",
12925
+ "then",
12926
+ "toJSON"
12927
+ ]);
12928
+ var ROUTE_CONTEXT = Symbol.for("furin.route.context.v1");
12929
+ var contextGlobal2 = globalThis;
12930
+ var RouteContext = contextGlobal2[ROUTE_CONTEXT] ??= createContext5(null);
12931
+ function withRouteSnapshot(element, pattern, props) {
12932
+ const {
12933
+ params,
12934
+ path: _path,
12935
+ query: _query,
12936
+ ...data
12937
+ } = props;
12938
+ const loaderData = Object.fromEntries(Object.entries(data).filter(([key]) => !(RESERVED_RENDER_KEYS.has(key) || key.startsWith("__furin"))));
12939
+ return createElement4(RouteContext.Provider, { value: { data: loaderData, params: params ?? {}, pattern } }, element);
12940
+ }
11825
12941
 
11826
12942
  // src/client/server-error.ts
11827
12943
  var SERVER_ERROR_BRAND = "FURIN_SERVER_ERROR";
@@ -11839,6 +12955,96 @@ class FurinServerError extends Error {
11839
12955
  function isFurinServerError(err) {
11840
12956
  return err instanceof FurinServerError || typeof err === "object" && err !== null && err.__furinBrand === SERVER_ERROR_BRAND;
11841
12957
  }
12958
+
12959
+ // src/shared/query-bindings.ts
12960
+ function isContainer(value) {
12961
+ if (!value || typeof value !== "object") {
12962
+ return false;
12963
+ }
12964
+ const prototype = Object.getPrototypeOf(value);
12965
+ return Array.isArray(value) || prototype === Object.prototype || prototype === null;
12966
+ }
12967
+ function bindQueryData(data, seeds) {
12968
+ return seeds.map((seed) => {
12969
+ const sources = new WeakMap;
12970
+ const index = (value, path) => {
12971
+ if (!isContainer(value) || sources.has(value)) {
12972
+ return;
12973
+ }
12974
+ sources.set(value, path);
12975
+ if (!Array.isArray(value)) {
12976
+ for (const [key, child] of Object.entries(value)) {
12977
+ index(child, [...path, key]);
12978
+ }
12979
+ }
12980
+ };
12981
+ index(seed.data, []);
12982
+ const bindings = [];
12983
+ const visiting = new WeakSet;
12984
+ const visit = (value, target) => {
12985
+ if (!isContainer(value) || visiting.has(value)) {
12986
+ return;
12987
+ }
12988
+ const source = sources.get(value);
12989
+ if (source) {
12990
+ bindings.push({ source, target });
12991
+ return;
12992
+ }
12993
+ visiting.add(value);
12994
+ for (const [key, child] of Object.entries(value)) {
12995
+ visit(child, [...target, key]);
12996
+ }
12997
+ visiting.delete(value);
12998
+ };
12999
+ visit(data, []);
13000
+ return { ...seed, bindings };
13001
+ });
13002
+ }
13003
+ function replace(value, path, next) {
13004
+ const [key, ...rest] = path;
13005
+ if (key === undefined) {
13006
+ return next;
13007
+ }
13008
+ if (!(isContainer(value) && Object.hasOwn(value, key))) {
13009
+ return value;
13010
+ }
13011
+ const child = replace(value[key], rest, next);
13012
+ if (child === value[key]) {
13013
+ return value;
13014
+ }
13015
+ const copy = Array.isArray(value) ? [...value] : { ...value };
13016
+ Object.defineProperty(copy, key, {
13017
+ configurable: true,
13018
+ enumerable: true,
13019
+ value: child,
13020
+ writable: true
13021
+ });
13022
+ return copy;
13023
+ }
13024
+ function isDeferredTarget(data, target) {
13025
+ const [key] = target;
13026
+ return key !== undefined && isContainer(data) && data[key] instanceof Promise;
13027
+ }
13028
+ function projectQueryData(data, seeds, read) {
13029
+ let projected = data;
13030
+ for (const seed of seeds) {
13031
+ const snapshot = read(seed);
13032
+ if (snapshot === undefined) {
13033
+ continue;
13034
+ }
13035
+ for (const binding of seed.bindings ?? []) {
13036
+ if (isDeferredTarget(data, binding.target)) {
13037
+ continue;
13038
+ }
13039
+ let value = snapshot;
13040
+ for (const key of binding.source) {
13041
+ value = isContainer(value) && Object.hasOwn(value, key) ? value[key] : undefined;
13042
+ }
13043
+ projected = replace(projected, binding.target, value);
13044
+ }
13045
+ }
13046
+ return projected;
13047
+ }
11842
13048
  // src/client/link.tsx
11843
13049
  function computeLinkView({
11844
13050
  to,
@@ -11888,7 +13094,7 @@ function LinkInteractive({
11888
13094
  href: _href,
11889
13095
  ...anchorProps
11890
13096
  }) {
11891
- const router2 = useRouter();
13097
+ const router2 = useRouterContext();
11892
13098
  const anchorRef = useRef(null);
11893
13099
  const intentTimerRef = useRef(null);
11894
13100
  const { logicalHref, href, isActive, resolvedChildren, extraProps } = computeLinkView({ activeProps, children, hash, inactiveProps, params, search, to }, router2);
@@ -11896,15 +13102,15 @@ function LinkInteractive({
11896
13102
  const effectiveDelay = preloadDelay ?? router2.defaultPreloadDelay;
11897
13103
  const effectiveStaleTime = preloadStaleTime ?? router2.defaultPreloadStaleTime;
11898
13104
  const { prefetch } = router2;
11899
- const triggerPrefetch = useCallback(() => {
13105
+ const triggerPrefetch = useCallback3(() => {
11900
13106
  prefetch(logicalHref, { staleTime: effectiveStaleTime });
11901
13107
  }, [prefetch, logicalHref, effectiveStaleTime]);
11902
- useEffect(() => {
13108
+ useEffect2(() => {
11903
13109
  if (effectivePreload === "render") {
11904
13110
  triggerPrefetch();
11905
13111
  }
11906
13112
  }, [effectivePreload, triggerPrefetch]);
11907
- useEffect(() => {
13113
+ useEffect2(() => {
11908
13114
  if (effectivePreload !== "viewport" || !anchorRef.current) {
11909
13115
  return;
11910
13116
  }
@@ -11917,7 +13123,7 @@ function LinkInteractive({
11917
13123
  observer.observe(anchorRef.current);
11918
13124
  return () => observer.disconnect();
11919
13125
  }, [effectivePreload, triggerPrefetch]);
11920
- useEffect(() => () => {
13126
+ useEffect2(() => () => {
11921
13127
  if (intentTimerRef.current !== null) {
11922
13128
  clearTimeout(intentTimerRef.current);
11923
13129
  intentTimerRef.current = null;
@@ -11971,7 +13177,7 @@ function LinkInteractive({
11971
13177
  triggerPrefetch();
11972
13178
  }
11973
13179
  };
11974
- return createElement4("a", {
13180
+ return createElement5("a", {
11975
13181
  "data-furin-link": true,
11976
13182
  href,
11977
13183
  onClick: handleClick,
@@ -12022,7 +13228,7 @@ function renderLinkElement(props, router2) {
12022
13228
  href: _href,
12023
13229
  ...anchorProps
12024
13230
  } = props;
12025
- return createElement4("a", {
13231
+ return createElement5("a", {
12026
13232
  "data-furin-link": true,
12027
13233
  href,
12028
13234
  ...isActive ? { "data-status": "active" } : {},
@@ -12033,11 +13239,11 @@ function renderLinkElement(props, router2) {
12033
13239
  }
12034
13240
  function Link(props) {
12035
13241
  if (typeof window === "undefined") {
12036
- return createElement4(RouterContext.Consumer, {
13242
+ return createElement5(RouterContext.Consumer, {
12037
13243
  children: (routerCtx) => renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER)
12038
13244
  });
12039
13245
  }
12040
- return createElement4(LinkInteractive, props);
13246
+ return createElement5(LinkInteractive, props);
12041
13247
  }
12042
13248
 
12043
13249
  // src/client/default-screens.tsx
@@ -12443,33 +13649,42 @@ function wrapSegmentBoundaries(inner, segment, options) {
12443
13649
  import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
12444
13650
  function buildElement(route, data, rootLayout) {
12445
13651
  const Component = route.page.component;
12446
- let element = createElement5(Component, data);
13652
+ let element = createElement6(Component, {
13653
+ ...data,
13654
+ key: pageKey(route.pattern, data, route.page._route.remountDeps)
13655
+ });
12447
13656
  const byDepth = new Map;
12448
13657
  const legacyRoute = route;
12449
13658
  for (const segment of legacyRoute.segmentBoundaries ?? []) {
12450
- byDepth.set(segment.depth, segment);
13659
+ const boundaries = byDepth.get(segment.depth) ?? [];
13660
+ boundaries.unshift(segment);
13661
+ byDepth.set(segment.depth, boundaries);
12451
13662
  }
12452
13663
  for (let i = route.routeChain.length - 1;i >= 1; i -= 1) {
12453
- element = wrapSegmentBoundaries(element, byDepth.get(i), undefined);
13664
+ for (const segment of byDepth.get(i) ?? []) {
13665
+ element = wrapSegmentBoundaries(element, segment, undefined);
13666
+ }
12454
13667
  const routeEntry = route.routeChain[i];
12455
13668
  if (routeEntry?.layout) {
12456
13669
  const Layout = routeEntry.layout;
12457
- element = createElement5(Layout, data, element);
13670
+ element = createElement6(Layout, data, element);
12458
13671
  }
12459
13672
  }
12460
- element = wrapSegmentBoundaries(element, byDepth.get(0), undefined);
13673
+ for (const segment of byDepth.get(0) ?? []) {
13674
+ element = wrapSegmentBoundaries(element, segment, undefined);
13675
+ }
12461
13676
  if (rootLayout.layout) {
12462
13677
  const RootLayoutComponent = rootLayout.layout;
12463
- element = createElement5(RootLayoutComponent, data, element);
13678
+ element = createElement6(RootLayoutComponent, data, element);
12464
13679
  }
12465
- return element;
13680
+ return withRouteSnapshot(element, route.pattern, data);
12466
13681
  }
12467
13682
  function wrapRootLayout(element, data, rootLayout) {
12468
13683
  if (!rootLayout.layout) {
12469
13684
  return element;
12470
13685
  }
12471
13686
  const RootLayoutComponent = rootLayout.layout;
12472
- return createElement5(RootLayoutComponent, data, element);
13687
+ return createElement6(RootLayoutComponent, data, element);
12473
13688
  }
12474
13689
  function buildNotFoundElement(component, error) {
12475
13690
  const NotFound = component ?? DefaultNotFoundFallback;
@@ -12509,12 +13724,6 @@ function buildErrorElement(component, error, digest, messageOverride, status) {
12509
13724
  }, undefined, false, undefined, this);
12510
13725
  }
12511
13726
 
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
13727
  // src/rsc/render-error.ts
12519
13728
  var INTERNAL_STACK_FRAMES = new Set([
12520
13729
  "<anonymous>",
@@ -12578,17 +13787,88 @@ function isFurinRscRenderError(error) {
12578
13787
  return error instanceof FurinRscRenderError || typeof error === "object" && error !== null && error.code === "FURIN_RSC_RENDER_ERROR";
12579
13788
  }
12580
13789
 
13790
+ // src/shared/defer.ts
13791
+ var DEFERRED_BRAND = Symbol.for("@teyik0/furin/deferred");
13792
+ function isDeferred(value) {
13793
+ return typeof value === "object" && value !== null && DEFERRED_BRAND in value && Object.hasOwn(value, DEFERRED_BRAND) && value[DEFERRED_BRAND] === true;
13794
+ }
13795
+
12581
13796
  // src/server/render/loaders.ts
12582
13797
  init_context_logger();
12583
13798
  init_instrumentation();
12584
13799
  init_patterns();
12585
13800
 
13801
+ // src/server/sync/query-context.ts
13802
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "async_hooks";
13803
+ init_registry();
13804
+ init_instance();
13805
+ var QUERY_CONTEXT2 = Symbol.for("furin.query.server-context.v1");
13806
+ var contextGlobal3 = globalThis;
13807
+ var contexts = contextGlobal3[QUERY_CONTEXT2] ??= new AsyncLocalStorage6;
13808
+ setServerQueryEnvironment(() => contexts.getStore());
13809
+ var trackedQueryPaths = instanceSlot(() => new Set);
13810
+ var deferredQueries = new WeakMap;
13811
+ function deferredQuerySeeds(promise) {
13812
+ return deferredQueries.get(promise);
13813
+ }
13814
+ function captureQueryReads(ctx, run, owner) {
13815
+ const { origin } = new URL(ctx.request.url);
13816
+ const store = new QueryStore(origin);
13817
+ const registry = getAutoInvalidateRegistry();
13818
+ const trackedPaths = trackedQueryPaths();
13819
+ const requestUrl = new URL(ctx.request.url);
13820
+ const path = toLogical(requestUrl.pathname, currentInstance().prefix) + requestUrl.search;
13821
+ const onRead = () => {
13822
+ const seeds = store.dehydrate();
13823
+ registry.registerLoaderTags(path, seeds.map((seed) => queryTag(seed.identity)), owner ?? "eden-queries");
13824
+ trackedPaths.delete(path);
13825
+ if (seeds.length > 0) {
13826
+ trackedPaths.add(path);
13827
+ }
13828
+ if (trackedPaths.size > 1000) {
13829
+ const oldest = trackedPaths.values().next().value;
13830
+ if (oldest !== undefined) {
13831
+ trackedPaths.delete(oldest);
13832
+ registry.unregisterPath(oldest, "eden-queries");
13833
+ registry.unregisterPath(oldest, "eden-request-queries");
13834
+ }
13835
+ }
13836
+ };
13837
+ return contexts.run({ origin, store, onRead }, async () => {
13838
+ const result = { ...await run() };
13839
+ const seeds = store.dehydrate();
13840
+ if (result.type === "data" && seeds.length > 0) {
13841
+ const captured = [...result.syncData.__furinQueries ?? []];
13842
+ mergeQuerySeeds(captured, bindQueryData(result.syncData, seeds));
13843
+ result.syncData = { ...result.syncData, __furinQueries: captured };
13844
+ }
13845
+ if (result.type === "data" && result.deferredPromises) {
13846
+ for (const [key, promise] of Object.entries(result.deferredPromises)) {
13847
+ promise.then((value) => {
13848
+ const completed = store.dehydrate();
13849
+ if (completed.length > 0) {
13850
+ const captured = deferredQueries.get(promise) ?? [];
13851
+ mergeQuerySeeds(captured, bindQueryData({ [key]: value }, completed));
13852
+ deferredQueries.set(promise, captured);
13853
+ }
13854
+ }).catch(() => {
13855
+ return;
13856
+ });
13857
+ }
13858
+ }
13859
+ return result;
13860
+ });
13861
+ }
13862
+
12586
13863
  // src/server/render/mixed-cache.ts
12587
13864
  init_registry();
12588
13865
  init_registry2();
12589
13866
  init_context_logger();
12590
13867
  init_instance();
12591
13868
  init_source_version();
13869
+ function capturedQueryTags() {
13870
+ return currentQueryEnvironment()?.store.dehydrate().map((seed) => queryTag(seed.identity)) ?? [];
13871
+ }
12592
13872
  var mixedCacheKey = Symbol("furin-mixed-loader-cache");
12593
13873
  function cachePathWithSearch(key) {
12594
13874
  const separator = key.indexOf("|");
@@ -12641,7 +13921,11 @@ async function readCachedSegment(entry, revalidate, parentData) {
12641
13921
  return;
12642
13922
  }
12643
13923
  }
12644
- return fromCrossJSON(snapshot.data, {});
13924
+ const environment = currentQueryEnvironment();
13925
+ environment?.store.hydrate(snapshot.queries ?? []);
13926
+ environment?.onRead();
13927
+ const data = fromCrossJSON(snapshot.data, {});
13928
+ return projectQueryData(data, snapshot.queries ?? [], (seed) => seed.data);
12645
13929
  } catch {
12646
13930
  getLogger().warn("Mixed loader cache entry is invalid; loading fresh data");
12647
13931
  }
@@ -12654,7 +13938,8 @@ async function createSegmentSnapshot(data, parentData, parentFieldsRead) {
12654
13938
  })));
12655
13939
  return JSON.stringify({
12656
13940
  data: await toCrossJSONAsync(data),
12657
- dependencies
13941
+ dependencies,
13942
+ queries: bindQueryData(data, currentQueryEnvironment()?.store.dehydrate() ?? []).filter((seed) => (seed.bindings?.length ?? 0) > 0)
12658
13943
  });
12659
13944
  }
12660
13945
  async function acquireSharedSegment(shared, identity) {
@@ -12681,6 +13966,10 @@ async function readSharedSegment(shared, identity, revalidate, parentData) {
12681
13966
  }
12682
13967
  }
12683
13968
  async function commitSharedSegment(shared, identity, lease, cached, revalidate) {
13969
+ const identityTags = new Set(identity.tags);
13970
+ if (capturedQueryTags().some((tag) => !identityTags.has(tag))) {
13971
+ return;
13972
+ }
12684
13973
  try {
12685
13974
  await shared.commit({
12686
13975
  entry: {
@@ -12708,6 +13997,7 @@ function storeLocalSegment(state, generation, key, path, tags, cached) {
12708
13997
  }
12709
13998
  async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, parentFieldsRead, run) {
12710
13999
  const instance = currentInstance();
14000
+ const declaredTags = route.tags ?? [];
12711
14001
  const mode = segment.mode ?? route.mode;
12712
14002
  const revalidate = mode === "isr" ? segment.revalidate ?? 60 : Number.POSITIVE_INFINITY;
12713
14003
  const requestUrl = new URL(ctx.request.url);
@@ -12728,7 +14018,12 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12728
14018
  mode: mode === "isr" ? "isr" : "ssg",
12729
14019
  path,
12730
14020
  scope: instance.prefix,
12731
- tags: route.tags ?? []
14021
+ tags: [
14022
+ ...new Set([
14023
+ ...declaredTags,
14024
+ ...getAutoInvalidateRegistry().tagsForPath(`${path}${requestUrl.search}`)
14025
+ ])
14026
+ ]
12732
14027
  };
12733
14028
  const stored = shared === undefined ? undefined : await readSharedSegment(shared, identity, revalidate, parentData);
12734
14029
  if (stored !== undefined) {
@@ -12744,7 +14039,7 @@ async function cacheMixedPublicLoader(route, ctx, segment, index, parentData, pa
12744
14039
  cachedAt: Date.now(),
12745
14040
  payload: await createSegmentSnapshot(data, parentData, parentFieldsRead)
12746
14041
  };
12747
- storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, route.tags, cached);
14042
+ storeLocalSegment(localState, generation, key, `${path}${requestUrl.search}`, [...declaredTags, ...capturedQueryTags()], cached);
12748
14043
  if (shared !== undefined && lease !== null) {
12749
14044
  await commitSharedSegment(shared, identity, lease, cached, revalidate);
12750
14045
  }
@@ -12779,6 +14074,12 @@ function assertPublicLoaderKey(key) {
12779
14074
  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
14075
  }
12781
14076
  }
14077
+ function assertRequestLoaderKey(key, ctx) {
14078
+ assertPublicLoaderKey(key);
14079
+ if (key === "log" || Object.hasOwn(ctx, key) || key in ctx && !Object.hasOwn(Object.prototype, key)) {
14080
+ throw new Error(`[furin] requestLoader data key "${key}" is reserved: it is overwritten by the SSR loader context. Rename this field to avoid conflicts.`);
14081
+ }
14082
+ }
12782
14083
  function isHttpRedirect(res) {
12783
14084
  return REDIRECT_STATUSES.has(res.status) && res.headers.has("location");
12784
14085
  }
@@ -12793,7 +14094,7 @@ async function readResponseMessage(res) {
12793
14094
  return res.statusText;
12794
14095
  }
12795
14096
  }
12796
- function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
14097
+ function createLoaderCtx(ctx, accumulatedParentPromise, inheritedRequestFields, onParentFieldAccess) {
12797
14098
  const cache = new Map;
12798
14099
  return new Proxy(ctx, {
12799
14100
  get(target, prop) {
@@ -12806,6 +14107,9 @@ function createLoaderCtx(ctx, accumulatedParentPromise, onParentFieldAccess) {
12806
14107
  if (Object.hasOwn(target, prop) || prop in target && !Object.hasOwn(Object.prototype, prop)) {
12807
14108
  return target[prop];
12808
14109
  }
14110
+ if (inheritedRequestFields && Object.hasOwn(inheritedRequestFields, prop)) {
14111
+ return inheritedRequestFields[prop];
14112
+ }
12809
14113
  onParentFieldAccess?.(prop);
12810
14114
  let entry = cache.get(prop);
12811
14115
  if (!entry) {
@@ -12918,6 +14222,8 @@ function runRequestLoaderFields(route, ctx) {
12918
14222
  if (declarations?.length !== route.routeChain.length) {
12919
14223
  throw new Error(`[furin] Missing per-loader request field metadata for ${route.pattern}.`);
12920
14224
  }
14225
+ const declaredKeys = declarations.map((keys) => new Set(keys));
14226
+ const requestKeys = new Set(route.requestKeys);
12921
14227
  const requestContext = createRequestLoaderContext(ctx);
12922
14228
  const results = loaderIndexes.map((index) => {
12923
14229
  const loader = route.routeChain[index]?.requestLoader;
@@ -12928,8 +14234,8 @@ function runRequestLoaderFields(route, ctx) {
12928
14234
  const result = observeLoader(() => invocation, `request:${index}`, ctx.path).then((value) => {
12929
14235
  const data = value;
12930
14236
  for (const key of Object.keys(data)) {
12931
- assertPublicLoaderKey(key);
12932
- if (!declarations[index]?.includes(key)) {
14237
+ assertRequestLoaderKey(key, ctx);
14238
+ if (!declaredKeys[index]?.has(key)) {
12933
14239
  throw new Error(`[furin] requestLoader in ${route.pattern} returned undeclared field "${key}".`);
12934
14240
  }
12935
14241
  }
@@ -12938,27 +14244,36 @@ function runRequestLoaderFields(route, ctx) {
12938
14244
  result.catch(() => {});
12939
14245
  return { index, result };
12940
14246
  });
12941
- const fields = {};
14247
+ let fields = {};
14248
+ const fieldsByLoader = route.routeChain.map((_, boundaryIndex) => {
14249
+ fields = { ...fields };
14250
+ for (const key of declarations[boundaryIndex] ?? []) {
14251
+ if (!requestKeys.has(key)) {
14252
+ continue;
14253
+ }
14254
+ const candidates = results.filter(({ index }) => index <= boundaryIndex && declaredKeys[index]?.has(key));
14255
+ fields[key] = Promise.all(candidates.map(({ result }) => result)).then((values) => {
14256
+ for (let index = values.length - 1;index >= 0; index -= 1) {
14257
+ const data = values[index];
14258
+ if (data && Object.hasOwn(data, key)) {
14259
+ return data[key];
14260
+ }
14261
+ }
14262
+ });
14263
+ fields[key].catch(() => {});
14264
+ }
14265
+ return fields;
14266
+ });
12942
14267
  for (const key of route.requestKeys) {
12943
- const candidates = results.filter(({ index }) => declarations[index]?.includes(key));
12944
- if (candidates.length === 0) {
14268
+ if (!Object.hasOwn(fields, key)) {
12945
14269
  throw new Error(`[furin] No requestLoader declares field "${key}" in ${route.pattern}.`);
12946
14270
  }
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
14271
  }
12957
14272
  const noFieldCompletion = Promise.all(results.filter(({ index }) => declarations[index]?.length === 0).map(({ result }) => result)).then(() => {
12958
14273
  return;
12959
14274
  });
12960
14275
  noFieldCompletion.catch(() => {});
12961
- return { fields, noFieldCompletion };
14276
+ return { fields, fieldsByLoader, noFieldCompletion };
12962
14277
  }
12963
14278
  function requestFieldPromises(route, fields, syncData, publicDeferred) {
12964
14279
  for (const key of Object.keys(fields)) {
@@ -13039,6 +14354,15 @@ async function normalizeLoaderError(err, headers) {
13039
14354
  const message = body || "Something went wrong";
13040
14355
  return { error: err, headers, message, status, type: "error" };
13041
14356
  }
14357
+ 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") {
14358
+ let message = "Something went wrong";
14359
+ if ("detail" in err.value && typeof err.value.detail === "string") {
14360
+ message = err.value.detail;
14361
+ } else if ("title" in err.value && typeof err.value.title === "string") {
14362
+ message = err.value.title;
14363
+ }
14364
+ return { error: err, headers, message, status: err.status, type: "error" };
14365
+ }
13042
14366
  if (isFurinRscRenderError(err)) {
13043
14367
  getLogger().error(err);
13044
14368
  return {
@@ -13067,10 +14391,10 @@ function mergeParentData(parent, own, path) {
13067
14391
  }
13068
14392
  return { ...parent, ...own };
13069
14393
  }
13070
- function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, ctxRecord, publicCtxRecord, mixed) {
14394
+ function startSegmentLoader(route, ctx, segment, index, label, parent, publicParent, inheritedRequestFields, ctxRecord, publicCtxRecord, mixed) {
13071
14395
  const publicSegment = mixed && (segment.mode ?? route.mode) !== "ssr";
13072
14396
  const parentFieldsRead = new Set;
13073
- const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
14397
+ const loaderCtx = createLoaderCtx(publicSegment ? publicCtxRecord : ctxRecord, publicSegment ? publicParent : parent, publicSegment ? undefined : inheritedRequestFields, publicSegment ? (key) => parentFieldsRead.add(key) : undefined);
13074
14398
  return observeLoader(() => {
13075
14399
  const run = async () => await segment.loader?.(loaderCtx) ?? {};
13076
14400
  return publicSegment ? cacheMixedPublicLoader(route, ctx, segment, index, publicParent, parentFieldsRead, run) : run();
@@ -13085,13 +14409,13 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13085
14409
  let accumulatedParentPromise = Promise.resolve({});
13086
14410
  let publicParentPromise = Promise.resolve({});
13087
14411
  let loaderIndex = 0;
13088
- for (const r of route.routeChain) {
14412
+ for (const [routeIndex, r] of route.routeChain.entries()) {
13089
14413
  const parentAccum = accumulatedParentPromise;
13090
14414
  const publicParent = publicParentPromise;
13091
14415
  const privateSegment = mixed && (r.mode ?? route.mode) === "ssr";
13092
14416
  if (r.loader) {
13093
14417
  const index = loaderIndex;
13094
- const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, ctxRecord, publicCtxRecord, mixed);
14418
+ const loaderPromise = startSegmentLoader(route, ctx, r, index, `layout:${loaderIndex}`, parentAccum, publicParent, requestFields?.fieldsByLoader[routeIndex - 1], ctxRecord, publicCtxRecord, mixed);
13095
14419
  loaderIndex += 1;
13096
14420
  loaderMap.set(r, loaderPromise);
13097
14421
  accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => mergeParentData(acc, own, ctx.path));
@@ -13105,7 +14429,7 @@ async function runLoadersInternal(route, ctx, includeRequestData, mixed) {
13105
14429
  }
13106
14430
  }
13107
14431
  }
13108
- const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
14432
+ const pagePromise = route.page.loader ? startSegmentLoader(route, ctx, route.page, route.routeChain.length, "page", accumulatedParentPromise, publicParentPromise, requestFields?.fields, ctxRecord, publicCtxRecord, mixed) : Promise.resolve({});
13109
14433
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
13110
14434
  await requestFields?.noFieldCompletion;
13111
14435
  const headers = {};
@@ -13148,10 +14472,10 @@ function createPublicLoaderContext(ctx) {
13148
14472
  return publicContext;
13149
14473
  }
13150
14474
  function runLoaders(route, ctx) {
13151
- return runLoadersInternal(route, ctx, true, false);
14475
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, false));
13152
14476
  }
13153
14477
  function runPublicLoaders(route, ctx) {
13154
- return runLoadersInternal(route, ctx, false, false);
14478
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, false));
13155
14479
  }
13156
14480
  function hasSsrLoaderAncestor(route) {
13157
14481
  return route.routeChain.some((entry) => entry.mode === "ssr" && entry.loader !== undefined);
@@ -13161,26 +14485,53 @@ function hasMixedLoaderModes(route) {
13161
14485
  return route.routeChain.some((entry) => entry.loader !== undefined && entry.mode !== undefined && (entry.mode !== route.mode || entry.mode === "isr" && (entry.revalidate ?? 60) !== pageRevalidate));
13162
14486
  }
13163
14487
  function runMixedLoaders(route, ctx) {
13164
- return runLoadersInternal(route, ctx, true, true);
14488
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, true, true));
13165
14489
  }
13166
14490
  function runRouteLoaders(route, ctx) {
13167
14491
  return hasMixedLoaderModes(route) ? runMixedLoaders(route, ctx) : runLoaders(route, ctx);
13168
14492
  }
13169
14493
  function runSegmentPublicLoaders(route, ctx) {
13170
- return runLoadersInternal(route, ctx, false, true);
14494
+ return captureQueryReads(ctx, () => runLoadersInternal(route, ctx, false, true));
13171
14495
  }
13172
14496
  function hasRequestLoader(route) {
13173
14497
  return route.routeChain.some((entry) => entry.requestLoader !== undefined);
13174
14498
  }
13175
14499
 
14500
+ // src/server/render/react-stream.ts
14501
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "async_hooks";
14502
+ import { renderToReadableStream as renderReactStream } from "react-dom/server";
14503
+
14504
+ // src/client/client-module.ts
14505
+ import { preloadModule as preloadModule2 } from "react-dom";
14506
+ var resolveModuleHrefs = () => [];
14507
+ var resolveNonce = () => {
14508
+ return;
14509
+ };
14510
+ function setClientModuleNonceResolver(resolver) {
14511
+ resolveNonce = resolver;
14512
+ }
14513
+ function setClientModuleHrefResolver(resolver) {
14514
+ resolveModuleHrefs = resolver;
14515
+ }
14516
+
14517
+ // src/server/render/react-stream.ts
14518
+ var renderNonces = new AsyncLocalStorage7;
14519
+ setClientModuleNonceResolver(() => renderNonces.getStore());
14520
+ function renderToReadableStream(element, options) {
14521
+ const nonce = options?.nonce;
14522
+ return renderNonces.run(typeof nonce === "string" ? nonce : nonce?.script, () => renderReactStream(element, options));
14523
+ }
14524
+
13176
14525
  // src/server/render/route-frame-transport.ts
13177
14526
  async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13178
14527
  try {
13179
14528
  const { rscFrames, value } = serializeRouteFrameValue(await promise, idPrefix);
14529
+ const queries = deferredQuerySeeds(promise);
13180
14530
  return serializeRouteFrame({
13181
14531
  key,
13182
14532
  type: "defer-resolve",
13183
- value
14533
+ value,
14534
+ ...queries && { queries: toCrossJSON(queries) }
13184
14535
  }) + rscFrames;
13185
14536
  } catch (error) {
13186
14537
  return serializeRouteFrame({
@@ -13192,16 +14543,17 @@ async function serializeDeferredRouteFrame(key, promise, idPrefix) {
13192
14543
  }
13193
14544
 
13194
14545
  // src/server/render/template.ts
14546
+ import { readFileSync as readFileSync5 } from "fs";
13195
14547
  init_plugin();
13196
14548
  init_instrumentation();
13197
14549
  init_instance();
13198
- import { readFileSync as readFileSync3 } from "fs";
13199
14550
  var instanceTemplateState = instanceSlot(() => ({
13200
14551
  devAssets: null,
13201
14552
  devCache: null,
13202
14553
  prodAssets: null,
13203
14554
  prodContent: null,
13204
- prodPath: null
14555
+ prodPath: null,
14556
+ prodPreload: null
13205
14557
  }));
13206
14558
  var DEV_TEMPLATE_TTL_MS = 1000;
13207
14559
  var TAG_ATTRIBUTE_PATTERN = /([A-Za-z][\w:-]*)="([^"]*)"/g;
@@ -13319,7 +14671,7 @@ function readTemplate(state) {
13319
14671
  return null;
13320
14672
  }
13321
14673
  try {
13322
- state.prodContent = readFileSync3(state.prodPath, "utf8");
14674
+ state.prodContent = readFileSync5(state.prodPath, "utf8");
13323
14675
  return state.prodContent;
13324
14676
  } catch {
13325
14677
  return null;
@@ -13336,10 +14688,17 @@ function readDocumentAssets(state) {
13336
14688
  state.prodAssets = documentAssetsFromTemplate(template);
13337
14689
  return state.prodAssets;
13338
14690
  }
14691
+ function setProductionPreloadManifest(manifest, instance) {
14692
+ instanceTemplateState(instance).prodPreload = manifest;
14693
+ }
14694
+ function getProductionPreloadManifest() {
14695
+ return instanceTemplateState().prodPreload ?? instanceTemplateState(defaultInstanceBucket()).prodPreload;
14696
+ }
14697
+ setClientModuleHrefResolver((key) => getProductionPreloadManifest()?.modules[key] ?? []);
13339
14698
 
13340
14699
  // src/server/render/ssr.ts
13341
14700
  function withSSRRouterContext(element, contextValue) {
13342
- return createElement6(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement6(RouterContext.Provider, { value: contextValue }, element));
14701
+ return createElement7(SearchStoreContext.Provider, { value: createSearchStore(searchSnapshotFromRouterContext(contextValue)) }, createElement7(RouterContext.Provider, { value: contextValue }, element));
13343
14702
  }
13344
14703
  function hasDocumentMarkers(html) {
13345
14704
  return html.includes('data-furin-head=""') && html.includes('data-furin-scripts=""');
@@ -13408,7 +14767,8 @@ async function renderElementWithShellFallback(element, errorComponent, ssrContex
13408
14767
  }
13409
14768
  }
13410
14769
  function assertDeferredModeAllowed(route, deferredPromises) {
13411
- const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !route.requestKeys?.includes(key));
14770
+ const requestKeys = new Set(route.requestKeys);
14771
+ const deferredKeys = Object.keys(deferredPromises ?? {}).filter((key) => !requestKeys.has(key));
13412
14772
  if (deferredKeys.length > 0 && route.mode !== "ssr" && !hasSsrLoaderAncestor(route)) {
13413
14773
  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
14774
  }
@@ -13443,6 +14803,10 @@ function resolveDocumentAssets(ctx) {
13443
14803
  }
13444
14804
  return documentAssetsFromTemplate(generateIndexHtml());
13445
14805
  }
14806
+ function withRouteModulePreloads(assets, pattern) {
14807
+ const modulePreloads = getProductionPreloadManifest()?.routes[pattern];
14808
+ return modulePreloads ? { ...assets, modulePreloads } : assets;
14809
+ }
13446
14810
  async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomputedLoaderResult, searchRoutes) {
13447
14811
  const loaderStart = Date.now();
13448
14812
  const loaderResult = precomputedLoaderResult ?? await runRouteLoaders(route, ctx);
@@ -13450,7 +14814,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13450
14814
  if (loaderResult.type === "redirect") {
13451
14815
  return loaderResult.response;
13452
14816
  }
13453
- if (throwOnFailure && (loaderResult.type === "not-found" || loaderResult.type === "error")) {
14817
+ if (throwOnFailure && loaderResult.type === "error") {
13454
14818
  throw loaderResult.error;
13455
14819
  }
13456
14820
  const isNotFound = loaderResult.type === "not-found";
@@ -13461,7 +14825,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13461
14825
  assertDeferredModeAllowed(route, deferredPromises);
13462
14826
  const { headers } = loaderResult;
13463
14827
  const componentProps = deferredPromises === undefined ? syncData : { ...syncData, ...deferredPromises };
13464
- const assets = await resolveDocumentAssets(ctx);
14828
+ const assets = withRouteModulePreloads(await resolveDocumentAssets(ctx), route.pattern);
13465
14829
  const errorComponent = route.error ?? root.error;
13466
14830
  let element;
13467
14831
  let headData;
@@ -13489,6 +14853,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13489
14853
  const ssrContext = {
13490
14854
  basePath: resolvedBasePath,
13491
14855
  currentHref: currentHrefFromContext(ctx, resolvedBasePath),
14856
+ currentPattern: route.pattern,
13492
14857
  defaultPreload: "intent",
13493
14858
  defaultPreloadDelay: 50,
13494
14859
  defaultPreloadStaleTime: 30000,
@@ -13519,7 +14884,7 @@ async function prepareRender(route, ctx, root, basePath, throwOnFailure, precomp
13519
14884
  }
13520
14885
  async function renderBufferedResult(prepared, route, root) {
13521
14886
  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, {
14887
+ 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
14888
  __furinError: { digest, message, status: 500 },
13524
14889
  __furinStatus: 500
13525
14890
  }));
@@ -13544,9 +14909,30 @@ async function renderBufferedResult(prepared, route, root) {
13544
14909
  headers,
13545
14910
  html,
13546
14911
  ndjson: await serializeLoaderDataNdjson(syncData, deferredPromises),
14912
+ queryTags: queryTagsFromData(syncData),
13547
14913
  status: prepared.status
13548
14914
  };
13549
14915
  }
14916
+ async function normalizePrerenderContext(route, ctx) {
14917
+ const parsedParams = await parseRouteParams(ctx.params, mergeRouteSchemas(route.routeChain, "params"));
14918
+ if (!parsedParams.ok) {
14919
+ throw new Error(`[furin] Invalid prerender params for "${route.pattern}".`, {
14920
+ cause: parsedParams.errors
14921
+ });
14922
+ }
14923
+ ctx.params = parsedParams.params;
14924
+ const querySchema = mergeRouteSchemas(route.routeChain, "query");
14925
+ if (querySchema === undefined) {
14926
+ return;
14927
+ }
14928
+ const parsedQuery = await parseRouteQuery(new URL(ctx.request.url), querySchema);
14929
+ if (!parsedQuery.ok) {
14930
+ throw new Error(`[furin] Invalid prerender query for "${route.pattern}".`, {
14931
+ cause: parsedQuery.errors
14932
+ });
14933
+ }
14934
+ ctx.query = parsedQuery.query;
14935
+ }
13550
14936
  function renderForPath(route, params, root, origin, mode, basePath, searchRoutes, search, requestContext) {
13551
14937
  return runInSyntheticRenderScope(async () => {
13552
14938
  const resolvedPath = resolvePath(route.pattern, params);
@@ -13572,6 +14958,9 @@ function renderForPath(route, params, root, origin, mode, basePath, searchRoutes
13572
14958
  request: new Request(requestUrl),
13573
14959
  set: { headers: {} }
13574
14960
  };
14961
+ if (requestContext === undefined) {
14962
+ await normalizePrerenderContext(route, ctx);
14963
+ }
13575
14964
  const loaderResult = await (hasMixedLoaderModes(route) ? runSegmentPublicLoaders(route, ctx) : runPublicLoaders(route, ctx));
13576
14965
  const prepared = await prepareRender(route, ctx, root, basePath, true, loaderResult, searchRoutes);
13577
14966
  if (prepared instanceof Response) {
@@ -13612,7 +15001,7 @@ async function serializeLoaderDataNdjson(syncData, deferredPromises) {
13612
15001
  }
13613
15002
 
13614
15003
  // src/server/render/static-params.ts
13615
- import { dirname as dirname8, relative as relative5 } from "path";
15004
+ import { dirname as dirname10, relative as relative5 } from "path";
13616
15005
  init_patterns();
13617
15006
  var STATIC_PARAMS_CONCURRENCY = 4;
13618
15007
  function collectStaticParamsStages(route) {
@@ -13633,8 +15022,8 @@ function ancestorPattern(route, ancestors) {
13633
15022
  if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
13634
15023
  return route.pattern;
13635
15024
  }
13636
- const pagesDir = dirname8(rootSourcePath);
13637
- const ancestorDir = dirname8(ancestorSourcePath);
15025
+ const pagesDir = dirname10(rootSourcePath);
15026
+ const ancestorDir = dirname10(ancestorSourcePath);
13638
15027
  if (ancestorDir === pagesDir) {
13639
15028
  return "/";
13640
15029
  }
@@ -13734,25 +15123,44 @@ async function prerenderRoute(route, params, root, origin, mode, basePath, searc
13734
15123
  html: renderResult.html,
13735
15124
  ndjson: renderResult.ndjson,
13736
15125
  status: renderResult.status,
13737
- tags: route.tags
15126
+ tags: [...route.tags ?? [], ...renderResult.queryTags ?? []]
13738
15127
  };
13739
15128
  }
13740
- async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15129
+ async function prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes) {
13741
15130
  const resolvedPath = resolvePath(route.pattern, params);
13742
15131
  const cached = getSSGCache(resolvedPath);
13743
15132
  if (cached) {
13744
15133
  if (cached.tags === route.tags) {
13745
- return cached;
15134
+ return { cacheStored: true, entry: cached };
13746
15135
  }
13747
- const taggedEntry = { ...cached, tags: route.tags };
15136
+ const taggedEntry = {
15137
+ ...cached,
15138
+ tags: [
15139
+ ...route.tags ?? [],
15140
+ ...(cached.tags ?? []).filter((tag) => queryFromTag(tag) !== undefined)
15141
+ ]
15142
+ };
13748
15143
  setSSGCache(resolvedPath, taggedEntry);
13749
- return taggedEntry;
15144
+ return { cacheStored: true, entry: taggedEntry };
13750
15145
  }
13751
- const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
13752
- if (entry instanceof Response) {
13753
- return entry;
15146
+ const cache = ssgRouteCache();
15147
+ const generation = cache.captureGeneration(resolvedPath);
15148
+ try {
15149
+ const entry = await prerenderRoute(route, params, root, origin, "ssg", basePath, searchRoutes);
15150
+ if (entry instanceof Response || entry.status !== 200 || !generation.valid) {
15151
+ return { cacheStored: false, entry };
15152
+ }
15153
+ setSSGCache(resolvedPath, entry);
15154
+ return { cacheStored: true, entry };
15155
+ } finally {
15156
+ cache.releaseGeneration(resolvedPath, generation);
15157
+ }
15158
+ }
15159
+ async function prerenderSSG(route, params, root, origin, basePath, searchRoutes) {
15160
+ const { entry } = await prerenderLocalSSG(route, params, root, origin, basePath, searchRoutes);
15161
+ if (!(entry instanceof Response) && entry.status >= 500) {
15162
+ throw new Error(`[furin] Failed to prerender SSG route "${route.pattern}" (HTTP ${entry.status}).`);
13754
15163
  }
13755
- setSSGCache(resolvedPath, entry);
13756
15164
  return entry;
13757
15165
  }
13758
15166
  // src/build/ssg-cache.ts
@@ -13815,9 +15223,9 @@ async function buildSSGCacheSnapshot(routes, root, origin, basePath) {
13815
15223
  }
13816
15224
 
13817
15225
  // 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";
13820
- import { fileURLToPath as fileURLToPath4 } from "url";
15226
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
15227
+ import { basename as basename4, join as join9 } from "path";
15228
+ import { fileURLToPath as fileURLToPath5 } from "url";
13821
15229
  init_transform_isomorphic();
13822
15230
 
13823
15231
  // src/rsc/version.ts
@@ -13866,9 +15274,9 @@ function assertInstalledRscVersions() {
13866
15274
  // src/rsc/build/index.ts
13867
15275
  async function buildRscGraph(apps, outDir, buildId, userPlugins) {
13868
15276
  await assertInstalledRscVersions();
13869
- const graphDir = join8(outDir, "rsc");
15277
+ const graphDir = join9(outDir, "rsc");
13870
15278
  mkdirSync3(graphDir, { recursive: true });
13871
- const rscEntry = fileURLToPath4(import.meta.resolve("../../rsc-server.tsx"));
15279
+ const rscEntry = fileURLToPath5(import.meta.resolve("../../rsc-server.tsx"));
13872
15280
  const entrypoints = [
13873
15281
  ...new Set(apps.flatMap(({ root, routes }) => [
13874
15282
  root.path,
@@ -13908,7 +15316,7 @@ ${result.logs.map((log) => log.message).join(`
13908
15316
  `)}`);
13909
15317
  }
13910
15318
  const codecResult = await runBunBuild({
13911
- entrypoints: [fileURLToPath4(import.meta.resolve("../server-codec.ts"))],
15319
+ entrypoints: [fileURLToPath5(import.meta.resolve("../server-codec.ts"))],
13912
15320
  outdir: outDir,
13913
15321
  target: "bun",
13914
15322
  format: "esm",
@@ -13926,22 +15334,23 @@ ${result.logs.map((log) => log.message).join(`
13926
15334
  ${codecResult.logs.map((log) => log.message).join(`
13927
15335
  `)}`);
13928
15336
  }
13929
- const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename3(output.path)}` }));
15337
+ const css = result.outputs.filter((output) => output.path.endsWith(".css")).map((output) => ({ href: `/_rsc/${basename4(output.path)}` }));
13930
15338
  const manifest = { buildId, clientReferences: [], css };
13931
- writeFileSync3(join8(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
15339
+ writeFileSync4(join9(graphDir, "manifest.json"), JSON.stringify(manifest, null, 2));
13932
15340
  return manifest;
13933
15341
  }
13934
15342
 
13935
15343
  // src/adapter/runtime-build.ts
13936
15344
  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");
15345
+ var _pkgRoot2 = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
15346
+ var _pkgSrcDir2 = existsSync8(join10(_pkgRoot2, "src", "furin.ts")) ? join10(_pkgRoot2, "src") : join10(_pkgRoot2, "dist");
13939
15347
  var _ext2 = ".ts";
13940
15348
  var PPR_ROUTE_IMPORT_RE = /ppr-route(?:\.ts)?$/;
13941
15349
  var MIXED_CACHE_IMPORT_RE = /mixed-cache(?:\.ts)?$/;
13942
15350
  var ANY_MODULE_RE = /.*/;
13943
15351
  var REACT_SERVER_IMPORT_RE = /^react-dom\/server(?:\.edge)?$/;
13944
15352
  var REACT_STATIC_IMPORT_RE = /^react-dom\/static\.edge$/;
15353
+ var SCRIPT_FILE_RE = /\.[cm]?[jt]sx?$/;
13945
15354
  var BUILD_ID_INPUT_PATHS = [
13946
15355
  `${_pkgSrcDir2}/build/compile-entry${_ext2}`,
13947
15356
  `${_pkgSrcDir2}/build/entry-template${_ext2}`,
@@ -13997,16 +15406,49 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
13997
15406
  }
13998
15407
  }
13999
15408
  }
15409
+ const sources = new Map;
15410
+ const visit = async (inputPath) => {
15411
+ const path = existsSync8(inputPath) ? realpathSync4(inputPath) : inputPath;
15412
+ fingerprintPaths.delete(inputPath);
15413
+ fingerprintPaths.add(path);
15414
+ if (sources.has(path)) {
15415
+ return;
15416
+ }
15417
+ sources.set(path, "");
15418
+ const content = existsSync8(path) ? await Bun.file(path).text() : "";
15419
+ sources.set(path, content);
15420
+ if (!SCRIPT_FILE_RE.test(path)) {
15421
+ return;
15422
+ }
15423
+ const transpiler = new Bun.Transpiler({ loader: path.endsWith("x") ? "tsx" : "ts" });
15424
+ await Promise.all(transpiler.scanImports(content).flatMap(({ path: specifier }) => {
15425
+ if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
15426
+ return [];
15427
+ }
15428
+ let dependency;
15429
+ try {
15430
+ dependency = Bun.resolveSync(specifier, dirname11(path));
15431
+ } catch {
15432
+ return [];
15433
+ }
15434
+ if (!isAbsolute5(dependency) || toPosixPath(dependency).includes("/node_modules/")) {
15435
+ return [];
15436
+ }
15437
+ fingerprintPaths.add(dependency);
15438
+ return [visit(dependency)];
15439
+ }));
15440
+ };
15441
+ await Promise.all([...fingerprintPaths].map(visit));
14000
15442
  for (const path of BUILD_ID_INPUT_PATHS) {
14001
- if (!existsSync7(path)) {
15443
+ if (!existsSync8(path)) {
14002
15444
  console.warn(`[furin] Warning: build fingerprint input "${toPosixPath(path)}" is missing \u2014 ` + "the generated build ID may not reflect all framework changes.");
14003
15445
  }
14004
15446
  fingerprintPaths.add(path);
14005
15447
  }
14006
- const fileParts = await Promise.all([...fingerprintPaths].toSorted().map(async (path) => {
14007
- const content = existsSync7(path) ? await Bun.file(path).text() : "";
15448
+ const fileParts = (await Promise.all([...fingerprintPaths].map(async (path) => {
15449
+ const content = sources.get(path) ?? (existsSync8(path) ? await Bun.file(path).text() : "");
14008
15450
  return `${stableFingerprintPath(path, projectRoot)}:${content}`;
14009
- }));
15451
+ }))).sort(compareCodeUnits);
14010
15452
  const routeParts = routes.map((route) => JSON.stringify({
14011
15453
  mode: route.mode,
14012
15454
  path: stableFingerprintPath(route.path, projectRoot),
@@ -14018,15 +15460,16 @@ async function createBuildFingerprint(entryChunk, cssChunks, routes, root, serve
14018
15460
  `);
14019
15461
  }
14020
15462
  function stableFingerprintPath(path, projectRoot) {
14021
- const projectPath = relative6(projectRoot, path);
14022
- if (!isAbsolute3(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
15463
+ const absolutePath = existsSync8(path) ? realpathSync4(path) : path;
15464
+ const projectPath = relative6(realpathSync4(projectRoot), absolutePath);
15465
+ if (!isAbsolute5(projectPath) && projectPath !== ".." && !projectPath.startsWith("../") && !projectPath.startsWith("..\\")) {
14023
15466
  return `app/${toPosixPath(projectPath)}`;
14024
15467
  }
14025
- const frameworkPath = relative6(_pkgRoot2, path);
14026
- if (!isAbsolute3(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
15468
+ const frameworkPath = relative6(_pkgRoot2, absolutePath);
15469
+ if (!isAbsolute5(frameworkPath) && frameworkPath !== ".." && !frameworkPath.startsWith("../") && !frameworkPath.startsWith("..\\")) {
14027
15470
  return `furin/${toPosixPath(frameworkPath)}`;
14028
15471
  }
14029
- return `external/${basename4(path)}`;
15472
+ return `external/${basename5(path)}`;
14030
15473
  }
14031
15474
  function buildCompileMetadata(root, routes) {
14032
15475
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14050,9 +15493,9 @@ function buildCompileMetadata(root, routes) {
14050
15493
  }
14051
15494
  function pprRuntimePlugin(apps) {
14052
15495
  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");
14054
- const reactServerPath = fileURLToPath5(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
14055
- const reactStaticPath = fileURLToPath5(import.meta.resolve("react-dom/static.edge"));
15496
+ const pprPath = resolve8(_pkgSrcDir2, "server/render/ppr-route.ts");
15497
+ const reactServerPath = fileURLToPath6(import.meta.resolve(enabled ? "react-dom/server.edge" : "react-dom/server"));
15498
+ const reactStaticPath = fileURLToPath6(import.meta.resolve("react-dom/static.edge"));
14056
15499
  return {
14057
15500
  name: "furin-ppr-runtime",
14058
15501
  setup(build) {
@@ -14062,7 +15505,7 @@ function pprRuntimePlugin(apps) {
14062
15505
  return;
14063
15506
  }
14064
15507
  build.onResolve({ filter: PPR_ROUTE_IMPORT_RE }, ({ path, importer }) => {
14065
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15508
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14066
15509
  if (absolute !== pprPath && `${absolute}.ts` !== pprPath) {
14067
15510
  return;
14068
15511
  }
@@ -14080,7 +15523,7 @@ export const runPprPublicLoaders = renderPprRoute;`,
14080
15523
  }
14081
15524
  function mixedRuntimePlugin(apps) {
14082
15525
  const enabled = apps.some((app) => app.routes.some(hasMixedLoaderModes));
14083
- const mixedPath = resolve6(_pkgSrcDir2, "server/render/mixed-cache.ts");
15526
+ const mixedPath = resolve8(_pkgSrcDir2, "server/render/mixed-cache.ts");
14084
15527
  return {
14085
15528
  name: "furin-mixed-runtime",
14086
15529
  setup(build) {
@@ -14088,7 +15531,7 @@ function mixedRuntimePlugin(apps) {
14088
15531
  return;
14089
15532
  }
14090
15533
  build.onResolve({ filter: MIXED_CACHE_IMPORT_RE }, ({ path, importer }) => {
14091
- const absolute = resolve6(dirname9(importer.split("?")[0]), path);
15534
+ const absolute = resolve8(dirname11(importer.split("?")[0]), path);
14092
15535
  if (absolute !== mixedPath && `${absolute}.ts` !== mixedPath) {
14093
15536
  return;
14094
15537
  }
@@ -14114,15 +15557,16 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
14114
15557
  const modulePaths = routeSourcePaths(app);
14115
15558
  const clientDirName = clientDirNameForPrefix(prefix);
14116
15559
  const label = prefix === "" ? "root app" : `app "${prefix}"`;
14117
- const { entryChunk, cssChunks } = await buildClient(routes, {
15560
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14118
15561
  basePath: prefix,
14119
15562
  clientDirName,
14120
15563
  clientLogging: options.clientLogging ?? false,
14121
- metafilePath: options.analyze ? join9(dirname9(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
15564
+ metafilePath: options.analyze ? join10(dirname11(targetDir), "analysis", `${targetName}-${clientDirName}.json`) : undefined,
14122
15565
  optimizeImports: options.optimizeImports,
14123
15566
  outDir: targetDir,
14124
15567
  pagesDir: app.pagesDir,
14125
15568
  plugins: options.plugins,
15569
+ preloadRouteChunks: options.preload?.routeChunks,
14126
15570
  publicPath: `${prefix}/_client/`,
14127
15571
  reactCompiler: options.reactCompiler,
14128
15572
  rootLayout: root.path
@@ -14130,10 +15574,11 @@ async function buildRuntimeApp(app, projectRoot, targetDir, serverEntry, options
14130
15574
  const buildFingerprint = await createBuildFingerprint(`${prefix}
14131
15575
  ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14132
15576
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14133
- const clientDir = join9(targetDir, clientDirName);
15577
+ const clientDir = join10(targetDir, clientDirName);
14134
15578
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14135
- writeFileSync4(join9(clientDir, "index.html"), indexHtml);
15579
+ writeFileSync5(join10(clientDir, "index.html"), indexHtml);
14136
15580
  setProductionTemplateContent(indexHtml);
15581
+ setProductionPreloadManifest(preloadManifest);
14137
15582
  ssgRouteCache().clear();
14138
15583
  let ssgCache;
14139
15584
  let prerenders = [];
@@ -14157,6 +15602,7 @@ ${entryChunk}`, cssChunks, routes, root, serverEntry, modulePaths, projectRoot);
14157
15602
  modulePaths,
14158
15603
  nativeRoutes: composableRouteModuleSpecifier(app),
14159
15604
  prefix,
15605
+ preloadManifest,
14160
15606
  rootConventions,
14161
15607
  rootPath: root.path,
14162
15608
  routeMetadata,
@@ -14192,7 +15638,7 @@ async function buildRuntimeAppsSequentially(apps, projectRoot, targetDir, server
14192
15638
  // src/adapter/bun.ts
14193
15639
  function generateBootEntry(appEntry, outDir, filename) {
14194
15640
  ensureDir(outDir);
14195
- const entryPath = join10(outDir, filename);
15641
+ const entryPath = join11(outDir, filename);
14196
15642
  return createVirtualBuildEntry(entryPath, serverBootSource(appEntry), "ts");
14197
15643
  }
14198
15644
  function collectEmbeddedAssets(entryApps, publicDir, compile) {
@@ -14215,7 +15661,7 @@ function relocateServerMaps(build, enabled, targetDir, buildRoot) {
14215
15661
  if (!enabled) {
14216
15662
  return;
14217
15663
  }
14218
- movePrivateServerSourceMaps(targetDir, join10(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
15664
+ movePrivateServerSourceMaps(targetDir, join11(buildRoot, "private", "server-sourcemaps", "bun"), build.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
14219
15665
  }
14220
15666
  function writeServerMetafile(build, analyze, buildRoot) {
14221
15667
  if (!analyze) {
@@ -14224,10 +15670,10 @@ function writeServerMetafile(build, analyze, buildRoot) {
14224
15670
  if (build.metafile === undefined) {
14225
15671
  throw new Error("[furin] Bun server build did not produce the requested metafile.");
14226
15672
  }
14227
- const analysisDir = join10(buildRoot, "analysis");
15673
+ const analysisDir = join11(buildRoot, "analysis");
14228
15674
  ensureDir(analysisDir);
14229
- const metafilePath = join10(analysisDir, "bun-server.json");
14230
- writeFileSync5(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
15675
+ const metafilePath = join11(analysisDir, "bun-server.json");
15676
+ writeFileSync6(metafilePath, `${JSON.stringify(build.metafile, null, 2)}
14231
15677
  `);
14232
15678
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
14233
15679
  }
@@ -14236,7 +15682,7 @@ function finalizeEmbeddedAssets(compile, apps, targetDir, manifest) {
14236
15682
  return;
14237
15683
  }
14238
15684
  for (const app of apps) {
14239
- rmSync2(join10(targetDir, clientDirNameForPrefix(app.prefix)), {
15685
+ rmSync2(join11(targetDir, clientDirNameForPrefix(app.prefix)), {
14240
15686
  force: true,
14241
15687
  recursive: true
14242
15688
  });
@@ -14259,7 +15705,7 @@ async function createBunAppEntry(apps, entryApps, options, publicDir, serverEntr
14259
15705
  ...context.extraContext ?? [],
14260
15706
  ` clientDir: import.meta.dir + ${JSON.stringify(`/${clientDirNameForPrefix(context.prefix ?? "")}`)},`
14261
15707
  ],
14262
- templateHtml: readFileSync4(join10(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
15708
+ templateHtml: readFileSync6(join11(targetDir, clientDirNameForPrefix(context.prefix ?? ""), "index.html"), "utf8")
14263
15709
  }));
14264
15710
  return await materializeServerAppEntry({
14265
15711
  apps: contexts,
@@ -14278,27 +15724,27 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14278
15724
  }
14279
15725
  const target = "bun";
14280
15726
  const targetManifest = buildTargetManifest(rootDir, buildRoot, target, serverEntry);
14281
- const targetDir = resolve7(rootDir, targetManifest.targetDir);
15727
+ const targetDir = resolve9(rootDir, targetManifest.targetDir);
14282
15728
  rmSync2(targetDir, { force: true, recursive: true });
14283
- rmSync2(join10(buildRoot, "private", "server-sourcemaps", "bun"), {
15729
+ rmSync2(join11(buildRoot, "private", "server-sourcemaps", "bun"), {
14284
15730
  force: true,
14285
15731
  recursive: true
14286
15732
  });
14287
15733
  ensureDir(targetDir);
14288
- const publicDir = existsSync8(join10(rootDir, "public")) ? join10(rootDir, "public") : undefined;
15734
+ const publicDir = existsSync9(join11(rootDir, "public")) ? join11(rootDir, "public") : undefined;
14289
15735
  const { entryApps, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "bun");
14290
15736
  targetManifest.buildId = headlineBuildId;
14291
15737
  if (serverEntry) {
14292
- targetManifest.rscManifestPath = toPosixPath(join10(targetManifest.targetDir, "rsc", "manifest.json"));
15738
+ targetManifest.rscManifestPath = toPosixPath(join11(targetManifest.targetDir, "rsc", "manifest.json"));
14293
15739
  }
14294
- const targetPublicDir = publicDir ? join10(targetDir, "public") : undefined;
15740
+ const targetPublicDir = publicDir ? join11(targetDir, "public") : undefined;
14295
15741
  if (publicDir && targetPublicDir && options.compile !== "embed") {
14296
15742
  copyDirRecursive(publicDir, targetPublicDir);
14297
15743
  }
14298
15744
  const appEntry = await createBunAppEntry(apps, entryApps, options, publicDir, serverEntry, targetDir);
14299
15745
  if (options.compile && serverEntry && appEntry) {
14300
15746
  const serverFilename = compiledServerFilename(process.platform);
14301
- const outfile = join10(targetDir, serverFilename);
15747
+ const outfile = join11(targetDir, serverFilename);
14302
15748
  const entry = generateBootEntry(appEntry, targetDir, "_compile-entry.ts");
14303
15749
  const embeddedAssets = collectEmbeddedAssets(entryApps, publicDir, options.compile);
14304
15750
  const serverBuild = await runBunBuild({
@@ -14328,7 +15774,7 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14328
15774
  relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
14329
15775
  writeServerMetafile(serverBuild, options.analyze, buildRoot);
14330
15776
  console.log(`[furin] Server binary: ${outfile}`);
14331
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, serverFilename));
15777
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, serverFilename));
14332
15778
  finalizeEmbeddedAssets(options.compile, apps, targetDir, targetManifest);
14333
15779
  } else if (serverEntry && appEntry) {
14334
15780
  const entry = generateBootEntry(appEntry, targetDir, "server.ts");
@@ -14355,29 +15801,31 @@ async function buildBunTarget(apps, rootDir, buildRoot, serverEntry, options) {
14355
15801
  });
14356
15802
  relocateServerMaps(serverBuild, options.serverSourceMaps, targetDir, buildRoot);
14357
15803
  writeServerMetafile(serverBuild, options.analyze, buildRoot);
14358
- console.log(`[furin] Server bundle: ${toPosixPath(join10(targetManifest.targetDir, "server.js"))}`);
14359
- targetManifest.serverPath = toPosixPath(join10(targetManifest.targetDir, "server.js"));
15804
+ console.log(`[furin] Server bundle: ${toPosixPath(join11(targetManifest.targetDir, "server.js"))}`);
15805
+ targetManifest.serverPath = toPosixPath(join11(targetManifest.targetDir, "server.js"));
14360
15806
  }
14361
15807
  return targetManifest;
14362
15808
  }
14363
15809
 
14364
15810
  // 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";
15811
+ import { existsSync as existsSync10, rmSync as rmSync3, writeFileSync as writeFileSync7 } from "fs";
15812
+ import { join as join12, relative as relative7, resolve as resolve10 } from "path";
15813
+ init_transform_isomorphic();
14367
15814
  async function buildPackageTarget(app, rootDir, buildRoot, options) {
14368
15815
  const { prefix, root, routes, pagesDir } = app;
14369
15816
  const modulePaths = routeSourcePaths(app);
14370
- const targetDir = join11(buildRoot, "package");
15817
+ const targetDir = join12(buildRoot, "package");
14371
15818
  rmSync3(targetDir, { force: true, recursive: true });
14372
15819
  ensureDir(targetDir);
14373
- const { entryChunk, cssChunks } = await buildClient(routes, {
15820
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(routes, {
14374
15821
  basePath: prefix,
14375
15822
  clientLogging: options.clientLogging ?? false,
14376
- metafilePath: options.analyze ? join11(buildRoot, "analysis", "package-client.json") : undefined,
15823
+ metafilePath: options.analyze ? join12(buildRoot, "analysis", "package-client.json") : undefined,
14377
15824
  optimizeImports: options.optimizeImports,
14378
15825
  outDir: targetDir,
14379
15826
  pagesDir,
14380
15827
  plugins: options.plugins,
15828
+ preloadRouteChunks: options.preload?.routeChunks,
14381
15829
  publicPath: `${prefix}/_client/`,
14382
15830
  reactCompiler: options.reactCompiler,
14383
15831
  rootLayout: root.path
@@ -14385,14 +15833,15 @@ async function buildPackageTarget(app, rootDir, buildRoot, options) {
14385
15833
  const buildFingerprint = await createBuildFingerprint(`${prefix}
14386
15834
  ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14387
15835
  const buildId = Bun.hash(buildFingerprint).toString(16).slice(0, 12);
14388
- const clientDir = join11(targetDir, "client");
14389
- const publicDir = join11(rootDir, "public");
14390
- if (existsSync9(publicDir)) {
14391
- copyDirRecursive(publicDir, join11(targetDir, "public"));
15836
+ const clientDir = join12(targetDir, "client");
15837
+ const publicDir = join12(rootDir, "public");
15838
+ if (existsSync10(publicDir)) {
15839
+ copyDirRecursive(publicDir, join12(targetDir, "public"));
14392
15840
  }
14393
15841
  const indexHtml = generateProdIndexHtml(entryChunk, cssChunks, buildId, undefined, false);
14394
- writeFileSync6(join11(clientDir, "index.html"), indexHtml);
15842
+ writeFileSync7(join12(clientDir, "index.html"), indexHtml);
14395
15843
  setProductionTemplateContent(indexHtml);
15844
+ setProductionPreloadManifest(preloadManifest);
14396
15845
  ssgRouteCache().clear();
14397
15846
  const ssgCache = await buildSSGCacheSnapshot(routes, root, "http://localhost", prefix);
14398
15847
  const rootConventions = root.errorPath || root.notFoundPath ? {
@@ -14420,6 +15869,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14420
15869
  modulePaths,
14421
15870
  nativeRoutes: composableRouteModuleSpecifier(app),
14422
15871
  prefix,
15872
+ preloadManifest,
14423
15873
  rootConventions,
14424
15874
  rootPath: root.path,
14425
15875
  routeMetadata,
@@ -14430,7 +15880,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14430
15880
  headerComment: "// Auto-generated by `furin build --target package` \u2014 do not edit",
14431
15881
  mode: "register"
14432
15882
  });
14433
- const registerEntry = join11(targetDir, "register.ts");
15883
+ const registerEntry = join12(targetDir, "register.ts");
14434
15884
  const register = createVirtualBuildEntry(registerEntry, registerSource, "ts");
14435
15885
  const result = await runBunBuild({
14436
15886
  entrypoints: [register.entrypoint],
@@ -14442,7 +15892,9 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14442
15892
  plugins: [
14443
15893
  register.plugin,
14444
15894
  ...options.plugins ?? [],
14445
- createRoutesPlugin({ instances: [app], target: "server" })
15895
+ createRoutesPlugin({ instances: [app], target: "server" }),
15896
+ isomorphicTransformPlugin("server"),
15897
+ environmentGuardPlugin("ssr")
14446
15898
  ],
14447
15899
  sourcemap: "none",
14448
15900
  target: "bun"
@@ -14450,7 +15902,7 @@ ${entryChunk}`, cssChunks, routes, root, null, modulePaths, rootDir);
14450
15902
  if (!result.success) {
14451
15903
  throw new AggregateError(result.logs, "[furin] package register build failed");
14452
15904
  }
14453
- const relativePagesDir = toPosixPath(relative7(targetDir, resolve8(rootDir, pagesDir)));
15905
+ const relativePagesDir = toPosixPath(relative7(targetDir, resolve10(rootDir, pagesDir)));
14454
15906
  const factorySource = `// Auto-generated by \`furin build --target package\` \u2014 do not edit
14455
15907
  import { fileURLToPath } from "node:url";
14456
15908
  import { furin } from "@teyik0/furin";
@@ -14477,7 +15929,7 @@ export function createFurinApp(options = {}) {
14477
15929
 
14478
15930
  export const prefix = ${JSON.stringify(prefix)};
14479
15931
  `;
14480
- writeFileSync6(join11(targetDir, "index.js"), factorySource);
15932
+ writeFileSync7(join12(targetDir, "index.js"), factorySource);
14481
15933
  const dtsSource = `import type { FurinOptions, furin } from "@teyik0/furin";
14482
15934
 
14483
15935
  /** Extra furin() options \u2014 pagesDir/prefix/clientDir are baked into the package and cannot be overridden. */
@@ -14485,7 +15937,7 @@ export type CreateFurinAppOptions = Omit<FurinOptions, "pagesDir" | "prefix" | "
14485
15937
  export declare function createFurinApp(options?: CreateFurinAppOptions): ReturnType<typeof furin>;
14486
15938
  export declare const prefix: string;
14487
15939
  `;
14488
- writeFileSync6(join11(targetDir, "index.d.ts"), dtsSource);
15940
+ writeFileSync7(join12(targetDir, "index.d.ts"), dtsSource);
14489
15941
  console.log(`[furin] Package artifact: ${toPosixPath(relative7(rootDir, targetDir))}`);
14490
15942
  return {
14491
15943
  buildId,
@@ -14496,19 +15948,19 @@ export declare const prefix: string;
14496
15948
  }
14497
15949
 
14498
15950
  // 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";
15951
+ import { cpSync as cpSync2, existsSync as existsSync11, rmSync as rmSync4, writeFileSync as writeFileSync8 } from "fs";
15952
+ import { dirname as dirname12, isAbsolute as isAbsolute6, join as join13, parse as parse3, relative as relative8, resolve as resolve11, sep as sep2, win32 } from "path";
14501
15953
  init_patterns();
14502
15954
  var STATIC_CONCURRENCY = 4;
14503
15955
  var DYNAMIC_SEGMENT_RE2 = /\/:[^/]+|\/\*/;
14504
15956
  var TRAILING_SLASHES_RE = /\/+$/;
14505
15957
  var STATIC_RENDER_ORIGIN = "http://localhost";
14506
15958
  function pathToOutputFile(urlPath, outDir, fileName) {
14507
- const normalizedOutDir = resolve9(outDir);
15959
+ const normalizedOutDir = resolve11(outDir);
14508
15960
  if (urlPath === "/" || urlPath === "") {
14509
- return join12(normalizedOutDir, fileName);
15961
+ return join13(normalizedOutDir, fileName);
14510
15962
  }
14511
- const resolved = resolve9(normalizedOutDir, urlPath.slice(1), fileName);
15963
+ const resolved = resolve11(normalizedOutDir, urlPath.slice(1), fileName);
14512
15964
  if (!resolved.startsWith(`${normalizedOutDir}${sep2}`)) {
14513
15965
  throw new Error(`[furin] static: unsafe output path detected for URL "${urlPath}" \u2014 path traversal via ".." is not allowed.`);
14514
15966
  }
@@ -14581,22 +16033,22 @@ async function prerenderAndWrite(route, params, root, outDir, renderedRoutes, sk
14581
16033
  throw new Error(`[furin] static: route "${route.pattern}" returned a response that cannot be exported.`);
14582
16034
  }
14583
16035
  const staticLocation = resolveStaticRedirectLocation(location, basePath, urlPath);
14584
- ensureDir(dirname10(htmlOutputFile));
14585
- writeFileSync7(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
16036
+ ensureDir(dirname12(htmlOutputFile));
16037
+ writeFileSync8(htmlOutputFile, createStaticRedirectHtml(staticLocation.html));
14586
16038
  if (staticLocation.spa !== null) {
14587
16039
  const serializedRedirect = await toCrossJSONAsync({
14588
16040
  __furinRedirect: staticLocation.spa
14589
16041
  });
14590
- writeFileSync7(dataOutputFile, `${JSON.stringify(serializedRedirect)}
16042
+ writeFileSync8(dataOutputFile, `${JSON.stringify(serializedRedirect)}
14591
16043
  `);
14592
16044
  }
14593
16045
  renderedRoutes.push(urlPath);
14594
16046
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)} (redirects to ${staticLocation.html})`);
14595
16047
  return;
14596
16048
  }
14597
- ensureDir(dirname10(htmlOutputFile));
14598
- writeFileSync7(htmlOutputFile, entry.html);
14599
- writeFileSync7(dataOutputFile, entry.ndjson);
16049
+ ensureDir(dirname12(htmlOutputFile));
16050
+ writeFileSync8(htmlOutputFile, entry.html);
16051
+ writeFileSync8(dataOutputFile, entry.ndjson);
14600
16052
  renderedRoutes.push(urlPath);
14601
16053
  console.log(`[furin] static: ${urlPath} \u2192 ${toPosixPath(htmlOutputFile)}`);
14602
16054
  } catch (err) {
@@ -14703,15 +16155,15 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14703
16155
  throw new Error(`[furin] static: basePath must start with "/" (received "${rawBasePath}"). ` + `Use "" for root deployments or "/sub-path" for sub-path deployments.`);
14704
16156
  }
14705
16157
  const rawOutDir = staticConfig.outDir ?? "dist";
14706
- const outDir = resolve9(rootDir, rawOutDir);
14707
- const normalizedRoot = resolve9(rootDir);
14708
- const normalizedBuildRoot = resolve9(buildRoot);
16158
+ const outDir = resolve11(rootDir, rawOutDir);
16159
+ const normalizedRoot = resolve11(rootDir);
16160
+ const normalizedBuildRoot = resolve11(buildRoot);
14709
16161
  if (outDir === normalizedRoot || outDir === normalizedBuildRoot || outDir === parse3(outDir).root || rawOutDir === win32.parse(rawOutDir).root) {
14710
16162
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
14711
16163
  }
14712
16164
  function isOutsideOutDir(target) {
14713
16165
  const rel = relative8(outDir, target);
14714
- return rel.startsWith("..") || isAbsolute4(rel);
16166
+ return rel.startsWith("..") || isAbsolute6(rel);
14715
16167
  }
14716
16168
  if (!(isOutsideOutDir(normalizedRoot) && isOutsideOutDir(normalizedBuildRoot))) {
14717
16169
  throw new Error(`[furin] static: outDir resolves to "${outDir}" which is unsafe to delete. ` + `Use a dedicated output directory such as "dist".`);
@@ -14727,36 +16179,38 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14727
16179
  const afterQueueCount = skippedRoutes.length;
14728
16180
  rmSync4(outDir, { force: true, recursive: true });
14729
16181
  ensureDir(outDir);
14730
- const targetDir = join12(buildRoot, "static");
16182
+ const targetDir = join13(buildRoot, "static");
14731
16183
  rmSync4(targetDir, { force: true, recursive: true });
14732
16184
  ensureDir(targetDir);
14733
- const { entryChunk, cssChunks } = await buildClient(ssgRoutes, {
16185
+ const { entryChunk, cssChunks, preloadManifest } = await buildClient(ssgRoutes, {
14734
16186
  basePath,
14735
16187
  clientLogging: Boolean(options.clientLogging),
14736
- metafilePath: options.analyze ? join12(buildRoot, "analysis", "static-client.json") : undefined,
16188
+ metafilePath: options.analyze ? join13(buildRoot, "analysis", "static-client.json") : undefined,
14737
16189
  optimizeImports: options.optimizeImports,
14738
16190
  outDir: targetDir,
14739
- pagesDir: dirname10(root.path),
16191
+ pagesDir: dirname12(root.path),
14740
16192
  plugins: options.plugins,
16193
+ preloadRouteChunks: options.preload?.routeChunks,
14741
16194
  publicPath,
14742
16195
  reactCompiler: options.reactCompiler,
14743
16196
  rootLayout: root.path
14744
16197
  });
14745
- const publicFavicon = join12(rootDir, "public", "favicon.ico");
14746
- const faviconHref = existsSync10(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
16198
+ const publicFavicon = join13(rootDir, "public", "favicon.ico");
16199
+ const faviconHref = existsSync11(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
14747
16200
  const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref, true);
14748
16201
  setProductionTemplateContent(shellHtml);
14749
- const publicSrcDir = join12(rootDir, "public");
14750
- if (existsSync10(publicSrcDir)) {
16202
+ setProductionPreloadManifest(preloadManifest);
16203
+ const publicSrcDir = join13(rootDir, "public");
16204
+ if (existsSync11(publicSrcDir)) {
14751
16205
  cpSync2(publicSrcDir, outDir, { recursive: true });
14752
16206
  }
14753
- const clientSrcDir = join12(targetDir, "client");
14754
- if (existsSync10(clientSrcDir)) {
14755
- cpSync2(clientSrcDir, join12(outDir, "_client"), { recursive: true });
16207
+ const clientSrcDir = join13(targetDir, "client");
16208
+ if (existsSync11(clientSrcDir)) {
16209
+ cpSync2(clientSrcDir, join13(outDir, "_client"), { recursive: true });
14756
16210
  }
14757
16211
  await runWithConcurrency(tasks, STATIC_CONCURRENCY);
14758
16212
  assertNoPrerenderSkips(onSSR, skippedRoutes, afterQueueCount);
14759
- writeFileSync7(join12(outDir, "404.html"), shellHtml);
16213
+ writeFileSync8(join13(outDir, "404.html"), shellHtml);
14760
16214
  console.log("[furin] static: wrote 404.html (SPA shell fallback)");
14761
16215
  rmSync4(targetDir, { force: true, recursive: true });
14762
16216
  console.log(`[furin] static: export complete \u2192 ${toPosixPath(outDir)}` + ` (${renderedRoutes.length} rendered, ${skippedRoutes.length} skipped)`);
@@ -14770,9 +16224,9 @@ async function buildStaticTarget(routes, rootDir, buildRoot, root, options) {
14770
16224
  }
14771
16225
 
14772
16226
  // 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";
14775
- import { fileURLToPath as fileURLToPath6, pathToFileURL as pathToFileURL2 } from "url";
16227
+ import { cpSync as cpSync3, existsSync as existsSync12, readFileSync as readFileSync7, rmSync as rmSync5, symlinkSync, writeFileSync as writeFileSync9 } from "fs";
16228
+ import { basename as basename6, dirname as dirname13, extname as extname3, join as join14, relative as relative9 } from "path";
16229
+ import { fileURLToPath as fileURLToPath7, pathToFileURL as pathToFileURL2 } from "url";
14776
16230
  init_transform_isomorphic();
14777
16231
  init_patterns();
14778
16232
  var ISR_PATH_PARAM = "__furin_path";
@@ -14781,9 +16235,9 @@ var ELYSIA_STATIC_IMPORT_RE = /^@elysia\/static$/;
14781
16235
  var MATCH_ALL_RE = /.*/;
14782
16236
  var REGEX_META_RE = /[.*+?^${}()|[\]\\]/;
14783
16237
  var UNSAFE_FUNCTION_PATH_RE = /[^a-zA-Z0-9_.[\]/-]/g;
14784
- var VERCEL_FUNCTIONS_PATH = fileURLToPath6(import.meta.resolve("@vercel/functions"));
16238
+ var VERCEL_FUNCTIONS_PATH = fileURLToPath7(import.meta.resolve("@vercel/functions"));
14785
16239
  var VERCEL_RUNTIME_STUB_NAMESPACE = "furin-vercel-runtime-stub";
14786
- var FURIN_RUNTIME_ROOT2 = dirname11(import.meta.dir);
16240
+ var FURIN_RUNTIME_ROOT2 = dirname13(import.meta.dir);
14787
16241
  function isFurinRuntimeImporter(importer) {
14788
16242
  if (importer === "") {
14789
16243
  return false;
@@ -14814,8 +16268,8 @@ function vercelRuntimePlugin() {
14814
16268
  };
14815
16269
  }
14816
16270
  function frameworkVersion() {
14817
- const packageRoot = dirname11(dirname11(fileURLToPath6(import.meta.resolve("@teyik0/furin"))));
14818
- const packageJson = JSON.parse(readFileSync5(join13(packageRoot, "package.json"), "utf8"));
16271
+ const packageRoot = dirname13(dirname13(fileURLToPath7(import.meta.resolve("@teyik0/furin"))));
16272
+ const packageJson = JSON.parse(readFileSync7(join14(packageRoot, "package.json"), "utf8"));
14819
16273
  return packageJson.version;
14820
16274
  }
14821
16275
  function serverEntryLoader(serverEntry) {
@@ -14833,7 +16287,7 @@ function serverEntryLoader(serverEntry) {
14833
16287
  }
14834
16288
  function assertDefaultServerExport(serverEntry) {
14835
16289
  const transpiler = new Bun.Transpiler({ loader: serverEntryLoader(serverEntry) });
14836
- const { exports, imports } = transpiler.scan(readFileSync5(serverEntry, "utf8"));
16290
+ const { exports, imports } = transpiler.scan(readFileSync7(serverEntry, "utf8"));
14837
16291
  if (!exports.includes("default")) {
14838
16292
  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
16293
  }
@@ -14913,7 +16367,7 @@ function isPprRoute(app, route) {
14913
16367
  return resolveDocumentMode(route) !== "ssr" && (app.root.route.requestLoader !== undefined || hasRequestLoader(route));
14914
16368
  }
14915
16369
  async function addPrerenderFallback(spec, physicalRoutePath, prerender, functionsDir) {
14916
- const fallback = `${basename5(spec.functionName)}.prerender-fallback.html`;
16370
+ const fallback = `${basename6(spec.functionName)}.prerender-fallback.html`;
14917
16371
  const { result } = prerender;
14918
16372
  if (result === undefined) {
14919
16373
  return;
@@ -14931,9 +16385,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
14931
16385
  body = result.html;
14932
16386
  ({ status } = result);
14933
16387
  }
14934
- const fallbackPath = join13(dirname11(join13(functionsDir, spec.functionName)), fallback);
14935
- ensureDir(dirname11(fallbackPath));
14936
- writeFileSync8(fallbackPath, body);
16388
+ const fallbackPath = join14(dirname13(join14(functionsDir, spec.functionName)), fallback);
16389
+ ensureDir(dirname13(fallbackPath));
16390
+ writeFileSync9(fallbackPath, body);
14937
16391
  spec.config.fallback = fallback;
14938
16392
  spec.config.initialHeaders = {
14939
16393
  "content-type": contentType,
@@ -14944,9 +16398,9 @@ async function addPrerenderFallback(spec, physicalRoutePath, prerender, function
14944
16398
  spec.config.initialStatus = status;
14945
16399
  }
14946
16400
  function createFunctionAlias(functionsDir, serverFunctionDir, functionName) {
14947
- const aliasPath = join13(functionsDir, `${functionName}.func`);
14948
- ensureDir(dirname11(aliasPath));
14949
- const target = relative9(dirname11(aliasPath), serverFunctionDir);
16401
+ const aliasPath = join14(functionsDir, `${functionName}.func`);
16402
+ ensureDir(dirname13(aliasPath));
16403
+ const target = relative9(dirname13(aliasPath), serverFunctionDir);
14950
16404
  symlinkSync(target, aliasPath, process.platform === "win32" ? "junction" : "dir");
14951
16405
  }
14952
16406
  function createExactPrerenderSpec(prerender, routePath) {
@@ -15169,10 +16623,10 @@ async function buildPprFallbacks(apps, builds, specs, functionsDir, rootDir, tar
15169
16623
  if (jobs.length === 0) {
15170
16624
  return;
15171
16625
  }
15172
- const resultPath = join13(targetDir, "ppr-results.json");
16626
+ const resultPath = join14(targetDir, "ppr-results.json");
15173
16627
  const requests = jobs.map(({ path, spec }) => `http://localhost/${spec.functionName}?${ISR_PATH_PARAM}=${encodeURIComponent(path)}`);
15174
16628
  const script = `
15175
- const handler = (await import(${JSON.stringify(pathToFileURL2(join13(functionsDir, "__server.func/index.js")).href)})).default;
16629
+ const handler = (await import(${JSON.stringify(pathToFileURL2(join14(functionsDir, "__server.func/index.js")).href)})).default;
15176
16630
  const results = [];
15177
16631
  for (const url of ${JSON.stringify(requests)}) {
15178
16632
  const response = await handler.fetch(new Request(url));
@@ -15199,7 +16653,7 @@ process.exit(0);
15199
16653
  ${stderr}
15200
16654
  ${stdout}`);
15201
16655
  }
15202
- const results = JSON.parse(readFileSync5(resultPath, "utf8"));
16656
+ const results = JSON.parse(readFileSync7(resultPath, "utf8"));
15203
16657
  for (const [index, job] of jobs.entries()) {
15204
16658
  const result = results[index];
15205
16659
  await addPrerenderFallback(job.spec, job.path, {
@@ -15281,13 +16735,13 @@ export default { fetch: handle };
15281
16735
  }
15282
16736
  async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options) {
15283
16737
  assertDefaultServerExport(serverEntry);
15284
- const targetDir = join13(buildRoot, "vercel");
15285
- const outputDir = join13(rootDir, ".vercel", "output");
15286
- const staticDir = join13(outputDir, "static");
15287
- const functionsDir = join13(outputDir, "functions");
15288
- const serverFunctionDir = join13(functionsDir, "__server.func");
16738
+ const targetDir = join14(buildRoot, "vercel");
16739
+ const outputDir = join14(rootDir, ".vercel", "output");
16740
+ const staticDir = join14(outputDir, "static");
16741
+ const functionsDir = join14(outputDir, "functions");
16742
+ const serverFunctionDir = join14(functionsDir, "__server.func");
15289
16743
  rmSync5(targetDir, { force: true, recursive: true });
15290
- rmSync5(join13(buildRoot, "private", "server-sourcemaps", "vercel"), {
16744
+ rmSync5(join14(buildRoot, "private", "server-sourcemaps", "vercel"), {
15291
16745
  force: true,
15292
16746
  recursive: true
15293
16747
  });
@@ -15296,41 +16750,43 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15296
16750
  ensureDir(staticDir);
15297
16751
  ensureDir(serverFunctionDir);
15298
16752
  const { builds, headlineBuildId } = await buildRuntimeAppsSequentially(apps, rootDir, targetDir, serverEntry, options, "vercel");
15299
- cpSync3(join13(targetDir, "server-codec.js"), join13(serverFunctionDir, "server-codec.js"));
15300
- const publicDir = join13(rootDir, "public");
15301
- if (existsSync11(publicDir)) {
16753
+ cpSync3(join14(targetDir, "server-codec.js"), join14(serverFunctionDir, "server-codec.js"));
16754
+ const publicDir = join14(rootDir, "public");
16755
+ if (existsSync12(publicDir)) {
15302
16756
  cpSync3(publicDir, staticDir, { recursive: true });
15303
16757
  for (const app of apps) {
15304
- const appStaticDir = join13(staticDir, app.prefix.slice(1));
15305
- const appPublicDir = join13(appStaticDir, "public");
16758
+ const appStaticDir = join14(staticDir, app.prefix.slice(1));
16759
+ const appPublicDir = join14(appStaticDir, "public");
15306
16760
  cpSync3(publicDir, appPublicDir, { recursive: true });
15307
- const favicon = join13(publicDir, "favicon.ico");
15308
- if (app.prefix !== "" && existsSync11(favicon)) {
15309
- cpSync3(favicon, join13(appStaticDir, "favicon.ico"));
16761
+ const favicon = join14(publicDir, "favicon.ico");
16762
+ if (app.prefix !== "" && existsSync12(favicon)) {
16763
+ cpSync3(favicon, join14(appStaticDir, "favicon.ico"));
15310
16764
  }
15311
16765
  }
15312
16766
  }
15313
16767
  for (let appIndex = 0;appIndex < apps.length; appIndex += 1) {
15314
16768
  const app = apps[appIndex];
15315
16769
  const build = builds[appIndex];
15316
- const clientOutputDir = join13(staticDir, app.prefix.slice(1), "_client");
16770
+ const clientOutputDir = join14(staticDir, app.prefix.slice(1), "_client");
15317
16771
  cpSync3(build.clientDir, clientOutputDir, { recursive: true });
15318
16772
  }
15319
16773
  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
- });
15333
- const entryPath = join13(serverFunctionDir, "_vercel-handler.ts");
16774
+ const [prerenderSpecs, appEntry] = await Promise.all([
16775
+ createPrerenderSpecs(apps, builds, functionsDir, pprResumeKey),
16776
+ materializeServerAppEntry({
16777
+ apps: builds.map(({ entryApp, indexHtml }) => ({
16778
+ ...entryApp,
16779
+ embed: undefined,
16780
+ serveAssets: false,
16781
+ templateHtml: indexHtml
16782
+ })),
16783
+ headerComment: "// Auto-generated by `furin build --target vercel` \u2014 do not edit",
16784
+ instances: apps,
16785
+ outDir: serverFunctionDir,
16786
+ serverEntry
16787
+ })
16788
+ ]);
16789
+ const entryPath = join14(serverFunctionDir, "_vercel-handler.ts");
15334
16790
  const entry = createVirtualBuildEntry(entryPath, vercelEntrySource(apps, builds, prerenderSpecs, appEntry, pprResumeKey), "ts");
15335
16791
  const serverBuild = await runBunBuild({
15336
16792
  define: { "process.env.NODE_ENV": JSON.stringify("production") },
@@ -15358,22 +16814,22 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15358
16814
  target: "bun"
15359
16815
  });
15360
16816
  if (options.serverSourceMaps) {
15361
- movePrivateServerSourceMaps(serverFunctionDir, join13(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
16817
+ movePrivateServerSourceMaps(serverFunctionDir, join14(buildRoot, "private", "server-sourcemaps", "vercel"), serverBuild.outputs.filter((output) => output.kind === "sourcemap").map((output) => output.path));
15362
16818
  }
15363
16819
  if (options.analyze) {
15364
16820
  if (serverBuild.metafile === undefined) {
15365
16821
  throw new Error("[furin] Vercel server build did not produce the requested metafile.");
15366
16822
  }
15367
- const metafilePath = join13(buildRoot, "analysis", "vercel-server.json");
15368
- ensureDir(dirname11(metafilePath));
15369
- writeFileSync8(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
16823
+ const metafilePath = join14(buildRoot, "analysis", "vercel-server.json");
16824
+ ensureDir(dirname13(metafilePath));
16825
+ writeFileSync9(metafilePath, `${JSON.stringify(serverBuild.metafile, null, 2)}
15370
16826
  `);
15371
16827
  console.log(`[furin] Server metafile: ${toPosixPath(metafilePath)}`);
15372
16828
  }
15373
16829
  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));
16830
+ writeFileSync9(join14(serverFunctionDir, "index.js"), vercelBootstrapSource(serverBundleBytes));
15375
16831
  await buildPprFallbacks(apps, builds, prerenderSpecs, functionsDir, rootDir, targetDir);
15376
- writeFileSync8(join13(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
16832
+ writeFileSync9(join14(serverFunctionDir, ".vc-config.json"), `${JSON.stringify({
15377
16833
  handler: "index.js",
15378
16834
  launcherType: "Nodejs",
15379
16835
  ...options.vercelConfig?.regions === undefined ? {} : { regions: options.vercelConfig.regions },
@@ -15384,7 +16840,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15384
16840
  `);
15385
16841
  for (const spec of prerenderSpecs) {
15386
16842
  createFunctionAlias(functionsDir, serverFunctionDir, spec.functionName);
15387
- writeFileSync8(join13(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
16843
+ writeFileSync9(join14(functionsDir, `${spec.functionName}.prerender-config.json`), `${JSON.stringify(spec.config, null, 2)}
15388
16844
  `);
15389
16845
  }
15390
16846
  const assetRoutes = apps.map((app) => ({
@@ -15414,7 +16870,7 @@ async function buildVercelTarget(apps, rootDir, buildRoot, serverEntry, options)
15414
16870
  ],
15415
16871
  version: 3
15416
16872
  };
15417
- writeFileSync8(join13(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
16873
+ writeFileSync9(join14(outputDir, "config.json"), `${JSON.stringify(config, null, 2)}
15418
16874
  `);
15419
16875
  const ssgRoutes = builds.flatMap((build, index) => build.prerenders.filter((prerender) => resolveDocumentMode(prerender.route) === "ssg").map((prerender) => physicalPath(apps[index].prefix, prerender.path))).toSorted();
15420
16876
  const isrRoutes = apps.flatMap((app) => app.routes.filter((route) => resolveDocumentMode(route) === "isr").map((route) => physicalPath(app.prefix, route.pattern))).toSorted();
@@ -15467,6 +16923,7 @@ var configSchema = t.Object({
15467
16923
  clientLogging: t.Optional(t.Boolean()),
15468
16924
  optimizeImports: t.Optional(t.Array(t.String())),
15469
16925
  pagesDir: t.Optional(t.String()),
16926
+ preload: t.Optional(t.Object({ routeChunks: t.Optional(t.Boolean()) })),
15470
16927
  reactCompiler: t.Optional(t.Boolean()),
15471
16928
  rootDir: t.Optional(t.String()),
15472
16929
  serverEntry: t.Optional(t.String()),
@@ -15490,9 +16947,9 @@ init_transform_isomorphic();
15490
16947
  init_instance();
15491
16948
 
15492
16949
  // src/server/router/discovery.ts
15493
- import { existsSync as existsSync12 } from "fs";
16950
+ import { existsSync as existsSync13 } from "fs";
15494
16951
  import { readdir } from "fs/promises";
15495
- import { join as join14, parse as parse4 } from "path";
16952
+ import { join as join15, parse as parse4 } from "path";
15496
16953
 
15497
16954
  // src/server/internal.ts
15498
16955
  var _compileContexts = new Map;
@@ -15591,6 +17048,7 @@ function adaptDefinedPage(route, parent) {
15591
17048
  params: route.schemas?.params,
15592
17049
  parent,
15593
17050
  query: route.schemas?.query,
17051
+ remountDeps: route.remountDeps,
15594
17052
  requestLoader: route.requestLoader
15595
17053
  },
15596
17054
  component,
@@ -15644,7 +17102,7 @@ async function scanPages(pagesDir) {
15644
17102
  async function scanRootLayout(pagesDir) {
15645
17103
  const rootPath = `${pagesDir}/root.tsx`;
15646
17104
  const ctx = getCompileContext();
15647
- if (!(existsSync12(rootPath) || ctx?.modules[rootPath])) {
17105
+ if (!(existsSync13(rootPath) || ctx?.modules[rootPath])) {
15648
17106
  throw new Error("[furin] root.tsx: not found.");
15649
17107
  }
15650
17108
  const mod = ctx?.modules[rootPath] ?? await import(rootPath);
@@ -15671,10 +17129,6 @@ async function scanRootLayout(pagesDir) {
15671
17129
  }
15672
17130
  var CONVENTION_FILE_NAMES = ["not-found", "error"];
15673
17131
  var SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
15674
- var DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
15675
- function routePatternKey(pattern) {
15676
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
15677
- }
15678
17132
  function isConventionFileName(name) {
15679
17133
  return CONVENTION_FILE_NAMES.includes(name);
15680
17134
  }
@@ -15684,8 +17138,8 @@ function getSourceModuleCandidates(dir, name) {
15684
17138
  async function loadConventionComponent(dir, name) {
15685
17139
  const ctx = getCompileContext();
15686
17140
  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;
17141
+ if (existsSync13(filePath) || ctx?.modules[filePath]) {
17142
+ const moduleSpecifier = IS_DEV && existsSync13(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15689
17143
  const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15690
17144
  if (mod.default) {
15691
17145
  return { component: mod.default, path: filePath };
@@ -15723,7 +17177,7 @@ async function scanPageFiles(pagesDir, root) {
15723
17177
  const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
15724
17178
  devRoute.notFound = notFound;
15725
17179
  devRoute.error = errorComponent;
15726
- devRoute.segmentBoundaries = segmentBoundaries;
17180
+ devRoute.segmentBoundaries = alignSegmentBoundaryDepths(segmentBoundaries, devRoute.routeChain);
15727
17181
  routes.push(devRoute);
15728
17182
  continue;
15729
17183
  }
@@ -15743,7 +17197,7 @@ async function scanPageFiles(pagesDir, root) {
15743
17197
  path: absolutePath,
15744
17198
  pattern,
15745
17199
  routeChain,
15746
- segmentBoundaries,
17200
+ segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
15747
17201
  tags: collectRouteTags(routeChain, page)
15748
17202
  });
15749
17203
  }
@@ -15768,7 +17222,7 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15768
17222
  for (const segment of segments) {
15769
17223
  directory = `${directory}/${segment}`;
15770
17224
  for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15771
- if (!existsSync12(candidate)) {
17225
+ if (!existsSync13(candidate)) {
15772
17226
  continue;
15773
17227
  }
15774
17228
  const layoutModule = await (IS_DEV ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
@@ -15781,6 +17235,21 @@ async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15781
17235
  }
15782
17236
  return parent;
15783
17237
  }
17238
+ function alignSegmentBoundaryDepths(boundaries, routeChain) {
17239
+ return boundaries.map((boundary) => {
17240
+ let depth = 0;
17241
+ for (const [index, entry] of routeChain.entries()) {
17242
+ if (!entry.sourcePath) {
17243
+ continue;
17244
+ }
17245
+ const directory = entry.sourcePath.slice(0, entry.sourcePath.lastIndexOf("/"));
17246
+ if (boundary.path === directory || boundary.path.startsWith(`${directory}/`)) {
17247
+ depth = index;
17248
+ }
17249
+ }
17250
+ return { ...boundary, depth };
17251
+ });
17252
+ }
15784
17253
  async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
15785
17254
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
15786
17255
  const dirs = [pagesDir];
@@ -15868,7 +17337,7 @@ async function collectPageFilePaths(dir) {
15868
17337
  const files = [];
15869
17338
  const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
15870
17339
  const resolved = await mapWithConcurrency(entries, DIR_SCAN_CONCURRENCY, async (entry) => {
15871
- const absolutePath = toPosixPath2(join14(dir, entry.name));
17340
+ const absolutePath = toPosixPath2(join15(dir, entry.name));
15872
17341
  if (entry.isDirectory()) {
15873
17342
  return await collectPageFilePaths(absolutePath);
15874
17343
  }
@@ -15888,9 +17357,9 @@ init_instance();
15888
17357
  init_lang_detect();
15889
17358
  init_ast_walk();
15890
17359
  init_parser();
15891
- import { readFileSync as readFileSync6 } from "fs";
17360
+ import { readFileSync as readFileSync8 } from "fs";
15892
17361
  function scanFurinInstances(serverEntryPath) {
15893
- const code = readFileSync6(serverEntryPath, "utf8");
17362
+ const code = readFileSync8(serverEntryPath, "utf8");
15894
17363
  const lang = detectLangFromPath(serverEntryPath);
15895
17364
  if (lang === "dts") {
15896
17365
  return [];
@@ -15971,42 +17440,42 @@ function registerIsomorphicRuntimePlugin() {
15971
17440
  function resolveAppSpecs(options, serverEntry, rootDir) {
15972
17441
  if (options.apps && options.apps.length > 0) {
15973
17442
  return options.apps.map((app) => ({
15974
- pagesDir: resolve10(rootDir, app.pagesDir),
17443
+ pagesDir: resolve12(rootDir, app.pagesDir),
15975
17444
  prefix: normalizePrefix(app.prefix)
15976
17445
  }));
15977
17446
  }
15978
17447
  if (options.pagesDir) {
15979
- return [{ pagesDir: resolve10(rootDir, options.pagesDir), prefix: "" }];
17448
+ return [{ pagesDir: resolve12(rootDir, options.pagesDir), prefix: "" }];
15980
17449
  }
15981
17450
  if (serverEntry) {
15982
17451
  const detected = scanFurinInstances(serverEntry);
15983
17452
  if (detected.length > 0) {
15984
17453
  return detected.map((app) => ({
15985
- pagesDir: resolve10(rootDir, app.pagesDir),
17454
+ pagesDir: resolve12(rootDir, app.pagesDir),
15986
17455
  prefix: app.prefix
15987
17456
  }));
15988
17457
  }
15989
17458
  }
15990
- return [{ pagesDir: resolve10(rootDir, "src/pages"), prefix: "" }];
17459
+ return [{ pagesDir: resolve12(rootDir, "src/pages"), prefix: "" }];
15991
17460
  }
15992
17461
  async function buildApp(options) {
15993
17462
  return withProductionBuild(() => buildAppInternal(options));
15994
17463
  }
15995
17464
  async function buildAppInternal(options) {
15996
- const rootDir = resolve10(options.rootDir ?? process.cwd());
15997
- const buildRoot = join15(rootDir, BUILD_OUTPUT_DIR);
17465
+ const rootDir = resolve12(options.rootDir ?? process.cwd());
17466
+ const buildRoot = join16(rootDir, BUILD_OUTPUT_DIR);
15998
17467
  const serverEntry = (() => {
15999
17468
  if (options.target === "static" || options.target === "package") {
16000
17469
  return null;
16001
17470
  }
16002
17471
  if (options.serverEntry) {
16003
- const resolved = resolve10(rootDir, options.serverEntry);
16004
- if (existsSync13(resolved)) {
17472
+ const resolved = resolve12(rootDir, options.serverEntry);
17473
+ if (existsSync14(resolved)) {
16005
17474
  return resolved;
16006
17475
  }
16007
17476
  }
16008
- const entry = resolve10(rootDir, "src/server.ts");
16009
- if (!existsSync13(entry)) {
17477
+ const entry = resolve12(rootDir, "src/server.ts");
17478
+ if (!existsSync14(entry)) {
16010
17479
  throw new Error("[furin] Entrypoint server.ts not found");
16011
17480
  }
16012
17481
  return entry;
@@ -16087,7 +17556,7 @@ async function buildAppInternal(options) {
16087
17556
  throw new Error(`[furin] Unsupported build target "${target}"`);
16088
17557
  }
16089
17558
  }
16090
- writeFileSync9(join15(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
17559
+ writeFileSync10(join16(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
16091
17560
  `);
16092
17561
  return {
16093
17562
  manifest,
@@ -16099,8 +17568,8 @@ async function buildAppInternal(options) {
16099
17568
  init_instance();
16100
17569
 
16101
17570
  // src/cli/config.ts
16102
- import { existsSync as existsSync14 } from "fs";
16103
- import { resolve as resolve11 } from "path";
17571
+ import { existsSync as existsSync15 } from "fs";
17572
+ import { resolve as resolve13 } from "path";
16104
17573
  import { pathToFileURL as pathToFileURL3 } from "url";
16105
17574
  import { Validator as Validator2 } from "elysia";
16106
17575
  var compiledConfigSchema = Validator2.create(configSchema);
@@ -16110,8 +17579,8 @@ var DEFAULT_CONFIG_FILENAMES = [
16110
17579
  "furin.config.mjs"
16111
17580
  ];
16112
17581
  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));
17582
+ const rootDir = resolve13(cwd);
17583
+ const configPath = explicitConfigPath ? resolve13(rootDir, explicitConfigPath) : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve13(rootDir, filename)).find((path) => existsSync15(path));
16115
17584
  if (!configPath) {
16116
17585
  return {
16117
17586
  configPath: null,
@@ -16128,19 +17597,19 @@ async function loadCliConfig(cwd, explicitConfigPath) {
16128
17597
  const [firstError] = compiledConfigSchema.Errors(configToValidate);
16129
17598
  throw new Error(`[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.instancePath ?? "/"})`);
16130
17599
  }
16131
- const resolvedRootDir = resolve11(rootDir, configToValidate.rootDir ?? ".");
17600
+ const resolvedRootDir = resolve13(rootDir, configToValidate.rootDir ?? ".");
16132
17601
  return {
16133
17602
  ...configToValidate,
16134
17603
  configPath,
16135
- pagesDir: configToValidate.pagesDir ? resolve11(resolvedRootDir, configToValidate.pagesDir) : undefined,
17604
+ pagesDir: configToValidate.pagesDir ? resolve13(resolvedRootDir, configToValidate.pagesDir) : undefined,
16136
17605
  plugins,
16137
17606
  rootDir: resolvedRootDir
16138
17607
  };
16139
17608
  }
16140
17609
 
16141
17610
  // 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";
17611
+ import { existsSync as existsSync16 } from "fs";
17612
+ import { isAbsolute as isAbsolute7, join as join17, relative as relative11, resolve as resolve14 } from "path";
16144
17613
  var LEADING_SLASHES_RE = /^\/+/;
16145
17614
  var TRAILING_SLASHES_RE2 = /\/+$/;
16146
17615
  function normalizeStaticPreviewBasePath(basePath) {
@@ -16158,15 +17627,15 @@ function startStaticPreview({
16158
17627
  port
16159
17628
  }) {
16160
17629
  const basePath = normalizeStaticPreviewBasePath(rawBasePath);
16161
- const distDir = resolve12(rawDistDir);
16162
- const indexPath = join16(distDir, "index.html");
16163
- const notFoundPath = join16(distDir, "404.html");
16164
- const faviconPath = join16(distDir, "favicon.ico");
16165
- if (!(existsSync15(indexPath) && existsSync15(notFoundPath))) {
17630
+ const distDir = resolve14(rawDistDir);
17631
+ const indexPath = join17(distDir, "index.html");
17632
+ const notFoundPath = join17(distDir, "404.html");
17633
+ const faviconPath = join17(distDir, "favicon.ico");
17634
+ if (!(existsSync16(indexPath) && existsSync16(notFoundPath))) {
16166
17635
  throw new Error(`[furin] preview: "${distDir}" is not a Furin static export. Run \`furin build --target static\` first.`);
16167
17636
  }
16168
17637
  const notFound = () => new Response(Bun.file(notFoundPath), { status: 404 });
16169
- const clientDir = join16(distDir, "_client");
17638
+ const clientDir = join17(distDir, "_client");
16170
17639
  const fetchStaticFile = async (request) => {
16171
17640
  const encodedPathname = new URL(request.url).pathname;
16172
17641
  let pathname;
@@ -16179,16 +17648,16 @@ function startStaticPreview({
16179
17648
  return notFound();
16180
17649
  }
16181
17650
  const logicalPath = pathname.slice(basePath.length).replace(LEADING_SLASHES_RE, "");
16182
- const exactPath = resolve12(distDir, logicalPath);
17651
+ const exactPath = resolve14(distDir, logicalPath);
16183
17652
  const relativePath = relative11(distDir, exactPath);
16184
- if (relativePath.startsWith("..") || isAbsolute5(relativePath)) {
17653
+ if (relativePath.startsWith("..") || isAbsolute7(relativePath)) {
16185
17654
  return notFound();
16186
17655
  }
16187
17656
  const exactFile = Bun.file(exactPath);
16188
17657
  if (!pathname.endsWith("/") && await exactFile.exists()) {
16189
17658
  return new Response(exactFile);
16190
17659
  }
16191
- const indexFile = Bun.file(join16(exactPath, "index.html"));
17660
+ const indexFile = Bun.file(join17(exactPath, "index.html"));
16192
17661
  if (await indexFile.exists()) {
16193
17662
  return new Response(indexFile);
16194
17663
  }
@@ -16204,7 +17673,7 @@ function startStaticPreview({
16204
17673
  routes: {
16205
17674
  ...entryRoutes,
16206
17675
  [`${basePath}/_client/*`]: { dir: clientDir },
16207
- "/favicon.ico": existsSync15(faviconPath) ? Bun.file(faviconPath) : notFound()
17676
+ "/favicon.ico": existsSync16(faviconPath) ? Bun.file(faviconPath) : notFound()
16208
17677
  }
16209
17678
  });
16210
17679
  }
@@ -16282,7 +17751,7 @@ if (command === "preview") {
16282
17751
  if (values.port !== undefined && !/^\d+$/.test(values.port) || !(Number.isInteger(port) && port >= 0 && port <= 65535)) {
16283
17752
  bail(`Invalid preview port "${values.port}". Expected an integer between 0 and 65535.`);
16284
17753
  }
16285
- const distDir = resolve13(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
17754
+ const distDir = resolve15(config.rootDir, values.dir ?? config.static?.outDir ?? "dist");
16286
17755
  const basePath = normalizeStaticPreviewBasePath(values.basePath ?? config.static?.basePath ?? "");
16287
17756
  const server = startStaticPreview({ basePath, distDir, port });
16288
17757
  log("Static preview ready");
@@ -16317,8 +17786,8 @@ if (command === "preview") {
16317
17786
  const config = await loadCliConfig(process.cwd(), values.config);
16318
17787
  const isServerlessTarget = target === "static" || target === "package";
16319
17788
  const resolvedServerEntry = isServerlessTarget ? undefined : (() => {
16320
- const entry = resolve13(config.rootDir, config.serverEntry ?? "src/server.ts");
16321
- if (!existsSync16(entry)) {
17789
+ const entry = resolve15(config.rootDir, config.serverEntry ?? "src/server.ts");
17790
+ if (!existsSync17(entry)) {
16322
17791
  const expected = config.serverEntry ?? "src/server.ts";
16323
17792
  throw new Error(`[furin] Entrypoint ${expected} not found`);
16324
17793
  }
@@ -16338,6 +17807,7 @@ if (command === "preview") {
16338
17807
  optimizeImports: config.optimizeImports,
16339
17808
  pagesDir: undefined,
16340
17809
  plugins: config.plugins,
17810
+ preload: config.preload,
16341
17811
  reactCompiler: config.reactCompiler,
16342
17812
  rootDir: config.rootDir,
16343
17813
  serverEntry: resolvedServerEntry,