@teyik0/furin 0.9.0-alpha.1 → 0.9.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 (85) hide show
  1. package/dist/adapter/runtime-build.d.ts +7 -3
  2. package/dist/adapter/vercel.js +31 -6
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/entry-template.d.ts +3 -12
  5. package/dist/build/entry-template.ts +3 -15
  6. package/dist/build/hydrate.d.ts +6 -1
  7. package/dist/build/index.d.ts +1 -1
  8. package/dist/build/index.js +565 -401
  9. package/dist/build/route-metadata.d.ts +2 -2
  10. package/dist/build/route-types.d.ts +1 -1
  11. package/dist/build/types.d.ts +10 -4
  12. package/dist/cli/index.js +594 -422
  13. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  14. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  15. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  16. package/dist/client/define-route.d.ts +14 -0
  17. package/dist/client/internal/runtime-types.d.ts +8 -0
  18. package/dist/client/link.js +3 -3
  19. package/dist/client/router/link-utils.d.ts +3 -2
  20. package/dist/client/router/search/index.js +2 -2
  21. package/dist/client/router/types.d.ts +9 -3
  22. package/dist/client.js +22 -6
  23. package/dist/config.d.ts +4 -0
  24. package/dist/config.js +4 -1
  25. package/dist/define-route.d.ts +53 -12
  26. package/dist/furin.d.ts +13 -3
  27. package/dist/furin.js +766 -614
  28. package/dist/plugin/route-config.d.ts +3 -3
  29. package/dist/plugin/route-manifest.d.ts +46 -0
  30. package/dist/plugin/route-tree.d.ts +13 -29
  31. package/dist/routes.d.ts +2 -2
  32. package/dist/server/dev/runtime.d.ts +2 -1
  33. package/dist/server/internal.d.ts +6 -0
  34. package/dist/server/internal.js +57 -76
  35. package/dist/server/registrations.d.ts +4 -2
  36. package/dist/server/router/defined-route.d.ts +4 -0
  37. package/dist/server/router/discovery.d.ts +14 -4
  38. package/dist/server/router/hmr.d.ts +12 -12
  39. package/dist/server/router/patterns.d.ts +4 -12
  40. package/dist/server/router/types.d.ts +16 -1
  41. package/dist/server/static-export.js +88 -120
  42. package/dist/server/sync/drizzle/index.d.ts +8 -10
  43. package/dist/shared/route-specificity.d.ts +10 -1
  44. package/package.json +3 -6
  45. package/src/adapter/package.ts +11 -37
  46. package/src/adapter/runtime-build.ts +5 -4
  47. package/src/adapter/static.ts +1 -1
  48. package/src/adapter/vercel.ts +2 -1
  49. package/src/build/client.ts +3 -3
  50. package/src/build/discover-pages-process.ts +1 -1
  51. package/src/build/elysia-aot.ts +2 -2
  52. package/src/build/entry-template.ts +3 -15
  53. package/src/build/hydrate.ts +12 -6
  54. package/src/build/index.ts +19 -9
  55. package/src/build/route-metadata.ts +15 -8
  56. package/src/build/route-types.ts +18 -43
  57. package/src/build/types.ts +12 -5
  58. package/src/cli/config.ts +6 -0
  59. package/src/cli/index.ts +30 -14
  60. package/src/client/define-route.ts +29 -4
  61. package/src/client/internal/runtime-types.ts +8 -0
  62. package/src/client/router/link-utils.ts +16 -8
  63. package/src/client/router/types.ts +40 -14
  64. package/src/config.ts +5 -0
  65. package/src/define-route.ts +85 -16
  66. package/src/furin.ts +31 -7
  67. package/src/plugin/dev-routes.ts +8 -17
  68. package/src/plugin/route-config.ts +77 -62
  69. package/src/plugin/route-manifest.ts +437 -0
  70. package/src/plugin/route-modules.ts +6 -1
  71. package/src/plugin/route-registry.ts +7 -21
  72. package/src/plugin/route-tree.ts +71 -181
  73. package/src/routes.ts +2 -2
  74. package/src/server/dev/runtime.ts +16 -22
  75. package/src/server/internal.ts +4 -1
  76. package/src/server/registrations.ts +5 -2
  77. package/src/server/render/static-params.ts +2 -10
  78. package/src/server/router/defined-route.ts +8 -0
  79. package/src/server/router/discovery.ts +237 -196
  80. package/src/server/router/hmr.ts +45 -63
  81. package/src/server/router/patterns.ts +41 -117
  82. package/src/server/router/types.ts +17 -1
  83. package/src/server/sync/drizzle/index.ts +18 -19
  84. package/src/shared/route-specificity.ts +34 -2
  85. package/src/shared/utils/index.ts +1 -1
package/dist/furin.js CHANGED
@@ -58,7 +58,7 @@ function segmentSpecificity(segment) {
58
58
  }
59
59
  return segment.startsWith(":") ? 2 : 3;
60
60
  }
61
- function compareRouteSpecificity(a, b) {
61
+ function compareConcreteSpecificity(a, b) {
62
62
  const aSegments = a.split("/").filter(Boolean);
63
63
  const bSegments = b.split("/").filter(Boolean);
64
64
  const length = Math.max(aSegments.length, bSegments.length);
@@ -78,6 +78,24 @@ function compareRouteSpecificity(a, b) {
78
78
  }
79
79
  return 0;
80
80
  }
81
+ function expandOptionalSegments(pattern) {
82
+ let variants = [[]];
83
+ for (const segment of pattern.split("/").filter(Boolean)) {
84
+ if (segment.startsWith(":") && segment.endsWith("?")) {
85
+ const required = segment.slice(0, -1);
86
+ variants = variants.flatMap((variant) => [variant, [...variant, required]]);
87
+ } else {
88
+ variants = variants.map((variant) => [...variant, segment]);
89
+ }
90
+ }
91
+ return variants.map((variant) => `/${variant.join("/")}`);
92
+ }
93
+ function mostSpecificVariant(pattern) {
94
+ return expandOptionalSegments(pattern).reduce((best, variant) => compareConcreteSpecificity(variant, best) > 0 ? variant : best);
95
+ }
96
+ function compareRouteSpecificity(a, b) {
97
+ return compareConcreteSpecificity(mostSpecificVariant(a), mostSpecificVariant(b));
98
+ }
81
99
 
82
100
  // src/shared/search-params.ts
83
101
  function isObject(value) {
@@ -188,18 +206,6 @@ function findSearchDefaultsForRouteTarget(to, routes) {
188
206
  var init_search_params = () => {};
189
207
 
190
208
  // src/server/router/patterns.ts
191
- import { parse } from "path";
192
- function collectIntermediateLayoutDirs(pagePath, rootPath) {
193
- const pageDir = pagePath.slice(0, pagePath.lastIndexOf("/"));
194
- const pagesDir = rootPath.slice(0, rootPath.lastIndexOf("/"));
195
- const layoutDirs = [];
196
- let dir = pageDir;
197
- while (dir.length > pagesDir.length) {
198
- layoutDirs.unshift(dir);
199
- dir = dir.slice(0, dir.lastIndexOf("/"));
200
- }
201
- return layoutDirs;
202
- }
203
209
  function resolveRouteRevalidate(page) {
204
210
  return page.revalidate ?? page._route.revalidate;
205
211
  }
@@ -239,57 +245,6 @@ function resolveMode(page, routeChain) {
239
245
  }
240
246
  return "ssr";
241
247
  }
242
- function parseDynamicRouteSegment(segment, sourcePath) {
243
- if (!(segment.startsWith("[") && segment.endsWith("]"))) {
244
- return;
245
- }
246
- const inner = segment.slice(1, -1);
247
- const catchAll = inner.startsWith("...");
248
- const name = catchAll ? inner.slice(3) : inner;
249
- if (!DYNAMIC_PARAMETER_NAME_RE.test(name)) {
250
- throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(name)} in ${JSON.stringify(sourcePath ?? segment)}. Parameter names must match ${DYNAMIC_PARAMETER_NAME_RE}.`);
251
- }
252
- return { catchAll, name };
253
- }
254
- function routeSegmentToPattern(segment) {
255
- const dynamic = parseDynamicRouteSegment(segment, undefined);
256
- if (!dynamic) {
257
- return segment;
258
- }
259
- return dynamic.catchAll ? "*" : `:${dynamic.name}`;
260
- }
261
- function isRouteGroup(segment) {
262
- return ROUTE_GROUP_RE.test(segment);
263
- }
264
- function routePatternKey(pattern) {
265
- return pattern.replace(DYNAMIC_ROUTE_SEGMENT_RE, "$1:param");
266
- }
267
- function filePathToPattern(path) {
268
- const parts = path.replaceAll("\\", "/").split("/");
269
- const segments = [];
270
- const lastIndex = parts.length - 1;
271
- for (let idx = 0;idx < parts.length; idx += 1) {
272
- const part = parts[idx];
273
- if (part === undefined || part.length === 0) {
274
- continue;
275
- }
276
- const isFile = idx === lastIndex;
277
- const name = isFile ? parse(part).name : part;
278
- if (!isFile && isRouteGroup(name)) {
279
- continue;
280
- }
281
- if (isFile && name === "index") {
282
- continue;
283
- }
284
- const dynamic = parseDynamicRouteSegment(name, path);
285
- if (dynamic) {
286
- segments.push(dynamic.catchAll ? "*" : `:${dynamic.name}`);
287
- } else {
288
- segments.push(name);
289
- }
290
- }
291
- return `/${segments.join("/")}`;
292
- }
293
248
  function escapeRegExp(value) {
294
249
  return value.replace(REGEX_META_CHARS_RE, "\\$&");
295
250
  }
@@ -304,11 +259,17 @@ function routePatternRegexSource(pattern, sources) {
304
259
  while (i < pattern.length && pattern[i] !== "/") {
305
260
  i += 1;
306
261
  }
307
- paramNames.push(pattern.slice(start, i));
308
- source += sources.param;
262
+ const name = pattern.slice(start, i);
263
+ if (name.endsWith("?") && source.endsWith("/")) {
264
+ paramNames.push(name.slice(0, -1));
265
+ source = `${source.slice(0, -1)}(?:/${sources.param})?`;
266
+ } else {
267
+ paramNames.push(name);
268
+ source += sources.param;
269
+ }
309
270
  } else if (pattern[i] === "*") {
310
- paramNames.push("*");
311
- source += sources.catchAll;
271
+ paramNames.push(SPLAT_PARAM);
272
+ source = source.endsWith("/") ? `${source.slice(0, -1)}(?:/${sources.catchAll})?` : source + sources.catchAll;
312
273
  i += 1;
313
274
  } else {
314
275
  const ch = pattern[i];
@@ -330,6 +291,25 @@ function buildRouteRegex(pattern) {
330
291
  regex: new RegExp(`^${source}${pattern === "/" || pattern.endsWith("/") ? "" : "/?"}$`)
331
292
  };
332
293
  }
294
+ function decodeParam(value) {
295
+ try {
296
+ return decodeURIComponent(value);
297
+ } catch {
298
+ return value;
299
+ }
300
+ }
301
+ function matchedParams(paramNames, match) {
302
+ const params = {};
303
+ for (const [index, name] of paramNames.entries()) {
304
+ const value = match[index + 1];
305
+ if (value !== undefined) {
306
+ params[name] = decodeParam(value);
307
+ } else if (name === SPLAT_PARAM) {
308
+ params[name] = "";
309
+ }
310
+ }
311
+ return params;
312
+ }
333
313
  function buildRouteMatcher(routes) {
334
314
  const compiled = routes.map((route) => {
335
315
  const { regex, paramNames } = buildRouteRegex(route.pattern);
@@ -341,27 +321,13 @@ function buildRouteMatcher(routes) {
341
321
  if (!match) {
342
322
  continue;
343
323
  }
344
- const params = {};
345
- for (let i = 0;i < candidate.paramNames.length; i += 1) {
346
- const name = candidate.paramNames[i];
347
- if (name !== undefined) {
348
- try {
349
- params[name] = decodeURIComponent(match[i + 1] ?? "");
350
- } catch {
351
- params[name] = match[i + 1] ?? "";
352
- }
353
- }
354
- }
355
- return { params, route: candidate.route };
324
+ return { params: matchedParams(candidate.paramNames, match), route: candidate.route };
356
325
  }
357
326
  return null;
358
327
  };
359
328
  }
360
- var DYNAMIC_PARAMETER_NAME_RE, ROUTE_GROUP_RE, DYNAMIC_ROUTE_SEGMENT_RE, REGEX_META_CHARS_RE;
329
+ var SPLAT_PARAM = "_splat", REGEX_META_CHARS_RE;
361
330
  var init_patterns = __esm(() => {
362
- DYNAMIC_PARAMETER_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
363
- ROUTE_GROUP_RE = /^\([^()]+\)$/;
364
- DYNAMIC_ROUTE_SEGMENT_RE = /(^|\/):[^/]+/g;
365
331
  REGEX_META_CHARS_RE = /[.*+?^${}()|[\]\\]/g;
366
332
  });
367
333
 
@@ -654,14 +620,20 @@ function routeHandler(route) {
654
620
  return renderer(context, route);
655
621
  };
656
622
  }
623
+ function renameSplatParam(context) {
624
+ if (context.params !== undefined && "*" in context.params) {
625
+ const { "*": splat, ...params } = context.params;
626
+ context.params = { ...params, _splat: splat };
627
+ }
628
+ }
657
629
  function registerPlain(route) {
658
- return new Elysia().get("", routeHandler(route));
630
+ return new Elysia().get("", { transform: renameSplatParam }, routeHandler(route));
659
631
  }
660
632
  function registerSchema(route, paramsSchema, querySchema) {
661
- return new Elysia().get("", { params: paramsSchema, query: querySchema }, routeHandler(route));
633
+ return new Elysia().get("", { params: paramsSchema, query: querySchema, transform: renameSplatParam }, routeHandler(route));
662
634
  }
663
635
  function registerQuery(route, querySchema) {
664
- return new Elysia().get("", { query: querySchema }, routeHandler(route));
636
+ return new Elysia().get("", { query: querySchema, transform: renameSplatParam }, routeHandler(route));
665
637
  }
666
638
  function schemaValues(value) {
667
639
  return value !== null && typeof value === "object" ? value : {};
@@ -738,9 +710,20 @@ function schemaFields(paramsSchema, querySchema) {
738
710
  return querySchema === undefined ? {} : { schemas: { query: querySchema } };
739
711
  }
740
712
  function terminalFields(runtime) {
741
- const { head, loader, metadata, paramsSchema, querySchema, requestLoader } = runtime;
713
+ const {
714
+ errorComponent,
715
+ head,
716
+ loader,
717
+ metadata,
718
+ notFoundComponent,
719
+ paramsSchema,
720
+ querySchema,
721
+ requestLoader
722
+ } = runtime;
742
723
  return {
743
724
  __type: "FURIN_ROUTE",
725
+ errorComponent,
726
+ notFoundComponent,
744
727
  mode: metadata.mode,
745
728
  revalidate: metadata.revalidate,
746
729
  remountDeps: metadata.remountDeps,
@@ -758,6 +741,12 @@ class RouteChain {
758
741
  constructor(runtime) {
759
742
  this.runtime = runtime;
760
743
  }
744
+ error(component) {
745
+ return new RouteChain({ ...this.runtime, errorComponent: component });
746
+ }
747
+ notFound(component) {
748
+ return new RouteChain({ ...this.runtime, notFoundComponent: component });
749
+ }
761
750
  requestLoader(requestLoader) {
762
751
  return new RouteChain({
763
752
  ...this.runtime,
@@ -805,9 +794,11 @@ class RouteChain {
805
794
  function configure(options) {
806
795
  assertStaticParamsOutsideConfig(options);
807
796
  return new RouteChain({
797
+ errorComponent: undefined,
808
798
  head: undefined,
809
799
  loader: undefined,
810
800
  metadata: options,
801
+ notFoundComponent: undefined,
811
802
  paramsSchema: options.params,
812
803
  querySchema: options.query,
813
804
  requestLoader: undefined
@@ -4903,11 +4894,12 @@ function navigationHrefPolicy(href, currentOrigin) {
4903
4894
  return url.origin === currentOrigin ? "internal" : "external";
4904
4895
  }
4905
4896
  function applyLinkParams(to, params) {
4906
- if (!params) {
4907
- return to;
4897
+ const values = params ?? {};
4898
+ let url = to.replaceAll(/\/:([a-zA-Z0-9_]+)\?(?=\/|$)/g, (_match, name) => values[name] === undefined || values[name] === "" ? "" : `/${encodeURIComponent(String(values[name]))}`).replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in values) ? encodeURIComponent(String(values[name])) : match);
4899
+ if (url === "") {
4900
+ url = "/";
4908
4901
  }
4909
- let url = to.replaceAll(/:([a-zA-Z0-9_]+)/g, (match, name) => (name in params) ? encodeURIComponent(String(params[name])) : match);
4910
- const wildcard = params["*"];
4902
+ const wildcard = values._splat;
4911
4903
  if (wildcard !== undefined && url.includes("/*")) {
4912
4904
  const encodedWildcard = String(wildcard).split("/").map(encodeURIComponent).join("/");
4913
4905
  url = url.replace("/*", () => `/${encodedWildcard}`);
@@ -10325,7 +10317,7 @@ function validateRouteChain(chain, root, pagePath) {
10325
10317
  const hasRoot = chain.some((r) => r === root);
10326
10318
  if (!hasRoot) {
10327
10319
  const location = pagePath ? `in ${pagePath}` : "";
10328
- throw new Error(`[furin] Page ${location} must inherit from root route. ` + "Its route chain must end at the root.tsx layout.");
10320
+ throw new Error(`[furin] Page ${location} must inherit from root route. ` + "Its route chain must end at the root layout.");
10329
10321
  }
10330
10322
  for (const route of chain) {
10331
10323
  if (hasCycle(route)) {
@@ -12868,7 +12860,7 @@ function memoizedBinarySearch(haystack, needle, state, key) {
12868
12860
  state.lastNeedle = needle;
12869
12861
  return state.lastIndex = binarySearch(haystack, needle, low, high);
12870
12862
  }
12871
- function parse2(map) {
12863
+ function parse(map) {
12872
12864
  return typeof map === "string" ? JSON.parse(map) : map;
12873
12865
  }
12874
12866
  function cast(map) {
@@ -12916,7 +12908,7 @@ var COLUMN = 0, SOURCES_INDEX = 1, SOURCE_LINE = 2, SOURCE_COLUMN = 3, NAMES_IND
12916
12908
  const isString = typeof map === "string";
12917
12909
  if (!isString && map._decodedMemo)
12918
12910
  return map;
12919
- const parsed = parse2(map);
12911
+ const parsed = parse(map);
12920
12912
  const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
12921
12913
  this.version = version;
12922
12914
  this.file = file;
@@ -14775,7 +14767,6 @@ var init_buffered_render = __esm(() => {
14775
14767
  });
14776
14768
 
14777
14769
  // src/server/render/static-params.ts
14778
- import { dirname as dirname2, relative as relative4 } from "path";
14779
14770
  function collectStaticParamsStages(route) {
14780
14771
  const stages = [];
14781
14772
  for (const [index, entry] of route.routeChain.entries()) {
@@ -14789,17 +14780,11 @@ function collectStaticParamsStages(route) {
14789
14780
  return stages;
14790
14781
  }
14791
14782
  function ancestorPattern(route, ancestors) {
14792
- const rootSourcePath = route.routeChain[0]?.sourcePath;
14793
14783
  const ancestorSourcePath = ancestors.at(-1)?.sourcePath;
14794
- if (rootSourcePath === undefined || ancestorSourcePath === undefined) {
14795
- return route.pattern;
14796
- }
14797
- const pagesDir = dirname2(rootSourcePath);
14798
- const ancestorDir = dirname2(ancestorSourcePath);
14799
- if (ancestorDir === pagesDir) {
14784
+ if (ancestors.length <= 1) {
14800
14785
  return "/";
14801
14786
  }
14802
- return filePathToPattern(`${relative4(pagesDir, ancestorDir)}/index.tsx`);
14787
+ return route.layouts.find(({ path }) => path === ancestorSourcePath)?.pattern ?? route.pattern;
14803
14788
  }
14804
14789
  function createBuildContext(pattern, params, origin) {
14805
14790
  const path = resolvePath(pattern, params);
@@ -14885,7 +14870,6 @@ async function resolveStaticParams(route, origin) {
14885
14870
  }
14886
14871
  var STATIC_PARAMS_CONCURRENCY = 4;
14887
14872
  var init_static_params = __esm(() => {
14888
- init_patterns();
14889
14873
  init_assemble();
14890
14874
  init_loaders();
14891
14875
  });
@@ -15119,176 +15103,280 @@ var init_internal = __esm(() => {
15119
15103
  _compileContexts = new Map;
15120
15104
  });
15121
15105
 
15122
- // src/plugin/route-tree.ts
15106
+ // src/plugin/route-manifest.ts
15123
15107
  import { existsSync as existsSync3, readdirSync } from "fs";
15124
- import { extname as extname2, join as join3, relative as relative6, resolve as resolve6 } from "path";
15125
- function instanceKey(instance) {
15126
- return `${resolve6(instance.pagesDir)}\x00${instance.prefix}`;
15108
+ import { extname as extname2 } from "path";
15109
+ function child(directory, name) {
15110
+ return `${directory}/${name}`;
15127
15111
  }
15128
- function routeModuleSpecifier(instance) {
15129
- return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
15112
+ function sortedEntries(directory) {
15113
+ return readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
15130
15114
  }
15131
- function scanRouteFiles(directory, directorySegments, files) {
15132
- const entries = readdirSync(directory, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name));
15133
- for (const entry of entries) {
15134
- if (entry.isDirectory()) {
15135
- if (entry.name.startsWith("_")) {
15136
- continue;
15137
- }
15138
- scanRouteFiles(join3(directory, entry.name), [...directorySegments, entry.name], files);
15139
- continue;
15140
- }
15141
- const extension = extname2(entry.name);
15142
- if (!ROUTE_EXTENSION.test(extension) || entry.name.endsWith(".d.ts")) {
15143
- continue;
15144
- }
15145
- const base = entry.name.slice(0, -extension.length);
15146
- const sourcePath = join3(directory, entry.name);
15147
- for (const segment of [...directorySegments, base]) {
15148
- parseDynamicRouteSegment(segment, sourcePath);
15115
+ function moduleBase(name) {
15116
+ if (name.endsWith(".d.ts") || !ROUTE_EXTENSION.test(name)) {
15117
+ return;
15118
+ }
15119
+ return name.slice(0, -extname2(name).length);
15120
+ }
15121
+ function findModule(directory, base) {
15122
+ return SOURCE_EXTENSIONS.map((extension) => child(directory, `${base}${extension}`)).find((path) => existsSync3(path));
15123
+ }
15124
+ function paramName(name, raw, sourcePath) {
15125
+ if (!PARAM_NAME.test(name)) {
15126
+ throw new Error(`[furin] Invalid dynamic parameter ${JSON.stringify(raw)} in ${JSON.stringify(sourcePath)}. Parameter names must match ${PARAM_NAME}.`);
15127
+ }
15128
+ return name;
15129
+ }
15130
+ function splitFlatName(base) {
15131
+ const tokens = [];
15132
+ let current = "";
15133
+ let escaped = false;
15134
+ for (const character of base) {
15135
+ if (character === "[") {
15136
+ escaped = true;
15137
+ } else if (character === "]") {
15138
+ escaped = false;
15149
15139
  }
15150
- if (ROUTE_CONVENTIONS.has(base)) {
15140
+ if (character === "." && !escaped) {
15141
+ tokens.push(current);
15142
+ current = "";
15151
15143
  continue;
15152
15144
  }
15153
- if (base.startsWith("_") && base !== "_route") {
15154
- continue;
15145
+ current += character;
15146
+ }
15147
+ tokens.push(current);
15148
+ return tokens;
15149
+ }
15150
+ function tanstackSegment(raw, sourcePath) {
15151
+ if (raw.startsWith("(") && raw.endsWith(")")) {
15152
+ return { raw, type: "group" };
15153
+ }
15154
+ if (raw === "$") {
15155
+ return { raw, type: "splat" };
15156
+ }
15157
+ if (raw.startsWith("{-$") && raw.endsWith("}")) {
15158
+ return {
15159
+ name: paramName(raw.slice(3, -1), raw, sourcePath),
15160
+ optional: true,
15161
+ raw,
15162
+ type: "param"
15163
+ };
15164
+ }
15165
+ if (raw.startsWith("$")) {
15166
+ return { name: paramName(raw.slice(1), raw, sourcePath), optional: false, raw, type: "param" };
15167
+ }
15168
+ if (raw.startsWith("_")) {
15169
+ return { raw, type: "pathless" };
15170
+ }
15171
+ const value = (raw.endsWith("_") ? raw.slice(0, -1) : raw).replace(BRACKET_ESCAPE, "$1");
15172
+ return { raw, type: "static", value };
15173
+ }
15174
+ function tanstackCandidate(base, segments, sourcePath) {
15175
+ const tokens = splitFlatName(base);
15176
+ const last = tokens.at(-1);
15177
+ const index = last === "index";
15178
+ const routeFile = last === "route";
15179
+ const own = (index || routeFile ? tokens.slice(0, -1) : tokens).map((token) => tanstackSegment(token, sourcePath));
15180
+ const routeSegments = [...segments, ...own];
15181
+ if (routeFile && routeSegments.length === 0) {
15182
+ throw new Error(`[furin] ${sourcePath}: a top-level route.tsx has no path to wrap. The root layout lives in __root.tsx.`);
15183
+ }
15184
+ return {
15185
+ forcedLayout: routeFile || routeSegments.at(-1)?.type === "pathless",
15186
+ index,
15187
+ segments: routeSegments,
15188
+ sourcePath
15189
+ };
15190
+ }
15191
+ function scanTanstack(pagesDir) {
15192
+ const candidates = [];
15193
+ const walk = (directory, segments) => {
15194
+ for (const entry of sortedEntries(directory)) {
15195
+ if (entry.name.startsWith("-")) {
15196
+ continue;
15197
+ }
15198
+ const sourcePath = child(directory, entry.name);
15199
+ if (entry.isDirectory()) {
15200
+ walk(sourcePath, [...segments, tanstackSegment(entry.name, sourcePath)]);
15201
+ continue;
15202
+ }
15203
+ const base = moduleBase(entry.name);
15204
+ if (base !== undefined && !(segments.length === 0 && base === "__root")) {
15205
+ candidates.push(tanstackCandidate(base, segments, sourcePath));
15206
+ }
15155
15207
  }
15156
- files.push({
15157
- base,
15158
- directorySegments,
15208
+ };
15209
+ walk(pagesDir, []);
15210
+ return {
15211
+ boundaries: [],
15212
+ candidates,
15213
+ rootPath: findModule(pagesDir, "__root") ?? child(pagesDir, "__root.tsx")
15214
+ };
15215
+ }
15216
+ function nextSegment(name, sourcePath) {
15217
+ if (name.startsWith("(") && name.endsWith(")")) {
15218
+ return { raw: name, type: "group" };
15219
+ }
15220
+ const catchAll = name.match(NEXT_CATCH_ALL);
15221
+ if (catchAll?.[1] !== undefined) {
15222
+ paramName(catchAll[1], name, sourcePath);
15223
+ return { raw: "$", type: "splat" };
15224
+ }
15225
+ if (name.startsWith("[") && name.endsWith("]")) {
15226
+ const name_ = paramName(name.slice(1, -1), name, sourcePath);
15227
+ return { name: name_, optional: false, raw: `$${name_}`, type: "param" };
15228
+ }
15229
+ return { raw: name, type: "static", value: name };
15230
+ }
15231
+ function addNextFile(state, base, segments, sourcePath) {
15232
+ if (base === "route") {
15233
+ throw new Error(`[furin] ${sourcePath}: route handlers are not supported. Declare API routes on your Elysia app instead.`);
15234
+ }
15235
+ if (base === "layout" && segments.at(-1)?.type === "splat") {
15236
+ throw new Error(`[furin] ${sourcePath}: a layout cannot share a catch-all folder with its page: move it to the parent folder.`);
15237
+ }
15238
+ if (base === "page" || base === "layout" && segments.length > 0) {
15239
+ state.candidates.push({
15240
+ forcedLayout: base === "layout",
15241
+ index: base === "page" && segments.at(-1)?.type !== "splat",
15242
+ segments,
15159
15243
  sourcePath
15160
15244
  });
15245
+ } else if (base === "layout") {
15246
+ state.rootPath ??= sourcePath;
15247
+ } else if (base === "error") {
15248
+ state.boundary.errorPath ??= sourcePath;
15249
+ } else if (base === "not-found") {
15250
+ state.boundary.notFoundPath ??= sourcePath;
15161
15251
  }
15162
15252
  }
15163
- function fileRouteId({ pagesDir, prefix }, sourcePath) {
15164
- const path = relative6(pagesDir, sourcePath).replaceAll("\\", "/").replace(ROUTE_EXTENSION, "");
15165
- return `${prefix}/${path}`.replace(INDEX_SUFFIX, "") || "/";
15166
- }
15167
- function segmentPath(segment) {
15168
- return routeSegmentToPattern(segment);
15253
+ function scanNext(pagesDir) {
15254
+ const candidates = [];
15255
+ const boundaries = [];
15256
+ let rootPath;
15257
+ const walk = (directory, segments) => {
15258
+ const boundary = { directory, errorPath: undefined, notFoundPath: undefined };
15259
+ const state = { boundary, candidates, rootPath };
15260
+ for (const entry of sortedEntries(directory)) {
15261
+ const sourcePath = child(directory, entry.name);
15262
+ if (!entry.isDirectory()) {
15263
+ addNextFile(state, moduleBase(entry.name), segments, sourcePath);
15264
+ } else if (!entry.name.startsWith("_")) {
15265
+ walk(sourcePath, [...segments, nextSegment(entry.name, sourcePath)]);
15266
+ }
15267
+ }
15268
+ rootPath ??= state.rootPath;
15269
+ if (boundary.errorPath || boundary.notFoundPath) {
15270
+ boundaries.push(boundary);
15271
+ }
15272
+ };
15273
+ walk(pagesDir, []);
15274
+ boundaries.sort((left, right) => left.directory.length - right.directory.length);
15275
+ return { boundaries, candidates, rootPath: rootPath ?? child(pagesDir, "layout.tsx") };
15276
+ }
15277
+ function segmentKey(segments) {
15278
+ return segments.map((segment) => segment.raw).join("/");
15279
+ }
15280
+ function segmentPattern(segment) {
15281
+ switch (segment.type) {
15282
+ case "group":
15283
+ case "pathless":
15284
+ return;
15285
+ case "param":
15286
+ return `:${segment.name}${segment.optional ? "?" : ""}`;
15287
+ case "splat":
15288
+ return "*";
15289
+ default:
15290
+ return segment.value;
15291
+ }
15169
15292
  }
15170
- function routeId(instanceId, path) {
15171
- const encodedPath = Array.from(new TextEncoder().encode(path), (byte) => byte.toString(16).padStart(2, "0")).join("");
15172
- return `_route_${instanceId}_${encodedPath}`;
15293
+ function urlPattern(segments) {
15294
+ return `/${segments.flatMap((segment) => segmentPattern(segment) ?? []).join("/")}`;
15173
15295
  }
15174
- function scanRouteManifest(pagesDir) {
15175
- const scannedFiles = [];
15176
- scanRouteFiles(pagesDir, [], scannedFiles);
15177
- const seenPatterns = new Map;
15178
- return scannedFiles.map((file) => {
15179
- if (file.base === "_route") {
15180
- return { ...file, pattern: undefined };
15181
- }
15182
- const relativePath = relative6(pagesDir, file.sourcePath).replaceAll("\\", "/");
15183
- const pattern = filePathToPattern(relativePath);
15184
- const patternKey = routePatternKey(pattern);
15185
- const previousPath = seenPatterns.get(patternKey);
15186
- if (previousPath !== undefined) {
15187
- throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${previousPath}" and "${relativePath}".`);
15188
- }
15189
- seenPatterns.set(patternKey, relativePath);
15190
- return { ...file, pattern };
15296
+ function routeParams(segments) {
15297
+ return segments.flatMap((segment) => {
15298
+ if (segment.type === "param") {
15299
+ return [{ name: segment.name, optional: segment.optional }];
15300
+ }
15301
+ return segment.type === "splat" ? [{ name: "_splat", optional: false }] : [];
15191
15302
  });
15192
15303
  }
15193
- function buildRouteTree(pagesDir, instanceId) {
15194
- const nodes = new Map;
15195
- const ensureNode = (segments) => {
15196
- const key = segments.join("/");
15197
- const existing = nodes.get(key);
15198
- if (existing) {
15199
- return existing;
15200
- }
15201
- const node = {
15202
- children: [],
15203
- fileRoutes: [],
15204
- indexRoute: undefined,
15205
- layout: undefined,
15206
- name: segments.at(-1) ?? ""
15207
- };
15208
- nodes.set(key, node);
15209
- if (segments.length > 0) {
15210
- ensureNode(segments.slice(0, -1)).children.push(node);
15211
- }
15212
- return node;
15213
- };
15214
- const root = ensureNode([]);
15215
- for (const file of scanRouteManifest(pagesDir)) {
15216
- const node = ensureNode(file.directorySegments);
15217
- if (file.pattern === undefined) {
15218
- const path = `/${file.directorySegments.map(segmentPath).join("/")}#layout`;
15219
- node.layout = { id: routeId(instanceId, path), path: "", sourcePath: file.sourcePath };
15220
- continue;
15221
- }
15222
- const route = {
15223
- id: routeId(instanceId, file.pattern),
15224
- path: file.pattern,
15225
- sourcePath: file.sourcePath
15226
- };
15227
- if (file.base === "index") {
15228
- node.indexRoute = route;
15229
- } else {
15230
- node.fileRoutes.push(route);
15231
- }
15304
+ function assertSplatLast(candidate) {
15305
+ const splat = candidate.segments.findIndex((segment) => segment.type === "splat");
15306
+ if (splat !== -1 && splat < candidate.segments.length - 1) {
15307
+ throw new Error(`[furin] ${candidate.sourcePath}: a catch-all segment must be the last segment of its path.`);
15232
15308
  }
15233
- return root;
15234
15309
  }
15235
- function collectRouteFiles(root) {
15236
- const files = [];
15237
- const nodes = [root];
15238
- while (nodes.length > 0) {
15239
- const node = nodes.pop();
15240
- if (!node) {
15241
- continue;
15242
- }
15243
- if (node.layout) {
15244
- files.push(node.layout);
15245
- }
15246
- if (node.indexRoute) {
15247
- files.push(node.indexRoute);
15310
+ function patternKeys(pattern) {
15311
+ const keys = expandOptionalSegments(pattern).map((variant) => variant.replace(PARAM_SEGMENT, "$1:param"));
15312
+ return [...new Set(keys)];
15313
+ }
15314
+ function claimPatterns(seenPatterns, pattern, sourcePath, relativePath) {
15315
+ for (const patternKey of patternKeys(pattern)) {
15316
+ const previous = seenPatterns.get(patternKey);
15317
+ if (previous !== undefined) {
15318
+ throw new Error(`[furin] Duplicate route pattern "${patternKey}" from "${relativePath(previous)}" and "${relativePath(sourcePath)}".`);
15248
15319
  }
15249
- files.push(...node.fileRoutes);
15250
- nodes.push(...node.children);
15320
+ seenPatterns.set(patternKey, sourcePath);
15251
15321
  }
15252
- return files;
15253
- }
15254
- function routeSourcePaths(instance) {
15255
- const instanceId = Bun.hash(instanceKey(instance)).toString(16);
15256
- return collectRouteFiles(buildRouteTree(instance.pagesDir, instanceId)).map(({ sourcePath }) => resolve6(sourcePath)).toSorted((left, right) => left.localeCompare(right));
15257
15322
  }
15258
- function conventionSourcePaths(directory) {
15259
- const paths = [];
15260
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
15261
- if (entry.isDirectory()) {
15262
- if (!entry.name.startsWith("_")) {
15263
- paths.push(...conventionSourcePaths(join3(directory, entry.name)));
15264
- }
15265
- continue;
15266
- }
15267
- const extension = extname2(entry.name);
15268
- if (!ROUTE_EXTENSION.test(extension) || entry.name.endsWith(".d.ts")) {
15269
- continue;
15323
+ function buildManifest(scan, pagesDir, prefix) {
15324
+ const relativePath = (path) => path.slice(pagesDir.length + 1);
15325
+ const { candidates } = scan;
15326
+ const keys = candidates.map((candidate) => segmentKey(candidate.segments));
15327
+ const hasDescendant = (key, self2) => candidates.some((other, index) => other !== self2 && (keys[index]?.startsWith(`${key}/`) === true || other.index && keys[index] === key));
15328
+ const layouts = new Map;
15329
+ const kinds = candidates.map((candidate, index) => {
15330
+ assertSplatLast(candidate);
15331
+ const key = keys[index] ?? "";
15332
+ const isLayout = !candidate.index && (candidate.forcedLayout || hasDescendant(key, candidate));
15333
+ if (!isLayout) {
15334
+ return "page";
15270
15335
  }
15271
- const base = entry.name.slice(0, -extension.length);
15272
- if (base === "error" || base === "not-found") {
15273
- paths.push(resolve6(directory, entry.name));
15336
+ const existing = layouts.get(key);
15337
+ if (existing !== undefined) {
15338
+ throw new Error(`[furin] Two layouts wrap "/${key}": "${relativePath(existing)}" and "${relativePath(candidate.sourcePath)}".`);
15274
15339
  }
15275
- }
15276
- return paths;
15340
+ layouts.set(key, candidate.sourcePath);
15341
+ return "layout";
15342
+ });
15343
+ const seenIds = new Map;
15344
+ const seenPatterns = new Map;
15345
+ const routes = candidates.map((candidate, index) => {
15346
+ const kind = kinds[index] ?? "page";
15347
+ const { segments, sourcePath } = candidate;
15348
+ const key = keys[index] ?? "";
15349
+ let parentPath = candidate.index ? layouts.get(key) : undefined;
15350
+ for (let depth = segments.length - 1;parentPath === undefined && depth > 0; depth -= 1) {
15351
+ parentPath = layouts.get(segmentKey(segments.slice(0, depth)));
15352
+ }
15353
+ const path = `/${key}${candidate.index && key !== "" ? "/" : ""}`;
15354
+ const id = prefix === "" ? path : `${prefix}${path}`;
15355
+ const previousId = seenIds.get(id);
15356
+ if (previousId !== undefined) {
15357
+ throw new Error(`[furin] Duplicate route id "${id}" from "${relativePath(previousId)}" and "${relativePath(sourcePath)}".`);
15358
+ }
15359
+ seenIds.set(id, sourcePath);
15360
+ const pattern = urlPattern(segments);
15361
+ if (kind === "page") {
15362
+ claimPatterns(seenPatterns, pattern, sourcePath, relativePath);
15363
+ }
15364
+ return { id, kind, params: routeParams(segments), parentPath, pattern, sourcePath };
15365
+ });
15366
+ return { boundaries: scan.boundaries, rootPath: scan.rootPath, routes };
15277
15367
  }
15278
- function routeSnapshotSourcePaths(instance) {
15279
- const rootPath = resolve6(instance.pagesDir, "root.tsx");
15280
- return [
15281
- ...existsSync3(rootPath) ? [rootPath] : [],
15282
- ...routeSourcePaths(instance),
15283
- ...conventionSourcePaths(instance.pagesDir)
15284
- ].toSorted((left, right) => left.localeCompare(right));
15368
+ function scanRouteManifest({ pagesDir, prefix, style }) {
15369
+ const directory = pagesDir.replaceAll("\\", "/");
15370
+ return buildManifest(style === "nextjs" ? scanNext(directory) : scanTanstack(directory), directory, prefix);
15285
15371
  }
15286
- var ROUTE_EXTENSION, ROUTE_CONVENTIONS, INDEX_SUFFIX;
15287
- var init_route_tree = __esm(() => {
15288
- init_patterns();
15372
+ var ROUTE_EXTENSION, PARAM_NAME, BRACKET_ESCAPE, SOURCE_EXTENSIONS, PARAM_SEGMENT, NEXT_CATCH_ALL;
15373
+ var init_route_manifest = __esm(() => {
15289
15374
  ROUTE_EXTENSION = /\.(?:jsx?|tsx?)$/;
15290
- ROUTE_CONVENTIONS = new Set(["error", "not-found", "root"]);
15291
- INDEX_SUFFIX = /\/index$/;
15375
+ PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
15376
+ BRACKET_ESCAPE = /\[([^\]]*)\]/g;
15377
+ SOURCE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
15378
+ PARAM_SEGMENT = /(^|\/):[^/]+/g;
15379
+ NEXT_CATCH_ALL = /^\[\[?\.\.\.([^\]]+)\]\]?$/;
15292
15380
  });
15293
15381
 
15294
15382
  // src/server/router/defined-route.ts
@@ -15306,9 +15394,11 @@ function adaptDefinedLayout(route, parent, sourcePath) {
15306
15394
  const component = route.component;
15307
15395
  return {
15308
15396
  __type: "FURIN_ROUTE",
15397
+ errorComponent: route.errorComponent,
15309
15398
  layout: component,
15310
15399
  loader: route.loader,
15311
15400
  mode: route.mode,
15401
+ notFoundComponent: route.notFoundComponent,
15312
15402
  params: route.schemas?.params,
15313
15403
  ...parent ? { parent } : {},
15314
15404
  query: route.schemas?.query,
@@ -15333,9 +15423,11 @@ function adaptDefinedPage(route, parent) {
15333
15423
  requestLoader: route.requestLoader
15334
15424
  },
15335
15425
  component,
15426
+ errorComponent: route.errorComponent,
15336
15427
  head,
15337
15428
  loader: route.loader,
15338
15429
  mode: route.mode,
15430
+ notFoundComponent: route.notFoundComponent,
15339
15431
  revalidate: route.revalidate,
15340
15432
  staticParams: route.staticParams,
15341
15433
  tags: copyTags(route.tags)
@@ -15373,7 +15465,7 @@ function collectRouteTags(routeChain, page) {
15373
15465
  function loadProdRoutes(ctx) {
15374
15466
  const rootExport = ctx.modules[ctx.rootPath]?.route;
15375
15467
  if (!isDefinedRouteTerminal(rootExport) || typeof rootExport.layout !== "function") {
15376
- throw new Error("[furin] root.tsx: defineRootRoute().layout() not found in CompileContext.");
15468
+ throw new Error(`[furin] ${ctx.rootPath}: defineRootRoute().layout() not found in CompileContext.`);
15377
15469
  }
15378
15470
  const rootRoute = adaptDefinedLayout(rootExport, undefined, ctx.rootPath);
15379
15471
  function resolveModuleComponent(modPath) {
@@ -15383,26 +15475,28 @@ function loadProdRoutes(ctx) {
15383
15475
  return ctx.modules[modPath]?.default;
15384
15476
  }
15385
15477
  const root = {
15386
- error: resolveModuleComponent(ctx.rootConventions?.errorPath),
15387
- notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
15478
+ error: rootRoute.errorComponent ?? resolveModuleComponent(ctx.rootConventions?.errorPath),
15479
+ notFound: rootRoute.notFoundComponent ?? resolveModuleComponent(ctx.rootConventions?.notFoundPath),
15388
15480
  path: ctx.rootPath,
15389
15481
  route: rootRoute
15390
15482
  };
15391
15483
  const routes = [];
15392
15484
  for (const { pattern, path, mode } of ctx.routes) {
15393
- const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, path, root, ctx);
15485
+ const meta = ctx.routeMetadata?.[path];
15486
+ const layouts = meta?.layouts ?? [];
15487
+ const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, layouts, root, ctx);
15394
15488
  if (!page) {
15395
15489
  throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
15396
15490
  }
15397
15491
  const routeChain = collectRouteChainFromRoute(page._route);
15398
15492
  validateRouteChain(routeChain, root.route, path);
15399
- const meta = ctx.routeMetadata?.[path];
15400
- const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
15401
- ...b,
15402
- error: resolveModuleComponent(b.errorPath),
15403
- notFound: resolveModuleComponent(b.notFoundPath)
15493
+ const boundaries = (meta?.segmentBoundaries ?? []).map((boundary) => ({
15494
+ ...boundary,
15495
+ error: boundary.fromRoute ? routeBoundaryComponent(ctx, boundary.errorPath, "errorComponent") : resolveModuleComponent(boundary.errorPath),
15496
+ notFound: boundary.fromRoute ? routeBoundaryComponent(ctx, boundary.notFoundPath, "notFoundComponent") : resolveModuleComponent(boundary.notFoundPath)
15404
15497
  }));
15405
15498
  routes.push({
15499
+ layouts,
15406
15500
  mode,
15407
15501
  page,
15408
15502
  path,
@@ -15416,45 +15510,30 @@ function loadProdRoutes(ctx) {
15416
15510
  }
15417
15511
  return { root, routes };
15418
15512
  }
15419
- function resolveCompiledRuntimePage(module, path, root, context) {
15513
+ function routeBoundaryComponent(ctx, modulePath, field) {
15514
+ const route = modulePath ? ctx.modules[modulePath]?.route : undefined;
15515
+ return isDefinedRouteTerminal(route) ? route[field] : undefined;
15516
+ }
15517
+ function resolveCompiledRuntimePage(module, layouts, root, context) {
15420
15518
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
15421
15519
  return;
15422
15520
  }
15423
- const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
15424
- const parent = resolveCompiledLayoutParent(path, pagesDir, root.route, context);
15521
+ let parent = root.route;
15522
+ for (const { path } of layouts) {
15523
+ const layout = context.modules[path]?.route;
15524
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15525
+ throw invalidNestedLayoutError(path);
15526
+ }
15527
+ parent = adaptDefinedLayout(layout, parent, path);
15528
+ }
15425
15529
  return adaptDefinedPage(module.route, parent);
15426
15530
  }
15427
15531
  function invalidNestedLayoutError(layoutPath) {
15428
- return new Error(`[furin] ${layoutPath}: _route.tsx must export \`route = defineRoute(id).config({ mode }).layout(({ children }) => ...)\`, with the file's id. For example, in blog/_route.tsx:
15429
- export const route = defineRoute("/blog/_route")
15532
+ return new Error(`[furin] ${layoutPath}: a layout file must export \`route = defineRoute(id).config({ mode }).layout(({ children }) => ...)\`, with the file's id. For example, in board/route.tsx:
15533
+ export const route = defineRoute("/board")
15430
15534
  .config({ mode: "ssr" })
15431
15535
  .layout(({ children }) => <section>{children}</section>);`);
15432
15536
  }
15433
- function resolveCompiledLayoutParent(pagePath, pagesDir, rootRoute, context) {
15434
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
15435
- if (pageDirectory.length <= pagesDir.length) {
15436
- return rootRoute;
15437
- }
15438
- const segments = pageDirectory.slice(pagesDir.length + 1).split("/");
15439
- let directory = pagesDir;
15440
- let parent = rootRoute;
15441
- for (const segment of segments) {
15442
- directory = `${directory}/${segment}`;
15443
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15444
- const layoutModule = context.modules[candidate];
15445
- if (!layoutModule) {
15446
- continue;
15447
- }
15448
- const layout = layoutModule.route;
15449
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15450
- throw invalidNestedLayoutError(candidate);
15451
- }
15452
- parent = adaptDefinedLayout(layout, parent, candidate);
15453
- break;
15454
- }
15455
- }
15456
- return parent;
15457
- }
15458
15537
  function toPosixPath(path) {
15459
15538
  return path.replaceAll("\\", "/");
15460
15539
  }
@@ -15463,36 +15542,60 @@ function routeRelativePath(pagesDir, absolutePath) {
15463
15542
  const path = toPosixPath(absolutePath);
15464
15543
  return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
15465
15544
  }
15466
- async function scanPages(pagesDir) {
15467
- const dir = toPosixPath(pagesDir);
15468
- const root = await scanRootLayout(dir);
15469
- const routes = await scanPageFiles(dir, root);
15545
+ function manifestLayouts(manifest, route) {
15546
+ const byPath = new Map(manifest.routes.map((entry) => [entry.sourcePath, entry]));
15547
+ const layouts = [];
15548
+ for (let parent = route.parentPath;parent !== undefined; ) {
15549
+ const layout = byPath.get(parent);
15550
+ if (!layout) {
15551
+ break;
15552
+ }
15553
+ layouts.unshift({ path: layout.sourcePath, pattern: layout.pattern });
15554
+ parent = layout.parentPath;
15555
+ }
15556
+ return layouts;
15557
+ }
15558
+ async function scanPages(instance) {
15559
+ const pagesDir = toPosixPath(instance.pagesDir);
15560
+ const manifest = scanRouteManifest({ ...instance, pagesDir });
15561
+ const root = await scanRootLayout(manifest, pagesDir, instance.style);
15562
+ const routes = await scanPageFiles(manifest, pagesDir, instance.style, root);
15470
15563
  if (routes.some((route) => route.routeChain.some((entry) => entry.requestLoader))) {
15471
15564
  await annotateScannedRequestKeys(routes);
15472
15565
  }
15473
15566
  return { root, routes };
15474
15567
  }
15475
- async function scanRootLayout(pagesDir) {
15476
- const rootPath = `${pagesDir}/root.tsx`;
15568
+ async function scanRootLayout(manifest, pagesDir, style) {
15569
+ const { rootPath } = manifest;
15570
+ const rootFile = ROOT_FILE_NAMES[style];
15477
15571
  const ctx = getCompileContext();
15478
15572
  if (!(existsSync4(rootPath) || ctx?.modules[rootPath])) {
15479
- throw new Error(`[furin] root.tsx: not found in ${pagesDir}. Every pages directory needs a root layout:
15573
+ throw new Error(`[furin] ${rootFile}: not found in ${pagesDir}. Every pages directory needs a root layout:
15480
15574
  ${ROOT_EXAMPLE}`);
15481
15575
  }
15482
15576
  const mod = ctx?.modules[rootPath] ?? await (isDevelopment() ? import(`${rootPath}?furin-server&t=${routeModuleSourceVersion(rootPath)}`) : import(rootPath));
15483
15577
  const rootExport = mod.route;
15484
15578
  if (!isDefinedRouteTerminal(rootExport)) {
15485
- throw new Error(`[furin] ${rootPath}: root.tsx must export \`route = defineRootRoute().config({ mode }).layout(...)\`:
15579
+ throw new Error(`[furin] ${rootPath}: ${rootFile} must export \`route = defineRootRoute().config({ mode }).layout(...)\`:
15486
15580
  ${ROOT_EXAMPLE}`);
15487
15581
  }
15488
15582
  if (!rootExport.layout) {
15489
- throw new Error(`[furin] ${rootPath}: root.tsx: defineRootRoute() must end with .layout(({ children }) => ...):
15583
+ throw new Error(`[furin] ${rootPath}: ${rootFile}: defineRootRoute() must end with .layout(({ children }) => ...):
15490
15584
  ${ROOT_EXAMPLE}`);
15491
15585
  }
15492
15586
  const rootRoute = adaptDefinedLayout(rootExport, undefined, rootPath);
15587
+ if (style === "tanstack") {
15588
+ return {
15589
+ error: rootRoute.errorComponent,
15590
+ notFound: rootRoute.notFoundComponent,
15591
+ path: rootPath,
15592
+ route: rootRoute
15593
+ };
15594
+ }
15595
+ const rootBoundary = manifest.boundaries.find((boundary) => boundary.directory === pagesDir);
15493
15596
  const [notFoundEntry, errorEntry] = await Promise.all([
15494
- loadConventionComponent(pagesDir, "not-found"),
15495
- loadConventionComponent(pagesDir, "error")
15597
+ loadConventionComponent(rootBoundary?.notFoundPath, "not-found"),
15598
+ loadConventionComponent(rootBoundary?.errorPath, "error")
15496
15599
  ]);
15497
15600
  return {
15498
15601
  error: errorEntry?.component,
@@ -15503,91 +15606,100 @@ ${ROOT_EXAMPLE}`);
15503
15606
  route: rootRoute
15504
15607
  };
15505
15608
  }
15506
- function getSourceModuleCandidates(dir, name) {
15507
- return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
15508
- }
15509
- async function loadConventionComponent(dir, name) {
15609
+ async function loadConventionComponent(filePath, name) {
15610
+ if (filePath === undefined) {
15611
+ return;
15612
+ }
15510
15613
  const ctx = getCompileContext();
15511
- for (const filePath of getSourceModuleCandidates(dir, name)) {
15512
- if (existsSync4(filePath) || ctx?.modules[filePath]) {
15513
- const moduleSpecifier = isDevelopment() && existsSync4(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15514
- const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15515
- if (mod.default) {
15516
- return { component: mod.default, path: filePath };
15517
- }
15518
- const exportNames = Object.keys(mod).join(", ") || "none";
15519
- throw new Error(`[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:
15520
- ${CONVENTION_EXAMPLES[name]}`);
15521
- }
15614
+ const moduleSpecifier = isDevelopment() && existsSync4(filePath) ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}` : filePath;
15615
+ const mod = ctx?.modules[filePath] ?? await import(moduleSpecifier);
15616
+ if (mod.default) {
15617
+ return { component: mod.default, path: filePath };
15522
15618
  }
15619
+ const exportNames = Object.keys(mod).join(", ") || "none";
15620
+ throw new Error(`[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:
15621
+ ${CONVENTION_EXAMPLES[name]}`);
15523
15622
  }
15524
- async function scanPageFiles(pagesDir, root) {
15623
+ async function scanPageFiles(manifest, pagesDir, style, root) {
15525
15624
  const routes = [];
15526
- const notFoundCache = new Map;
15527
- const errorCache = new Map;
15528
- for (const { pattern, sourcePath } of scanRouteManifest(pagesDir)) {
15529
- if (pattern === undefined) {
15625
+ const boundaryCache = new Map;
15626
+ for (const manifestRoute of manifest.routes) {
15627
+ if (manifestRoute.kind !== "page") {
15530
15628
  continue;
15531
15629
  }
15532
- const absolutePath = toPosixPath(sourcePath);
15630
+ const { pattern } = manifestRoute;
15631
+ const absolutePath = manifestRoute.sourcePath;
15533
15632
  const relativePath = routeRelativePath(pagesDir, absolutePath);
15534
- const segmentBoundaries = await collectSegmentBoundaries(absolutePath, pagesDir, notFoundCache, errorCache);
15633
+ const layouts = manifestLayouts(manifest, manifestRoute);
15634
+ const directoryBoundaries = style === "nextjs" ? await collectSegmentBoundaries(absolutePath, manifest.boundaries, boundaryCache) : [];
15535
15635
  if (isDevelopment()) {
15536
- const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
15537
- devRoute.segmentBoundaries = alignSegmentBoundaryDepths(segmentBoundaries, devRoute.routeChain);
15636
+ const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, layouts);
15637
+ devRoute.segmentBoundaries = style === "nextjs" ? alignSegmentBoundaryDepths(directoryBoundaries, devRoute.routeChain) : routeDefinedBoundaries(root, devRoute.routeChain, devRoute.page, absolutePath);
15538
15638
  routes.push(devRoute);
15539
15639
  continue;
15540
15640
  }
15541
15641
  const ctx = getCompileContext();
15542
15642
  const pageMod = ctx?.modules[absolutePath] ?? await import(absolutePath);
15543
- const page = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
15643
+ const page = await resolveRuntimePage(pageMod, layouts, root.route);
15544
15644
  if (!page) {
15545
15645
  throw new Error(`[furin] ${relativePath}: no valid defineRoute(id).page() export found`);
15546
15646
  }
15547
15647
  const routeChain = collectRouteChainFromRoute(page._route);
15548
15648
  validateRouteChain(routeChain, root.route, relativePath);
15549
15649
  routes.push({
15650
+ layouts,
15550
15651
  mode: resolveMode(page, routeChain),
15551
15652
  page,
15552
15653
  path: absolutePath,
15553
15654
  pattern,
15554
15655
  routeChain,
15555
- segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
15656
+ segmentBoundaries: style === "nextjs" ? alignSegmentBoundaryDepths(directoryBoundaries, routeChain) : routeDefinedBoundaries(root, routeChain, page, absolutePath),
15556
15657
  tags: collectRouteTags(routeChain, page)
15557
15658
  });
15558
15659
  }
15559
15660
  return routes;
15560
15661
  }
15561
- async function resolveRuntimePage(module, absolutePath, pagesDir, rootRoute) {
15662
+ function routeDefinedBoundaries(root, routeChain, page, pagePath) {
15663
+ const entries = [
15664
+ { depth: 0, path: root.path, route: routeChain[0] ?? root.route },
15665
+ ...routeChain.slice(1, -1).map((route, index) => ({ depth: index, path: route.sourcePath, route })),
15666
+ { depth: Math.max(routeChain.length - 2, 0), path: pagePath, route: page }
15667
+ ];
15668
+ const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
15669
+ return entries.flatMap(({ depth, path, route }) => {
15670
+ const { errorComponent, notFoundComponent } = route;
15671
+ if (path === undefined || !(errorComponent || notFoundComponent)) {
15672
+ return [];
15673
+ }
15674
+ return [
15675
+ {
15676
+ depth,
15677
+ error: errorComponent,
15678
+ errorPath: errorComponent ? path : undefined,
15679
+ fromRoute: true,
15680
+ notFound: notFoundComponent,
15681
+ notFoundPath: notFoundComponent ? path : undefined,
15682
+ path: path === root.path ? pagesDir : path
15683
+ }
15684
+ ];
15685
+ });
15686
+ }
15687
+ async function resolveRuntimePage(module, layouts, rootRoute) {
15562
15688
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
15563
15689
  return;
15564
15690
  }
15565
- const parent = await resolveDefinedLayoutParent(absolutePath, pagesDir, rootRoute);
15691
+ const parent = await resolveDefinedLayoutParent(layouts, rootRoute);
15566
15692
  return adaptDefinedPage(module.route, parent);
15567
15693
  }
15568
- async function resolveDefinedLayoutParent(pagePath, pagesDir, rootRoute) {
15569
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
15570
- if (pageDirectory.length <= pagesDir.length) {
15571
- return rootRoute;
15572
- }
15573
- const relativeDirectory = pageDirectory.slice(pagesDir.length + 1);
15574
- const segments = relativeDirectory.split("/");
15575
- let directory = pagesDir;
15694
+ async function resolveDefinedLayoutParent(layouts, rootRoute) {
15576
15695
  let parent = rootRoute;
15577
- for (const segment of segments) {
15578
- directory = `${directory}/${segment}`;
15579
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
15580
- if (!existsSync4(candidate)) {
15581
- continue;
15582
- }
15583
- const layoutModule = await (isDevelopment() ? import(`${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`) : import(candidate));
15584
- const layout = layoutModule.route;
15585
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15586
- throw invalidNestedLayoutError(candidate);
15587
- }
15588
- parent = adaptDefinedLayout(layout, parent, candidate);
15589
- break;
15696
+ for (const { path } of layouts) {
15697
+ const layoutModule = await (isDevelopment() ? import(`${path}?furin-server&t=${routeModuleSourceVersion(path)}`) : import(path));
15698
+ const layout = layoutModule.route;
15699
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
15700
+ throw invalidNestedLayoutError(path);
15590
15701
  }
15702
+ parent = adaptDefinedLayout(layout, parent, path);
15591
15703
  }
15592
15704
  return parent;
15593
15705
  }
@@ -15606,50 +15718,35 @@ function alignSegmentBoundaryDepths(boundaries, routeChain) {
15606
15718
  return { ...boundary, depth };
15607
15719
  });
15608
15720
  }
15609
- async function collectSegmentBoundaries(pageAbsolutePath, pagesDir, notFoundCache, errorCache) {
15721
+ async function collectSegmentBoundaries(pageAbsolutePath, boundaries, cache) {
15610
15722
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
15611
- const dirs = [pagesDir];
15612
- if (pageDir.length > pagesDir.length) {
15613
- const relativeTail = pageDir.slice(pagesDir.length + 1);
15614
- const parts = relativeTail.split("/");
15615
- let acc = pagesDir;
15616
- for (const part of parts) {
15617
- acc = `${acc}/${part}`;
15618
- dirs.push(acc);
15619
- }
15620
- }
15621
- const boundaries = [];
15622
- for (let depth = 0;depth < dirs.length; depth += 1) {
15623
- const dir = dirs[depth];
15624
- const [errorEntry, notFoundEntry] = await Promise.all([
15625
- errorCache.has(dir) ? Promise.resolve(errorCache.get(dir)) : loadConventionComponent(dir, "error").then((r) => {
15626
- errorCache.set(dir, r);
15627
- return r;
15628
- }),
15629
- notFoundCache.has(dir) ? Promise.resolve(notFoundCache.get(dir)) : loadConventionComponent(dir, "not-found").then((r) => {
15630
- notFoundCache.set(dir, r);
15631
- return r;
15632
- })
15633
- ]);
15634
- if (errorEntry || notFoundEntry) {
15635
- boundaries.push({
15636
- depth,
15637
- error: errorEntry?.component,
15638
- errorPath: errorEntry?.path,
15639
- notFound: notFoundEntry?.component,
15640
- notFoundPath: notFoundEntry?.path,
15641
- path: dir
15642
- });
15643
- }
15644
- }
15645
- return boundaries;
15723
+ const enclosing = boundaries.filter(({ directory }) => pageDir === directory || pageDir.startsWith(`${directory}/`));
15724
+ return await Promise.all(enclosing.map((boundary) => {
15725
+ const cached = cache.get(boundary.directory);
15726
+ if (cached) {
15727
+ return cached;
15728
+ }
15729
+ const loaded = Promise.all([
15730
+ loadConventionComponent(boundary.errorPath, "error"),
15731
+ loadConventionComponent(boundary.notFoundPath, "not-found")
15732
+ ]).then(([errorEntry, notFoundEntry]) => ({
15733
+ depth: 0,
15734
+ error: errorEntry?.component,
15735
+ errorPath: errorEntry?.path,
15736
+ notFound: notFoundEntry?.component,
15737
+ notFoundPath: notFoundEntry?.path,
15738
+ path: boundary.directory
15739
+ }));
15740
+ cache.set(boundary.directory, loaded);
15741
+ return loaded;
15742
+ }));
15646
15743
  }
15647
- async function buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir) {
15744
+ async function buildDevRoute(absolutePath, relativePath, pattern, root, layouts) {
15648
15745
  let page;
15649
15746
  let routeChain = [];
15650
15747
  try {
15651
15748
  const pageMod = await import(`${absolutePath}?furin-server&t=${routeModuleSourceVersion(absolutePath)}`);
15652
- const resolvedPage = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
15749
+ const resolvedPage = await resolveRuntimePage(pageMod, layouts, root.route);
15653
15750
  if (resolvedPage) {
15654
15751
  page = resolvedPage;
15655
15752
  routeChain = collectRouteChainFromRoute(page._route);
@@ -15662,6 +15759,7 @@ async function buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir
15662
15759
  component: () => null
15663
15760
  };
15664
15761
  return {
15762
+ layouts,
15665
15763
  mode: page ? resolveMode(page, routeChain) : "ssr",
15666
15764
  page: page ?? devStubPage,
15667
15765
  path: absolutePath,
@@ -15678,9 +15776,9 @@ var ROOT_EXAMPLE = ` export const route = defineRootRoute()
15678
15776
  <head><HeadContent /></head>
15679
15777
  <body>{children}<Scripts /></body>
15680
15778
  </html>
15681
- ));`, CONVENTION_EXAMPLES, SOURCE_MODULE_EXTENSIONS;
15779
+ ));`, CONVENTION_EXAMPLES, ROOT_FILE_NAMES;
15682
15780
  var init_discovery = __esm(() => {
15683
- init_route_tree();
15781
+ init_route_manifest();
15684
15782
  init_instance();
15685
15783
  init_internal();
15686
15784
  init_patterns();
@@ -15693,7 +15791,10 @@ var init_discovery = __esm(() => {
15693
15791
  return <h1>Page not found</h1>;
15694
15792
  }`
15695
15793
  };
15696
- SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
15794
+ ROOT_FILE_NAMES = {
15795
+ nextjs: "layout.tsx",
15796
+ tanstack: "__root.tsx"
15797
+ };
15697
15798
  });
15698
15799
 
15699
15800
  // src/server/render/not-found.ts
@@ -16888,17 +16989,15 @@ async function importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx) {
16888
16989
  throw err;
16889
16990
  }
16890
16991
  }
16891
- async function importFreshLayoutRouteModule(layoutDir, resolveImport, ctx) {
16892
- for (const layoutPath of getSourceModuleCandidates(layoutDir, "_route")) {
16893
- const freshMod = await importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx);
16894
- if (!freshMod) {
16895
- continue;
16896
- }
16897
- if (!(isDefinedRouteTerminal(freshMod.route) && typeof freshMod.route.layout === "function")) {
16898
- throw invalidExportFailure(invalidNestedLayoutError(layoutPath), layoutPath);
16899
- }
16900
- return freshMod;
16992
+ async function importFreshLayoutRouteModule(layoutPath, resolveImport, ctx) {
16993
+ const freshMod = await importFreshRouteModuleCandidate(layoutPath, resolveImport, ctx);
16994
+ if (!freshMod) {
16995
+ return;
16996
+ }
16997
+ if (!(isDefinedRouteTerminal(freshMod.route) && typeof freshMod.route.layout === "function")) {
16998
+ throw invalidExportFailure(invalidNestedLayoutError(layoutPath), layoutPath);
16901
16999
  }
17000
+ return freshMod;
16902
17001
  }
16903
17002
  function invalidExportFailure(error, file) {
16904
17003
  Reflect.set(error, "furinPosition", { column: 1, file, line: 1 });
@@ -16911,9 +17010,11 @@ function patchRouteEntryFromFreshModule(entry, freshMod) {
16911
17010
  }
16912
17011
  if (isDefinedRouteTerminal(freshRoute) && typeof freshRoute.layout === "function") {
16913
17012
  const adapted = adaptDefinedLayout(freshRoute, entry.parent);
17013
+ entry.errorComponent = adapted.errorComponent;
16914
17014
  entry.layout = adapted.layout;
16915
17015
  entry.loader = adapted.loader;
16916
17016
  entry.mode = adapted.mode;
17017
+ entry.notFoundComponent = adapted.notFoundComponent;
16917
17018
  entry.params = adapted.params;
16918
17019
  entry.query = adapted.query;
16919
17020
  entry.requestLoader = adapted.requestLoader;
@@ -16922,21 +17023,14 @@ function patchRouteEntryFromFreshModule(entry, freshMod) {
16922
17023
  entry.tags = adapted.tags;
16923
17024
  }
16924
17025
  }
16925
- async function refreshLayoutChain(chain, pagePath, rootPath, importFn) {
17026
+ async function refreshLayoutChain(chain, layoutPaths, importFn) {
16926
17027
  const resolveImport = importFn ?? routeModuleImport;
16927
17028
  const ctx = getCompileContext();
16928
- const layoutDirs = collectIntermediateLayoutDirs(pagePath, rootPath);
16929
- const freshMods = await Promise.all(layoutDirs.map((layoutDir) => importFreshLayoutRouteModule(layoutDir, resolveImport, ctx)));
16930
- let chainIdx = 1;
16931
- for (const freshMod of freshMods) {
16932
- if (chainIdx >= chain.length) {
16933
- break;
16934
- }
16935
- if (!freshMod) {
16936
- continue;
17029
+ const freshMods = await Promise.all(layoutPaths.map((layoutPath) => importFreshLayoutRouteModule(layoutPath, resolveImport, ctx)));
17030
+ for (const [index, freshMod] of freshMods.entries()) {
17031
+ if (freshMod) {
17032
+ patchRouteEntryFromFreshModule(chain[index + 1], freshMod);
16937
17033
  }
16938
- patchRouteEntryFromFreshModule(chain[chainIdx], freshMod);
16939
- chainIdx += 1;
16940
17034
  }
16941
17035
  }
16942
17036
  function rebuildDevRoute(base, page, chain) {
@@ -16963,7 +17057,7 @@ async function resolveCurrentDevRoute(route, root) {
16963
17057
  let chain;
16964
17058
  if (isDefinedRouteTerminal(pageMod.route) && typeof pageMod.route.page === "function") {
16965
17059
  const currentChain = route.routeChain;
16966
- await refreshLayoutChain(currentChain, route.path, root.path, undefined);
17060
+ await refreshLayoutChain(currentChain, route.layouts.map(({ path }) => path), undefined);
16967
17061
  const parent = currentChain.at(-2) ?? currentRoot.route;
16968
17062
  const adaptedPage = adaptDefinedPage(pageMod.route, parent);
16969
17063
  page = adaptedPage;
@@ -17016,7 +17110,7 @@ async function loadCachedDevLoaderData(route, ctx, root, mode, purpose) {
17016
17110
  const result = purpose === "document" ? await runDevLoaders(route, loaderCtx) : await runPublicLoaders(route, loaderCtx);
17017
17111
  if (result.type === "data") {
17018
17112
  const entry = {
17019
- dependencies: computeRouteDependencies(route.path, root.path),
17113
+ dependencies: computeRouteDependencies(route.path, root.path, route.layouts.map(({ path }) => path)),
17020
17114
  generatedAt: Date.now(),
17021
17115
  headers: result.headers,
17022
17116
  loaderData: result.syncData,
@@ -17028,15 +17122,8 @@ async function loadCachedDevLoaderData(route, ctx, root, mode, purpose) {
17028
17122
  }
17029
17123
  return result;
17030
17124
  }
17031
- function computeRouteDependencies(pagePath, rootPath) {
17032
- const deps = [pagePath, rootPath];
17033
- for (const dir of collectIntermediateLayoutDirs(pagePath, rootPath)) {
17034
- for (const candidate of getSourceModuleCandidates(dir, "_route")) {
17035
- if (existsSync6(candidate)) {
17036
- deps.push(candidate);
17037
- }
17038
- }
17039
- }
17125
+ function computeRouteDependencies(pagePath, rootPath, layoutPaths) {
17126
+ const deps = [pagePath, rootPath, ...layoutPaths.filter((path) => existsSync6(path))];
17040
17127
  const graph = devGraph(undefined);
17041
17128
  return [...new Set(deps.flatMap((path) => graph.sourceDependencies(path)))].filter(existsSync6);
17042
17129
  }
@@ -17128,7 +17215,7 @@ var init_hmr = __esm(() => {
17128
17215
 
17129
17216
  // src/plugin/preflight.ts
17130
17217
  import { existsSync as existsSync7, readFileSync as readFileSync4 } from "fs";
17131
- import { join as join5 } from "path";
17218
+ import { join as join4 } from "path";
17132
17219
  function staticPlugins(bunfig) {
17133
17220
  if (typeof bunfig !== "object" || bunfig === null || !("serve" in bunfig)) {
17134
17221
  return [];
@@ -17144,7 +17231,7 @@ function staticPlugins(bunfig) {
17144
17231
  return staticConfig.plugins.filter((plugin) => typeof plugin === "string");
17145
17232
  }
17146
17233
  function stripPluginPreflightWarning(projectRoot) {
17147
- const bunfigPath = join5(projectRoot, "bunfig.toml");
17234
+ const bunfigPath = join4(projectRoot, "bunfig.toml");
17148
17235
  const hasBunfig = existsSync7(bunfigPath);
17149
17236
  const plugins = hasBunfig ? staticPlugins(Bun.TOML.parse(readFileSync4(bunfigPath, "utf8"))) : [];
17150
17237
  if (plugins.includes(STRIP_PLUGIN)) {
@@ -18777,9 +18864,9 @@ var init_dist2 = __esm(() => {
18777
18864
  });
18778
18865
 
18779
18866
  // src/shared/parser.ts
18780
- import { parse as parse3 } from "yuku-parser";
18867
+ import { parse as parse2 } from "yuku-parser";
18781
18868
  function parseSource(code, lang) {
18782
- return parse3(code, { lang, sourceType: "module" });
18869
+ return parse2(code, { lang, sourceType: "module" });
18783
18870
  }
18784
18871
  var init_parser = () => {};
18785
18872
 
@@ -20537,7 +20624,7 @@ var init_transform_dev_page = __esm(() => {
20537
20624
 
20538
20625
  // src/plugin/transform-client-module.ts
20539
20626
  import { realpathSync as realpathSync2 } from "fs";
20540
- import { dirname as dirname5 } from "path";
20627
+ import { dirname as dirname4 } from "path";
20541
20628
  function clientModuleKey(modulePath) {
20542
20629
  const realPath = realpathSync2(modulePath).replaceAll("\\", "/");
20543
20630
  return `__FURIN_CLIENT_MODULE_${Bun.hash(realPath).toString(36)}__`;
@@ -20590,7 +20677,7 @@ function rewriteClientModules(module, environment) {
20590
20677
  }
20591
20678
  let key;
20592
20679
  try {
20593
- key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname5(filename))));
20680
+ key = JSON.stringify(clientModuleKey(Bun.resolveSync(specifier, dirname4(filename))));
20594
20681
  } catch (error) {
20595
20682
  throw new Error(`[furin] Cannot resolve clientModule import ${JSON.stringify(specifier)} in ${filename}`, { cause: error });
20596
20683
  }
@@ -21031,7 +21118,7 @@ var init_transform_isomorphic = __esm(() => {
21031
21118
  });
21032
21119
 
21033
21120
  // src/server/dev/error.ts
21034
- import { relative as relative7 } from "path";
21121
+ import { relative as relative5 } from "path";
21035
21122
  function errorMessage2(error) {
21036
21123
  if (error instanceof Error) {
21037
21124
  return error.message;
@@ -21082,7 +21169,7 @@ function createDevErrorPayload(error, context) {
21082
21169
  };
21083
21170
  }
21084
21171
  function displaySourcePath(path) {
21085
- const projected = relative7(process.cwd(), path).replaceAll("\\", "/");
21172
+ const projected = relative5(process.cwd(), path).replaceAll("\\", "/");
21086
21173
  return projected.startsWith("../") ? path : projected;
21087
21174
  }
21088
21175
  function publishDevError(graph, error, context) {
@@ -21129,7 +21216,7 @@ var init_server_only_module = __esm(() => {
21129
21216
  });
21130
21217
 
21131
21218
  // src/server/dev/rewrite-module-specifiers.ts
21132
- import { dirname as dirname6, resolve as resolve7 } from "path";
21219
+ import { dirname as dirname5, resolve as resolve6 } from "path";
21133
21220
  function sourcePosition2(source, byteOffset) {
21134
21221
  const bytes = new TextEncoder().encode(source);
21135
21222
  const prefix = new TextDecoder().decode(bytes.slice(0, byteOffset));
@@ -21150,7 +21237,7 @@ function relativeSpecifier(node) {
21150
21237
  return isStringLiteral(node.source) ? node.source : undefined;
21151
21238
  }
21152
21239
  function resolvedSpecifier(specifier, directory, versioned) {
21153
- const path = versioned ? Bun.resolveSync(specifier, directory) : resolve7(directory, specifier);
21240
+ const path = versioned ? Bun.resolveSync(specifier, directory) : resolve6(directory, specifier);
21154
21241
  const normalized = path.replaceAll("\\", "/");
21155
21242
  return versioned && SCRIPT_FILE_FILTER.test(normalized) && !isServerOnlyModule(path) ? `${normalized}?furin-server&t=${routeModuleSourceVersion(normalized)}` : normalized;
21156
21243
  }
@@ -21162,7 +21249,7 @@ function rewriteModuleSpecifiers(input) {
21162
21249
  Reflect.set(error, "position", sourcePosition2(input.code, parseError.start));
21163
21250
  throw error;
21164
21251
  }
21165
- const directory = dirname6(input.filePath);
21252
+ const directory = dirname5(input.filePath);
21166
21253
  const output = new MagicString(input.code);
21167
21254
  walkAST(program, (node) => {
21168
21255
  const literal = relativeSpecifier(node);
@@ -21184,7 +21271,7 @@ var init_rewrite_module_specifiers = __esm(() => {
21184
21271
  });
21185
21272
 
21186
21273
  // src/server/dev-page-imports.ts
21187
- import { dirname as dirname7, isAbsolute as isAbsolute4, resolve as resolve8 } from "path";
21274
+ import { dirname as dirname6, isAbsolute as isAbsolute4, resolve as resolve7 } from "path";
21188
21275
  import { fileURLToPath as fileURLToPath3, pathToFileURL } from "url";
21189
21276
  function toImportSpecifier(filePath) {
21190
21277
  return filePath.replaceAll("\\", "/");
@@ -21211,7 +21298,7 @@ function pinJsxRuntime(source, loader) {
21211
21298
  if (!runtime || loader === "ts") {
21212
21299
  return source;
21213
21300
  }
21214
- const pragma = `/** @jsxImportSource ${pathToFileURL(dirname7(runtime)).href} */ `;
21301
+ const pragma = `/** @jsxImportSource ${pathToFileURL(dirname6(runtime)).href} */ `;
21215
21302
  const shebangEnd = source.startsWith("#!") ? source.indexOf(`
21216
21303
  `) + 1 : 0;
21217
21304
  return shebangEnd > 0 ? `${source.slice(0, shebangEnd)}${pragma}${source.slice(shebangEnd)}` : `${pragma}${source}`;
@@ -21277,7 +21364,7 @@ var init_dev_page_imports = __esm(() => {
21277
21364
 
21278
21365
  // src/server/dev-page-plugin.ts
21279
21366
  import { statSync as statSync4 } from "fs";
21280
- import { dirname as dirname8, isAbsolute as isAbsolute5 } from "path";
21367
+ import { dirname as dirname7, isAbsolute as isAbsolute5 } from "path";
21281
21368
  function getSourceLoader(filePath) {
21282
21369
  return SCRIPT_FILE_FILTER.test(filePath) ? detectLoaderFromPath(filePath) : null;
21283
21370
  }
@@ -21361,7 +21448,7 @@ function transformDevSource(raw, filePath, options) {
21361
21448
  const serverSource = split?.contract ?? isomorphicSource;
21362
21449
  let result = options.rewriteRelativeImports ? rewriteRelativeImportsWithVersion(serverSource, filePath, true) : serverSource;
21363
21450
  if (options.rewriteBareImports) {
21364
- result = rewriteBareImports(result, dirname8(filePath), loader);
21451
+ result = rewriteBareImports(result, dirname7(filePath), loader);
21365
21452
  }
21366
21453
  result = rewriteSingletonImports(result, loader);
21367
21454
  return pinJsxRuntime(result, loader);
@@ -21498,9 +21585,9 @@ var init_dev_page_plugin = __esm(() => {
21498
21585
 
21499
21586
  // src/plugin/route-modules.ts
21500
21587
  import { existsSync as existsSync8, readFileSync as readFileSync6, realpathSync as realpathSync3, statSync as statSync5 } from "fs";
21501
- import { dirname as dirname9, isAbsolute as isAbsolute6, join as join6, relative as relative8, sep as sep2 } from "path";
21588
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join5, relative as relative6, sep as sep2 } from "path";
21502
21589
  function validateRouteParams(path, schemas) {
21503
- const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? segment : segment.slice(1));
21590
+ const pathParams = path.split("/").filter((segment) => segment === "*" || segment.startsWith(":")).map((segment) => segment === "*" ? SPLAT_PARAM : segment.slice(1).replace(OPTIONAL_MARK, ""));
21504
21591
  if (pathParams.length === 0) {
21505
21592
  return;
21506
21593
  }
@@ -21520,18 +21607,18 @@ function routeModuleCache() {
21520
21607
  return cache;
21521
21608
  }
21522
21609
  function findPackageRoot(sourcePath) {
21523
- const fallback = dirname9(sourcePath);
21610
+ const fallback = dirname8(sourcePath);
21524
21611
  let directory = fallback;
21525
- while (dirname9(directory) !== directory) {
21526
- if (existsSync8(join6(directory, "package.json"))) {
21612
+ while (dirname8(directory) !== directory) {
21613
+ if (existsSync8(join5(directory, "package.json"))) {
21527
21614
  return directory;
21528
21615
  }
21529
- directory = dirname9(directory);
21616
+ directory = dirname8(directory);
21530
21617
  }
21531
- return existsSync8(join6(directory, "package.json")) ? directory : fallback;
21618
+ return existsSync8(join5(directory, "package.json")) ? directory : fallback;
21532
21619
  }
21533
21620
  function isWithinDirectory(path, directory) {
21534
- const relativePath = relative8(directory, path);
21621
+ const relativePath = relative6(directory, path);
21535
21622
  return relativePath === "" || !(relativePath.startsWith("..") || isAbsolute6(relativePath));
21536
21623
  }
21537
21624
  function isFurinPackageImport(specifier) {
@@ -21549,8 +21636,8 @@ function resolveRouteModuleImports(dependencyPath, packageRoot) {
21549
21636
  continue;
21550
21637
  }
21551
21638
  try {
21552
- const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname9(dependencyPath)));
21553
- if (isAbsolute6(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative8(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
21639
+ const resolvedImport = realpathSync3.native(Bun.resolveSync(imported.path, dirname8(dependencyPath)));
21640
+ if (isAbsolute6(resolvedImport) && isWithinDirectory(resolvedImport, packageRoot) && !relative6(packageRoot, resolvedImport).split(sep2).includes("node_modules")) {
21554
21641
  resolvedImports.push(resolvedImport);
21555
21642
  }
21556
21643
  } catch {}
@@ -21582,19 +21669,99 @@ function collectRouteModuleDependencies(sourcePath) {
21582
21669
  function routeModuleDependencies(sourcePath) {
21583
21670
  return routeModuleCache().get(sourcePath)?.dependencies ?? collectRouteModuleDependencies(sourcePath);
21584
21671
  }
21585
- var ROUTE_MODULE_CACHE_SYMBOL;
21672
+ var ROUTE_MODULE_CACHE_SYMBOL, OPTIONAL_MARK;
21586
21673
  var init_route_modules = __esm(() => {
21587
21674
  init_lang_detect();
21675
+ init_patterns();
21588
21676
  ROUTE_MODULE_CACHE_SYMBOL = Symbol.for("@teyik0/furin/route-module-cache");
21677
+ OPTIONAL_MARK = /\?$/;
21678
+ });
21679
+
21680
+ // src/plugin/route-tree.ts
21681
+ import { existsSync as existsSync9 } from "fs";
21682
+ import { resolve as resolve8 } from "path";
21683
+ function instanceKey(instance) {
21684
+ return `${resolve8(instance.pagesDir)}\x00${instance.prefix}`;
21685
+ }
21686
+ function routeModuleSpecifier(instance) {
21687
+ return `@teyik0/furin/routes?instance=${Bun.hash(instanceKey(instance)).toString(16)}`;
21688
+ }
21689
+ function routeId(instanceId, id) {
21690
+ const encodedId = Array.from(new TextEncoder().encode(id), (byte) => byte.toString(16).padStart(2, "0")).join("");
21691
+ return `_route_${instanceId}_${encodedId}`;
21692
+ }
21693
+ function relativePrefix(pattern, parentPattern) {
21694
+ const own = pattern === "/" ? "" : pattern;
21695
+ const parent = parentPattern === "/" ? "" : parentPattern;
21696
+ if (!own.startsWith(parent)) {
21697
+ throw new Error(`[furin] Route pattern "${pattern}" does not extend its layout's "${parentPattern}".`);
21698
+ }
21699
+ return own.slice(parent.length);
21700
+ }
21701
+ function buildRouteTree(instance, instanceId) {
21702
+ const { routes } = scanRouteManifest(instance);
21703
+ const byPath = new Map(routes.map((route) => [route.sourcePath, route]));
21704
+ const root = { children: [], layout: undefined, pages: [], prefix: "" };
21705
+ const nodes = new Map([[undefined, root]]);
21706
+ const parentPattern = (route) => route.parentPath === undefined ? "/" : byPath.get(route.parentPath)?.pattern ?? "/";
21707
+ const ensureNode = (sourcePath) => {
21708
+ const existing = nodes.get(sourcePath);
21709
+ if (existing) {
21710
+ return existing;
21711
+ }
21712
+ const layout = sourcePath === undefined ? undefined : byPath.get(sourcePath);
21713
+ if (!layout) {
21714
+ return root;
21715
+ }
21716
+ const prefix = relativePrefix(layout.pattern, parentPattern(layout));
21717
+ const node = {
21718
+ children: [],
21719
+ layout: {
21720
+ id: routeId(instanceId, layout.id),
21721
+ path: "",
21722
+ prefix,
21723
+ sourcePath: resolve8(layout.sourcePath)
21724
+ },
21725
+ pages: [],
21726
+ prefix
21727
+ };
21728
+ nodes.set(sourcePath, node);
21729
+ ensureNode(layout.parentPath).children.push(node);
21730
+ return node;
21731
+ };
21732
+ for (const route of routes) {
21733
+ if (route.kind === "layout") {
21734
+ ensureNode(route.sourcePath);
21735
+ continue;
21736
+ }
21737
+ ensureNode(route.parentPath).pages.push({
21738
+ id: routeId(instanceId, route.id),
21739
+ path: route.pattern,
21740
+ prefix: relativePrefix(route.pattern, parentPattern(route)),
21741
+ sourcePath: resolve8(route.sourcePath)
21742
+ });
21743
+ }
21744
+ return root;
21745
+ }
21746
+ function routeSnapshotSourcePaths(instance) {
21747
+ const { boundaries, rootPath, routes } = scanRouteManifest(instance);
21748
+ return [
21749
+ ...existsSync9(rootPath) ? [rootPath] : [],
21750
+ ...routes.map(({ sourcePath }) => sourcePath),
21751
+ ...boundaries.flatMap(({ errorPath, notFoundPath }) => [errorPath, notFoundPath].filter((path) => path !== undefined))
21752
+ ].map((path) => resolve8(path)).toSorted((left, right) => left.localeCompare(right));
21753
+ }
21754
+ var init_route_tree = __esm(() => {
21755
+ init_route_manifest();
21589
21756
  });
21590
21757
 
21591
21758
  // src/plugin/dev-routes.ts
21592
- import { existsSync as existsSync9, readFileSync as readFileSync7, statSync as statSync6, watch } from "fs";
21593
- import { dirname as dirname10, relative as relative9, resolve as resolve9, sep as sep3 } from "path";
21759
+ import { existsSync as existsSync10, readFileSync as readFileSync7, statSync as statSync6, watch } from "fs";
21760
+ import { dirname as dirname9, relative as relative7, resolve as resolve9, sep as sep3 } from "path";
21594
21761
  import { Elysia as Elysia16 } from "elysia";
21595
21762
  function routeTopologySource(instance) {
21596
21763
  const pagesDir = resolve9(instance.pagesDir);
21597
- const paths = routeSnapshotSourcePaths(instance).map((path) => relative9(pagesDir, path).replaceAll("\\", "/"));
21764
+ const paths = routeSnapshotSourcePaths(instance).map((path) => relative7(pagesDir, path).replaceAll("\\", "/"));
21598
21765
  return `${JSON.stringify(paths)}
21599
21766
  `;
21600
21767
  }
@@ -21703,7 +21870,7 @@ function reportChangedSourceError(state, directory, filename) {
21703
21870
  return;
21704
21871
  }
21705
21872
  const sourcePath = resolve9(directory, String(filename));
21706
- if (!(SCRIPT_FILE_FILTER.test(sourcePath) && existsSync9(sourcePath))) {
21873
+ if (!(SCRIPT_FILE_FILTER.test(sourcePath) && existsSync10(sourcePath))) {
21707
21874
  return;
21708
21875
  }
21709
21876
  try {
@@ -21721,7 +21888,7 @@ function replaceSourceWatchers(state) {
21721
21888
  const directories = new Set;
21722
21889
  for (const path of routeDependencyPaths(state.instance)) {
21723
21890
  if (!(path === pagesDir || path.startsWith(`${pagesDir}${sep3}`))) {
21724
- directories.add(dirname10(path));
21891
+ directories.add(dirname9(path));
21725
21892
  }
21726
21893
  }
21727
21894
  const watchDirectory = (directory, recursive) => {
@@ -21873,27 +22040,20 @@ async function composableRouteApps(route) {
21873
22040
  };
21874
22041
  }
21875
22042
  async function composeRuntimeNode(node) {
21876
- const prefix = node.name && !isRouteGroup(node.name) ? `/${segmentPath(node.name)}` : "";
21877
- const { fileRoutes } = node;
21878
- const [layoutApps, indexRouteApps, fileRouteApps, childApps] = await Promise.all([
22043
+ const { pages, prefix } = node;
22044
+ const [layoutApps, pageApps, childApps] = await Promise.all([
21879
22045
  node.layout ? composableRouteApps(node.layout) : undefined,
21880
- node.indexRoute ? composableRouteApps(node.indexRoute) : undefined,
21881
- Promise.all(fileRoutes.map((route) => composableRouteApps(route))),
22046
+ Promise.all(pages.map((route) => composableRouteApps(route))),
21882
22047
  Promise.all(node.children.map((child) => composeRuntimeNode(child)))
21883
22048
  ]);
21884
22049
  const appScope = layoutApps?.app ?? new Elysia16;
21885
22050
  const shellScope = layoutApps?.shell ?? new Elysia16;
21886
- if (indexRouteApps) {
21887
- appScope.use(new Elysia16({ prefix: "" }).use(indexRouteApps.app));
21888
- shellScope.use(new Elysia16({ prefix: "" }).use(indexRouteApps.shell));
21889
- }
21890
- for (const [index, route] of fileRoutes.entries()) {
21891
- const routeApps = fileRouteApps[index];
22051
+ for (const [index, route] of pages.entries()) {
22052
+ const routeApps = pageApps[index];
21892
22053
  if (routeApps) {
21893
- const segment = route.path.slice(route.path.lastIndexOf("/") + 1);
21894
- appScope.use(new Elysia16({ prefix: `/${segment}` }).use(routeApps.app));
22054
+ appScope.use(new Elysia16({ prefix: route.prefix }).use(routeApps.app));
21895
22055
  if (route.path !== "/*") {
21896
- shellScope.use(new Elysia16({ prefix: `/${segment}` }).use(routeApps.shell));
22056
+ shellScope.use(new Elysia16({ prefix: route.prefix }).use(routeApps.shell));
21897
22057
  }
21898
22058
  }
21899
22059
  }
@@ -21910,7 +22070,7 @@ async function composeRuntimeInstance(instance) {
21910
22070
  await Promise.resolve().then(() => init_dev_page_plugin());
21911
22071
  registerDevPagePlugin();
21912
22072
  const instanceId = Bun.hash(instanceKey(instance)).toString(16);
21913
- return composeRuntimeNode(buildRouteTree(instance.pagesDir, instanceId));
22073
+ return composeRuntimeNode(buildRouteTree(instance, instanceId));
21914
22074
  }
21915
22075
  function registerDevRoutesPlugin(instances) {
21916
22076
  for (const instance of instances) {
@@ -21939,7 +22099,6 @@ var DEV_ROUTE_WATCHERS_SYMBOL, DEV_ROUTE_WATCHER_OWNERS_SYMBOL, DEV_ROUTE_RECONC
21939
22099
  var init_dev_routes = __esm(() => {
21940
22100
  init_define_route();
21941
22101
  init_lang_detect();
21942
- init_patterns();
21943
22102
  init_source_version();
21944
22103
  init_route_modules();
21945
22104
  init_route_tree();
@@ -21949,11 +22108,8 @@ var init_dev_routes = __esm(() => {
21949
22108
  });
21950
22109
 
21951
22110
  // src/plugin/route-config.ts
21952
- import { existsSync as existsSync10, readFileSync as readFileSync8, writeFileSync } from "fs";
21953
- import { basename as basename3, join as join7, relative as relative10, resolve as resolve10 } from "path";
21954
- function withoutExtension(path) {
21955
- return path.replace(EXTENSION_RE, "");
21956
- }
22111
+ import { existsSync as existsSync11, readFileSync as readFileSync8, writeFileSync } from "fs";
22112
+ import { relative as relative8, resolve as resolve10 } from "path";
21957
22113
  function propertyName(key) {
21958
22114
  if (key?.type === "Identifier") {
21959
22115
  return key.name;
@@ -22034,9 +22190,9 @@ function position2(source, offset) {
22034
22190
  function issueAt(file, parsed, node, message) {
22035
22191
  return { file, ...position2(parsed.source, node.start), message };
22036
22192
  }
22037
- function checkKey(file, instance, parsed) {
22193
+ function checkKey(file, route, parsed) {
22038
22194
  const { config, head, id } = parsed.route;
22039
- const expected = fileRouteId(instance, file);
22195
+ const expected = route.id;
22040
22196
  if (!id) {
22041
22197
  return issueAt(file, parsed, head, `defineRoute() must name this file. Its id is "${expected}":
22042
22198
  defineRoute("${expected}")`);
@@ -22065,21 +22221,21 @@ function suggestedMode(route, isRoot) {
22065
22221
  }
22066
22222
  return route.methods.has("loader") || route.methods.has("requestLoader") ? "ssr" : "ssg";
22067
22223
  }
22068
- function checkFactory(file, instance, parsed) {
22224
+ function checkFactory(file, manifestRoute, parsed) {
22069
22225
  const { route } = parsed;
22070
- const isRoot = withoutExtension(file) === join7(instance.pagesDir, "root");
22226
+ const isRoot = manifestRoute === undefined;
22071
22227
  if (isRoot === route.isRootFactory) {
22072
22228
  return;
22073
22229
  }
22074
22230
  const mode = suggestedMode(route, isRoot);
22075
22231
  if (isRoot) {
22076
- return issueAt(file, parsed, route.head, `root.tsx must use defineRootRoute(), which has no parent layout:
22232
+ return issueAt(file, parsed, route.head, `The root layout must use defineRootRoute(), which has no parent layout:
22077
22233
  import { defineRootRoute } from "@teyik0/furin";
22078
22234
  export const route = defineRootRoute().config({ mode: "${mode}" })`);
22079
22235
  }
22080
- return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for root.tsx. Use defineRoute with this file's id:
22236
+ return issueAt(file, parsed, route.head, `defineRootRoute() is reserved for the root layout. Use defineRoute with this file's id:
22081
22237
  import { defineRoute } from "@teyik0/furin";
22082
- export const route = defineRoute("${fileRouteId(instance, file)}").config({ mode: "${mode}" })`);
22238
+ export const route = defineRoute("${manifestRoute.id}").config({ mode: "${mode}" })`);
22083
22239
  }
22084
22240
  function checkConfig(file, parsed) {
22085
22241
  const { route } = parsed;
@@ -22110,56 +22266,64 @@ function declaredParams(route) {
22110
22266
  }
22111
22267
  return new Set(keys.filter((key) => key !== undefined));
22112
22268
  }
22113
- function undeclaredSegments(file, pagesDir, declared) {
22114
- return withoutExtension(relative10(pagesDir, file)).split(PATH_SEPARATOR_RE).flatMap((segment) => {
22115
- const dynamic = parseDynamicRouteSegment(segment, file);
22116
- return dynamic ? [{ key: dynamic.catchAll ? "*" : dynamic.name, segment }] : [];
22117
- }).filter(({ key }) => declared !== true && !declared.has(key));
22269
+ function undeclaredParams(route, declared) {
22270
+ return route.params.filter(({ name }) => declared !== true && !declared.has(name));
22118
22271
  }
22119
- function paramsSchema(segments) {
22120
- const fields = segments.map(({ key }) => `${IDENTIFIER_RE.test(key) ? key : JSON.stringify(key)}: t.String()`);
22272
+ function paramsSchema(params) {
22273
+ const fields = params.map(({ name, optional }) => `${IDENTIFIER_RE.test(name) ? name : JSON.stringify(name)}: ${optional ? "t.Optional(t.String())" : "t.String()"}`);
22121
22274
  return `params: t.Object({ ${fields.join(", ")} })`;
22122
22275
  }
22123
- function checkParams(file, pagesDir, parsed) {
22124
- const missing = undeclaredSegments(file, pagesDir, declaredParams(parsed.route));
22276
+ function checkParams(file, route, parsed) {
22277
+ const missing = undeclaredParams(route, declaredParams(parsed.route));
22125
22278
  if (missing.length === 0) {
22126
22279
  return;
22127
22280
  }
22128
22281
  const plural = missing.length > 1;
22129
22282
  const tImport = parsed.imports.get("t")?.specifier === "elysia" ? "" : `
22130
22283
  import { t } from "elysia";`;
22131
- return issueAt(file, parsed, parsed.route.config ?? parsed.route.head, `The URL segment${plural ? "s" : ""} ${missing.map(({ segment }) => segment).join(", ")} ${plural ? "are" : "is"} missing from this page's params schema. Each page declares every dynamic segment of its path, including those of its layouts. Add to config():${tImport}
22284
+ return issueAt(file, parsed, parsed.route.config ?? parsed.route.head, `The path param${plural ? "s" : ""} ${missing.map(({ name }) => name).join(", ")} ${plural ? "are" : "is"} missing from this page's params schema. Each page declares every dynamic segment of its path, including those of its layouts. Add to config():${tImport}
22132
22285
  ${paramsSchema(missing)}`);
22133
22286
  }
22134
- function checkRoute(file, instance, parsed) {
22135
- const factory = checkFactory(file, instance, parsed);
22287
+ function checkBoundaryMethods(file, instance, parsed) {
22288
+ const method = ["error", "notFound"].find((name) => parsed.route.methods.has(name));
22289
+ if (instance.style !== "nextjs" || method === undefined) {
22290
+ return;
22291
+ }
22292
+ const convention = method === "error" ? "an error.tsx" : "a not-found.tsx";
22293
+ return issueAt(file, parsed, parsed.route.head, `.${method}() is the TanStack style. In the nextjs style, default-export the component from ${convention} next to this route.`);
22294
+ }
22295
+ function checkRoute(file, instance, route, parsed) {
22296
+ const factory = checkFactory(file, route, parsed);
22136
22297
  if (factory) {
22137
22298
  return [factory];
22138
22299
  }
22139
- const isLayout = basename3(withoutExtension(file)) === "_route";
22140
22300
  return [
22141
22301
  checkConfig(file, parsed),
22142
- parsed.route.isRootFactory ? undefined : checkKey(file, instance, parsed),
22302
+ route === undefined ? undefined : checkKey(file, route, parsed),
22143
22303
  checkMode(file, parsed),
22144
- parsed.route.isRootFactory || isLayout ? undefined : checkParams(file, instance.pagesDir, parsed)
22304
+ route === undefined || route.kind === "layout" ? undefined : checkParams(file, route, parsed),
22305
+ checkBoundaryMethods(file, instance, parsed)
22145
22306
  ];
22146
22307
  }
22147
- function routeFiles(pagesDir) {
22148
- const root = join7(pagesDir, "root.tsx");
22149
- return [
22150
- ...existsSync10(root) ? [root] : [],
22151
- ...routeSourcePaths({ pagesDir, prefix: "" })
22152
- ].toSorted((left, right) => left.localeCompare(right));
22308
+ function routeFiles(manifest) {
22309
+ const files = manifest.routes.map((route) => [
22310
+ resolve10(route.sourcePath),
22311
+ route
22312
+ ]);
22313
+ if (existsSync11(manifest.rootPath)) {
22314
+ files.push([resolve10(manifest.rootPath), undefined]);
22315
+ }
22316
+ return files.toSorted(([left], [right]) => left.localeCompare(right));
22153
22317
  }
22154
- function validateRouteConfig({ pagesDir, prefix }) {
22155
- const instance = { pagesDir: resolve10(pagesDir), prefix };
22156
- return routeFiles(instance.pagesDir).flatMap((file) => {
22318
+ function validateRouteConfig(spec) {
22319
+ const instance = { ...spec, pagesDir: resolve10(spec.pagesDir) };
22320
+ return routeFiles(scanRouteManifest(instance)).flatMap(([file, route]) => {
22157
22321
  const parsed = parseRoute(file);
22158
- return parsed ? checkRoute(file, instance, parsed).filter((issue) => issue !== undefined) : [];
22322
+ return parsed ? checkRoute(file, instance, route, parsed).filter((issue) => issue !== undefined) : [];
22159
22323
  });
22160
22324
  }
22161
22325
  function displayPath2(file) {
22162
- const projected = relative10(process.cwd(), file).replaceAll("\\", "/");
22326
+ const projected = relative8(process.cwd(), file).replaceAll("\\", "/");
22163
22327
  return projected.startsWith("../") ? file : projected;
22164
22328
  }
22165
22329
  function formatRouteConfigIssue(issue) {
@@ -22192,30 +22356,32 @@ function createRouteConfigReporter(instance, store) {
22192
22356
  });
22193
22357
  };
22194
22358
  }
22195
- function scaffoldTemplate(file, instance) {
22196
- if (withoutExtension(file) === join7(instance.pagesDir, "root")) {
22359
+ function scaffoldTemplate(route) {
22360
+ if (route === undefined) {
22197
22361
  return ROOT_TEMPLATE;
22198
22362
  }
22199
- const isLayout = basename3(withoutExtension(file)) === "_route";
22200
- const params = undeclaredSegments(file, instance.pagesDir, new Set);
22363
+ const isLayout = route.kind === "layout";
22364
+ const { params } = route;
22201
22365
  return `import { defineRoute } from "@teyik0/furin";${params.length > 0 ? `
22202
22366
  import { t } from "elysia";` : ""}
22203
22367
 
22204
- export const route = defineRoute("${fileRouteId(instance, file)}")
22368
+ export const route = defineRoute("${route.id}")
22205
22369
  .config({ mode: "${isLayout ? "ssr" : "ssg"}"${params.length > 0 ? `, ${paramsSchema(params)}` : ""} })
22206
22370
  .${isLayout ? "layout(({ children }) => children)" : "page(() => null)"};
22207
22371
  `;
22208
22372
  }
22209
- function scaffoldEmptyRoutes({ pagesDir, prefix }) {
22210
- const instance = { pagesDir: resolve10(pagesDir), prefix };
22373
+ function scaffoldEmptyRoutes(spec) {
22374
+ const instance = { ...spec, pagesDir: resolve10(spec.pagesDir) };
22211
22375
  const written = [];
22212
- for (const file of routeFiles(instance.pagesDir).filter((path) => readSource(path)?.trim() === "")) {
22213
- writeFileSync(file, scaffoldTemplate(file, instance));
22214
- written.push(file);
22376
+ for (const [file, route] of routeFiles(scanRouteManifest(instance))) {
22377
+ if (readSource(file)?.trim() === "") {
22378
+ writeFileSync(file, scaffoldTemplate(route));
22379
+ written.push(file);
22380
+ }
22215
22381
  }
22216
22382
  return written;
22217
22383
  }
22218
- var EXTENSION_RE, IDENTIFIER_RE, PATH_SEPARATOR_RE, ROUTE_CONFIG_DIAGNOSTIC = "route config", ROOT_TEMPLATE = `import { defineRootRoute, HeadContent, Scripts } from "@teyik0/furin";
22384
+ var IDENTIFIER_RE, ROUTE_CONFIG_DIAGNOSTIC = "route config", ROOT_TEMPLATE = `import { defineRootRoute, HeadContent, Scripts } from "@teyik0/furin";
22219
22385
 
22220
22386
  export const route = defineRootRoute()
22221
22387
  .config({ mode: "ssr" })
@@ -22233,13 +22399,10 @@ export const route = defineRootRoute()
22233
22399
  `;
22234
22400
  var init_route_config = __esm(() => {
22235
22401
  init_lang_detect();
22236
- init_patterns();
22237
22402
  init_parser();
22238
22403
  init_route_chains();
22239
- init_route_tree();
22240
- EXTENSION_RE = /\.(?:[cm]?[jt]sx?)$/;
22404
+ init_route_manifest();
22241
22405
  IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/;
22242
- PATH_SEPARATOR_RE = /[\\/]/;
22243
22406
  });
22244
22407
 
22245
22408
  // src/build/route-metadata.ts
@@ -22274,13 +22437,13 @@ var init_route_metadata = __esm(() => {
22274
22437
  });
22275
22438
 
22276
22439
  // src/rsc/build/paths.ts
22277
- import { dirname as dirname11, join as join8 } from "path";
22440
+ import { dirname as dirname10, join as join6 } from "path";
22278
22441
  import { fileURLToPath as fileURLToPath4 } from "url";
22279
22442
  var SOURCE_DIR, CLIENT_REFERENCE_RUNTIME_PATH, BUNDLED_CLIENT_CODEC_PATH;
22280
22443
  var init_paths = __esm(() => {
22281
- SOURCE_DIR = dirname11(fileURLToPath4(import.meta.resolve("@teyik0/furin/rsc")));
22282
- CLIENT_REFERENCE_RUNTIME_PATH = join8(SOURCE_DIR, "rsc/client-references.ts");
22283
- BUNDLED_CLIENT_CODEC_PATH = join8(SOURCE_DIR, "rsc/bundled-client-codec.ts");
22444
+ SOURCE_DIR = dirname10(fileURLToPath4(import.meta.resolve("@teyik0/furin/rsc")));
22445
+ CLIENT_REFERENCE_RUNTIME_PATH = join6(SOURCE_DIR, "rsc/client-references.ts");
22446
+ BUNDLED_CLIENT_CODEC_PATH = join6(SOURCE_DIR, "rsc/bundled-client-codec.ts");
22284
22447
  });
22285
22448
 
22286
22449
  // src/shared/route-map.ts
@@ -22310,8 +22473,8 @@ ${body}
22310
22473
  }
22311
22474
 
22312
22475
  // src/build/route-types.ts
22313
- import { existsSync as existsSync11, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync2 } from "fs";
22314
- import { extname as extname3, join as join9, relative as relative11, resolve as resolve11 } from "path";
22476
+ import { existsSync as existsSync12, readFileSync as readFileSync9, renameSync, writeFileSync as writeFileSync2 } from "fs";
22477
+ import { extname as extname3, join as join7, relative as relative9, resolve as resolve11 } from "path";
22315
22478
  function tagKeyToPropertyName(tag) {
22316
22479
  return /^[$A-Z_a-z][$\w]*$/.test(tag) ? tag : JSON.stringify(tag);
22317
22480
  }
@@ -22322,38 +22485,19 @@ function tagToStringLiteral(tag) {
22322
22485
  function importSpecifier(path, projectRoot) {
22323
22486
  const extension = extname3(path);
22324
22487
  const sourcePath = extension ? path.slice(0, -extension.length) : path;
22325
- const relativePath = relative11(projectRoot, sourcePath).replaceAll("\\", "/");
22488
+ const relativePath = relative9(projectRoot, sourcePath).replaceAll("\\", "/");
22326
22489
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
22327
22490
  }
22328
- function fileRouteEntries({ pagesDir, prefix }, projectRoot) {
22329
- const pages = resolve11(pagesDir);
22330
- const files = routeSourcePaths({ pagesDir: pages, prefix }).map((path) => {
22331
- const relativePath = relative11(pages, path).replaceAll("\\", "/");
22332
- const segments = relativePath.split("/");
22333
- const base = (segments.pop() ?? "").slice(0, -extname3(path).length);
22334
- return { base, path, relativePath, segments };
22335
- });
22336
- const layouts = new Map(files.filter(({ base }) => base === "_route").map((file) => [file.segments.join("/"), file.path]));
22337
- return files.map(({ base, path, relativePath, segments }) => {
22338
- const isLayout = base === "_route";
22339
- let parent = join9(pages, "root.tsx");
22340
- for (let depth = isLayout ? segments.length - 1 : segments.length;depth > 0; depth -= 1) {
22341
- const layout = layouts.get(segments.slice(0, depth).join("/"));
22342
- if (layout) {
22343
- parent = layout;
22344
- break;
22345
- }
22346
- }
22347
- const pathParams = [...segments, base].flatMap((segment) => {
22348
- const dynamic = parseDynamicRouteSegment(segment, path);
22349
- return dynamic ? [dynamic.catchAll ? '"*": string' : `${dynamic.name}: string`] : [];
22350
- });
22351
- const id = fileRouteId({ pagesDir: pages, prefix }, path);
22352
- const pattern = filePathToPattern(isLayout ? segments.concat("index").join("/") : relativePath);
22491
+ function fileRouteEntries(instance, projectRoot) {
22492
+ const { prefix } = instance;
22493
+ const manifest = scanRouteManifest({ ...instance, pagesDir: resolve11(instance.pagesDir) });
22494
+ return manifest.routes.map(({ id, kind, params, parentPath, pattern }) => {
22495
+ const parent = parentPath ?? manifest.rootPath;
22496
+ const pathParams = params.map(({ name, optional }) => `${name}${optional ? "?" : ""}: string`);
22353
22497
  return {
22354
22498
  id,
22355
22499
  lines: ` ${JSON.stringify(id)}: {
22356
- kind: "${isLayout ? "layout" : "page"}";
22500
+ kind: "${kind}";
22357
22501
  pattern: ${JSON.stringify(`${prefix}${pattern === "/" ? "" : pattern}` || "/")};
22358
22502
  parent: typeof import(${JSON.stringify(importSpecifier(parent, projectRoot))}).route;
22359
22503
  pathParams: {${pathParams.length > 0 ? ` ${pathParams.join("; ")} ` : ""}};
@@ -22392,8 +22536,8 @@ import "@teyik0/furin/routes";
22392
22536
 
22393
22537
  ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapDeclaration(entries)}${tagBlock}
22394
22538
  `;
22395
- const typesPath = join9(projectRoot, "furin-env.d.ts");
22396
- const existing = existsSync11(typesPath) ? readFileSync9(typesPath, "utf8") : "";
22539
+ const typesPath = join7(projectRoot, "furin-env.d.ts");
22540
+ const existing = existsSync12(typesPath) ? readFileSync9(typesPath, "utf8") : "";
22397
22541
  if (content === existing) {
22398
22542
  return false;
22399
22543
  }
@@ -22403,8 +22547,7 @@ ${apps === undefined ? "" : fileRoutesDeclaration(apps, projectRoot)}${routeMapD
22403
22547
  return true;
22404
22548
  }
22405
22549
  var init_route_types = __esm(() => {
22406
- init_route_tree();
22407
- init_patterns();
22550
+ init_route_manifest();
22408
22551
  });
22409
22552
 
22410
22553
  // src/build/shared.ts
@@ -22419,8 +22562,8 @@ var init_shared2 = __esm(() => {
22419
22562
  });
22420
22563
 
22421
22564
  // src/build/hydrate.ts
22422
- import { existsSync as existsSync12, mkdirSync, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
22423
- import { dirname as dirname12, join as join10 } from "path";
22565
+ import { existsSync as existsSync13, mkdirSync, readFileSync as readFileSync10, writeFileSync as writeFileSync3 } from "fs";
22566
+ import { join as join8 } from "path";
22424
22567
  function generateClientReferenceEntry(boundaries) {
22425
22568
  if (boundaries.length === 0) {
22426
22569
  return "";
@@ -22472,11 +22615,13 @@ function hydrateEntry(routes, rootLayout, basePath, clientLogging, modulePathKey
22472
22615
  continue;
22473
22616
  }
22474
22617
  const parts = [`depth: ${seg.depth}`];
22618
+ const errorExport = seg.fromRoute ? "route.errorComponent" : "default";
22619
+ const notFoundExport = seg.fromRoute ? "route.notFoundComponent" : "default";
22475
22620
  if (errorIdent) {
22476
- parts.push(`error: ${errorIdent}.default`);
22621
+ parts.push(`error: ${errorIdent}.${errorExport}`);
22477
22622
  }
22478
22623
  if (notFoundIdent) {
22479
- parts.push(`notFound: ${notFoundIdent}.default`);
22624
+ parts.push(`notFound: ${notFoundIdent}.${notFoundExport}`);
22480
22625
  }
22481
22626
  if (seg.depth === 0 && seg.path.replaceAll("\\", "/") !== rootDirectory) {
22482
22627
  parts.push("isRoot: false");
@@ -22819,8 +22964,8 @@ function releaseDevRouteTypes(projectRoot, prefix) {
22819
22964
  function writeDevRouteTypes(projectRoot, prefix, app) {
22820
22965
  const apps = devRouteTypesApps.get(projectRoot) ?? new Map;
22821
22966
  devRouteTypesApps.set(projectRoot, apps.set(prefix, app));
22822
- const live = [...apps].filter(([, { pagesDir }]) => existsSync12(pagesDir));
22823
- return writeRouteTypes(live.find(([appPrefix]) => appPrefix === "")?.[1].routes ?? [], projectRoot, live.map(([appPrefix, { pagesDir }]) => ({ pagesDir, prefix: appPrefix })));
22967
+ const live = [...apps].filter(([, { pagesDir }]) => existsSync13(pagesDir));
22968
+ return writeRouteTypes(live.find(([appPrefix]) => appPrefix === "")?.[1].routes ?? [], projectRoot, live.map(([appPrefix, { pagesDir, style }]) => ({ pagesDir, prefix: appPrefix, style })));
22824
22969
  }
22825
22970
  function writeDevFiles(routes, {
22826
22971
  outDir,
@@ -22828,30 +22973,31 @@ function writeDevFiles(routes, {
22828
22973
  basePath,
22829
22974
  clientLogging,
22830
22975
  clientBoundaries,
22976
+ pages,
22831
22977
  prefix
22832
22978
  }, projectRoot, serverSourceVersion) {
22833
- if (!existsSync12(outDir)) {
22979
+ if (!existsSync13(outDir)) {
22834
22980
  mkdirSync(outDir, { recursive: true });
22835
22981
  }
22836
22982
  const serverVersion = serverSourceVersion === undefined ? "" : `
22837
22983
  if (import.meta.hot) import.meta.hot.data.furinServerSourceVersion = ${JSON.stringify(serverSourceVersion)};
22838
22984
  `;
22839
22985
  const hydrateCode = generateClientReferenceEntry(clientBoundaries ?? []) + generateHydrateEntry(routes, rootLayout, basePath, clientLogging) + serverVersion;
22840
- const hydratePath = join10(outDir, "_hydrate.tsx");
22841
- const existingHydrate = existsSync12(hydratePath) ? readFileSync10(hydratePath, "utf8") : "";
22986
+ const hydratePath = join8(outDir, "_hydrate.tsx");
22987
+ const existingHydrate = existsSync13(hydratePath) ? readFileSync10(hydratePath, "utf8") : "";
22842
22988
  let changed = false;
22843
22989
  if (hydrateCode !== existingHydrate) {
22844
22990
  writeFileSync3(hydratePath, hydrateCode);
22845
22991
  changed = true;
22846
22992
  }
22847
22993
  const indexHtml = generateIndexHtml();
22848
- const indexPath = join10(outDir, "index.html");
22849
- const existingIndex = existsSync12(indexPath) ? readFileSync10(indexPath, "utf8") : "";
22994
+ const indexPath = join8(outDir, "index.html");
22995
+ const existingIndex = existsSync13(indexPath) ? readFileSync10(indexPath, "utf8") : "";
22850
22996
  if (indexHtml !== existingIndex) {
22851
22997
  writeFileSync3(indexPath, indexHtml);
22852
22998
  changed = true;
22853
22999
  }
22854
- changed = writeDevRouteTypes(projectRoot, prefix, { pagesDir: dirname12(rootLayout), routes }) || changed;
23000
+ changed = writeDevRouteTypes(projectRoot, prefix, { ...pages, routes }) || changed;
22855
23001
  if (changed) {
22856
23002
  console.log("[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)");
22857
23003
  }
@@ -23144,7 +23290,7 @@ var init_discover = __esm(() => {
23144
23290
 
23145
23291
  // src/plugin/hmr-dependencies.ts
23146
23292
  import { readFileSync as readFileSync11 } from "fs";
23147
- import { dirname as dirname13, isAbsolute as isAbsolute7, resolve as resolve12 } from "path";
23293
+ import { dirname as dirname11, isAbsolute as isAbsolute7, resolve as resolve12 } from "path";
23148
23294
  function hmrDependencySignature(imports, filename) {
23149
23295
  const routePath = resolve12(filename);
23150
23296
  const visited = new Set;
@@ -23153,7 +23299,7 @@ function hmrDependencySignature(imports, filename) {
23153
23299
  if (specifier === "furin" || specifier.startsWith("furin/") || specifier === "@teyik0/furin" || specifier.startsWith("@teyik0/furin/")) {
23154
23300
  return true;
23155
23301
  }
23156
- const path = Bun.resolveSync(specifier, dirname13(importer));
23302
+ const path = Bun.resolveSync(specifier, dirname11(importer));
23157
23303
  if (path === routePath) {
23158
23304
  return false;
23159
23305
  }
@@ -23320,21 +23466,18 @@ var exports_runtime = {};
23320
23466
  __export(exports_runtime, {
23321
23467
  createDevRuntime: () => createDevRuntime
23322
23468
  });
23323
- import { existsSync as existsSync13, readFileSync as readFileSync12 } from "fs";
23324
- import { basename as basename4, dirname as dirname14, join as join11, resolve as resolve13 } from "path";
23469
+ import { existsSync as existsSync14, readFileSync as readFileSync12 } from "fs";
23470
+ import { join as join9, resolve as resolve13 } from "path";
23325
23471
  import { staticPlugin as staticPlugin2 } from "@elysia/static";
23326
23472
  import { Elysia as Elysia17, file as file2 } from "elysia";
23327
- function wrapsRoute(sourcePath, routePath) {
23328
- if (!LAYOUT_FILE_RE.test(basename4(sourcePath))) {
23329
- return false;
23330
- }
23331
- const directory = dirname14(sourcePath).replaceAll("\\", "/");
23332
- return routePath.replaceAll("\\", "/").startsWith(`${directory}/`);
23473
+ function wrapsRoute(sourcePath, route) {
23474
+ const normalized = sourcePath.replaceAll("\\", "/");
23475
+ return route.layouts.some(({ path }) => path.replaceAll("\\", "/") === normalized);
23333
23476
  }
23334
23477
  function repairedDevelopmentRoutes(snapshot, changedSources, graph) {
23335
23478
  const patterns = new Set;
23336
23479
  for (const route of snapshot.routes) {
23337
- if (changedSources.some((sourcePath) => route.path === sourcePath || snapshot.root.path === sourcePath || graph.dependsOn(route.path, sourcePath) || wrapsRoute(sourcePath, route.path))) {
23480
+ if (changedSources.some((sourcePath) => route.path === sourcePath || snapshot.root.path === sourcePath || graph.dependsOn(route.path, sourcePath) || wrapsRoute(sourcePath, route))) {
23338
23481
  patterns.add(route.pattern);
23339
23482
  }
23340
23483
  }
@@ -23354,9 +23497,9 @@ function ownerAddsRouteHooks(app, owner) {
23354
23497
  const mounted = anchor && owner.routes.find((route) => route.method === anchor.method && route.handler === anchor.handler && route.path.endsWith(anchor.path));
23355
23498
  return mounted !== undefined && handlerPhaseHookCount(mounted.hooks) !== handlerPhaseHookCount(anchor?.hooks);
23356
23499
  }
23357
- async function loadDevelopmentRoutes(resolvedPagesDir) {
23500
+ async function loadDevelopmentRoutes(routeInstance) {
23358
23501
  await Promise.resolve().then(() => init_discovery());
23359
- return scanPages(resolvedPagesDir);
23502
+ return scanPages(routeInstance);
23360
23503
  }
23361
23504
  function createDevelopmentRouteSnapshot(instance, root, routes) {
23362
23505
  const searchRoutes = createSearchRouteMetadata(routes);
@@ -23367,7 +23510,7 @@ function createDevelopmentRouteSnapshot(instance, root, routes) {
23367
23510
  routes
23368
23511
  };
23369
23512
  }
23370
- async function createDevRuntime(instance, resolvedPagesDir, options) {
23513
+ async function createDevRuntime(instance, resolvedPagesDir, style, options) {
23371
23514
  const { prefix, syncPath } = instance;
23372
23515
  const { clientLogging, sync } = options;
23373
23516
  const cwd = process.cwd();
@@ -23383,7 +23526,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23383
23526
  registerDevPagePlugin();
23384
23527
  await Promise.resolve().then(() => init_dev_routes());
23385
23528
  await Promise.resolve().then(() => init_route_tree());
23386
- const routeInstance = { pagesDir: resolvedPagesDir, prefix };
23529
+ const routeInstance = { pagesDir: resolvedPagesDir, prefix, style };
23387
23530
  registerDevRoutesPlugin([routeInstance]);
23388
23531
  await Promise.resolve().then(() => init_route_config());
23389
23532
  const reportRouteConfig = createRouteConfigReporter(routeInstance, devDiagnosticStore(instance));
@@ -23391,7 +23534,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23391
23534
  const graph = devGraph(instance);
23392
23535
  const { nativeRoutesApp, root, routes } = await withInstance(instance, async () => {
23393
23536
  const { furinShell } = await import(routeModuleSpecifier(routeInstance));
23394
- const loaded = await loadDevelopmentRoutes(resolvedPagesDir);
23537
+ const loaded = await loadDevelopmentRoutes(routeInstance);
23395
23538
  return { nativeRoutesApp: furinShell, ...loaded };
23396
23539
  });
23397
23540
  const initialSnapshot = createDevelopmentRouteSnapshot(instance, root, routes);
@@ -23472,6 +23615,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23472
23615
  clientLogging: clientLogging ?? false,
23473
23616
  clientBoundaries,
23474
23617
  outDir: furinDir,
23618
+ pages: { pagesDir: resolvedPagesDir, style },
23475
23619
  publicPath: `${prefix}/_client/`,
23476
23620
  prefix,
23477
23621
  rootLayout: snapshot.root.path
@@ -23480,13 +23624,13 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23480
23624
  await writeCurrentDevFiles(initialSnapshot, []);
23481
23625
  graph.commit(initialSnapshot);
23482
23626
  reportRouteConfig();
23483
- const hmrEntry = (await import(join11(furinDir, "index.html"))).default;
23627
+ const hmrEntry = (await import(join9(furinDir, "index.html"))).default;
23484
23628
  const refreshDevelopmentRoutes = (changedSources) => withInstance(instance, async () => {
23485
23629
  invalidateStampedRouteModules();
23486
23630
  try {
23487
23631
  const previousSnapshot = currentSnapshot();
23488
23632
  const repaired = repairedDevelopmentRoutes(previousSnapshot, changedSources, graph);
23489
- const next = await loadDevelopmentRoutes(resolvedPagesDir);
23633
+ const next = await loadDevelopmentRoutes(routeInstance);
23490
23634
  const nextRoutes = next.routes.map((route) => route.routeChain.length > 0 ? route : {
23491
23635
  ...route,
23492
23636
  tags: previousSnapshot.routes.find((previous) => previous.path === route.path)?.tags
@@ -23510,7 +23654,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23510
23654
  }
23511
23655
  } catch (error) {
23512
23656
  publishDevDiagnostic(error, {
23513
- entryPath: join11(resolvedPagesDir, "root.tsx"),
23657
+ entryPath: currentSnapshot().root.path,
23514
23658
  phase: "import",
23515
23659
  route: "*"
23516
23660
  });
@@ -23518,7 +23662,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23518
23662
  }
23519
23663
  });
23520
23664
  const publicDir = resolve13(cwd, "public");
23521
- const publicExists = existsSync13(publicDir);
23665
+ const publicExists = existsSync14(publicDir);
23522
23666
  const publicAssets = publicExists ? await staticPlugin2({ assets: publicDir, prefix: "/public" }) : new Elysia17;
23523
23667
  const browserEvents = (await Promise.resolve().then(() => (init_plugin2(), exports_plugin))).createBrowserEventsPlugin({
23524
23668
  development: instance.development,
@@ -23539,7 +23683,7 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23539
23683
  reportRouteConfig();
23540
23684
  },
23541
23685
  onSourceError: (error, sourcePath) => {
23542
- const route = currentSnapshot().routes.find((candidate) => graph.dependsOn(candidate.path, sourcePath) || wrapsRoute(sourcePath, candidate.path));
23686
+ const route = currentSnapshot().routes.find((candidate) => graph.dependsOn(candidate.path, sourcePath) || wrapsRoute(sourcePath, candidate));
23543
23687
  withInstance(instance, () => publishDevDiagnostic(error, {
23544
23688
  entryPath: route ? route.path : sourcePath,
23545
23689
  phase: "transform",
@@ -23561,12 +23705,12 @@ async function createDevRuntime(instance, resolvedPagesDir, options) {
23561
23705
  routeTopologyWatcher?.close();
23562
23706
  routeTopologyWatcher = undefined;
23563
23707
  watcherOwner = undefined;
23564
- }).get("/_bun_hmr_entry/index.html", hmrEntry).get("/_bun_hmr_entry", hmrEntry).use(options.requestHooks).use(publicAssets).get("/favicon.ico", publicExists ? file2(join11(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(browserEvents).use(createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
23708
+ }).get("/_bun_hmr_entry/index.html", hmrEntry).get("/_bun_hmr_entry", hmrEntry).use(options.requestHooks).use(publicAssets).get("/favicon.ico", publicExists ? file2(join9(publicDir, "favicon.ico")) : () => new Response(null, { status: 404 })).use(browserEvents).use(createDevDiagnosticPlugin(devDiagnosticStore(instance), instance, async () => {
23565
23709
  await routeTopologyWatcher?.refresh();
23566
23710
  })).use(createInstrumentationPlugin(() => currentSnapshot().routes, syncPath))
23567
23711
  };
23568
23712
  }
23569
- var LAYOUT_FILE_RE, HANDLER_PHASE_HOOKS;
23713
+ var HANDLER_PHASE_HOOKS;
23570
23714
  var init_runtime2 = __esm(() => {
23571
23715
  init_prefix();
23572
23716
  init_dev_loader();
@@ -23576,13 +23720,12 @@ var init_runtime2 = __esm(() => {
23576
23720
  init_hmr();
23577
23721
  init_patterns();
23578
23722
  init_schemas();
23579
- LAYOUT_FILE_RE = /^_route\.[cm]?[jt]sx?$/;
23580
23723
  HANDLER_PHASE_HOOKS = ["transform", "beforeHandle", "afterHandle"];
23581
23724
  });
23582
23725
 
23583
23726
  // src/furin.ts
23584
23727
  init_define_route();
23585
- import { dirname as dirname15, resolve as resolve14 } from "path";
23728
+ import { dirname as dirname12, resolve as resolve14 } from "path";
23586
23729
  import { Elysia as Elysia18, NotFound as NotFound2 } from "elysia";
23587
23730
 
23588
23731
  // src/server/cache/invalidation.ts
@@ -23798,13 +23941,13 @@ function createLoggerPlugin(instance, logger, clientLogging) {
23798
23941
 
23799
23942
  // src/server/prod/runtime.ts
23800
23943
  import { existsSync as existsSync5 } from "fs";
23801
- import { join as join4 } from "path";
23944
+ import { join as join3 } from "path";
23802
23945
  import { Elysia as Elysia12 } from "elysia";
23803
23946
 
23804
23947
  // src/server/assets/client-dir.ts
23805
23948
  init_prefix();
23806
23949
  import { existsSync } from "fs";
23807
- import { basename as basename2, delimiter, dirname as dirname3, join, resolve as resolve4 } from "path";
23950
+ import { basename as basename2, delimiter, dirname as dirname2, join, resolve as resolve4 } from "path";
23808
23951
  import { fileURLToPath as fileURLToPath2 } from "url";
23809
23952
  function resolveClientDirFromArgv(prefix) {
23810
23953
  const dirName = clientDirNameForPrefix(prefix);
@@ -23816,7 +23959,7 @@ function resolveClientDirFromEnv(dirName) {
23816
23959
  return null;
23817
23960
  }
23818
23961
  const base = envClientDir.startsWith("/") ? envClientDir : resolve4(process.cwd(), envClientDir);
23819
- return dirName === "client" ? base : join(dirname3(base), dirName);
23962
+ return dirName === "client" ? base : join(dirname2(base), dirName);
23820
23963
  }
23821
23964
  function resolveClientDirFromModuleUrl(dirName) {
23822
23965
  try {
@@ -23828,7 +23971,7 @@ function resolveClientDirFromModuleUrl(dirName) {
23828
23971
  if (modulePath.includes("/$bunfs/")) {
23829
23972
  return null;
23830
23973
  }
23831
- const moduleClientDir = join(dirname3(modulePath), dirName);
23974
+ const moduleClientDir = join(dirname2(modulePath), dirName);
23832
23975
  if (existsSync(join(moduleClientDir, "index.html"))) {
23833
23976
  return moduleClientDir;
23834
23977
  }
@@ -23860,7 +24003,7 @@ function resolveClientDirFromCandidate(candidate, dirName) {
23860
24003
  }
23861
24004
  const absolute = candidate.startsWith("/") ? candidate : resolve4(process.cwd(), candidate);
23862
24005
  if (existsSync(absolute)) {
23863
- const clientDir = join(dirname3(absolute), dirName);
24006
+ const clientDir = join(dirname2(absolute), dirName);
23864
24007
  if (existsSync(join(clientDir, "index.html"))) {
23865
24008
  return clientDir;
23866
24009
  }
@@ -23875,7 +24018,7 @@ function resolveClientDirFromPath(candidate, dirName) {
23875
24018
  for (const dir of pathEntries) {
23876
24019
  const fullPath = join(dir, candidate);
23877
24020
  if (existsSync(fullPath)) {
23878
- const clientDir = join(dirname3(fullPath), dirName);
24021
+ const clientDir = join(dirname2(fullPath), dirName);
23879
24022
  if (existsSync(join(clientDir, "index.html"))) {
23880
24023
  return clientDir;
23881
24024
  }
@@ -23893,12 +24036,12 @@ function resolveFallbackClientDir(dirName) {
23893
24036
 
23894
24037
  // src/server/assets/production.ts
23895
24038
  import { existsSync as existsSync2 } from "fs";
23896
- import { dirname as dirname4, isAbsolute as isAbsolute3, join as join2, relative as relative5, resolve as resolve5, sep } from "path";
24039
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join2, relative as relative4, resolve as resolve5, sep } from "path";
23897
24040
  import { staticPlugin } from "@elysia/static";
23898
24041
  import { Elysia as Elysia11, file } from "elysia";
23899
24042
  function resolveEmbeddedAssetPath(directory, requestPath) {
23900
24043
  const assetPath = resolve5(directory, requestPath);
23901
- const pathFromDirectory = relative5(directory, assetPath);
24044
+ const pathFromDirectory = relative4(directory, assetPath);
23902
24045
  if (pathFromDirectory === "" || pathFromDirectory === ".." || pathFromDirectory.startsWith(`..${sep}`) || isAbsolute3(pathFromDirectory)) {
23903
24046
  return null;
23904
24047
  }
@@ -23950,7 +24093,7 @@ async function createProductionAssetsPlugin(ctx, embedded, clientDir) {
23950
24093
  if (embedded) {
23951
24094
  return createEmbeddedAssetsPlugin(embedded);
23952
24095
  }
23953
- const publicDir = join2(dirname4(clientDir), "public");
24096
+ const publicDir = join2(dirname3(clientDir), "public");
23954
24097
  const publicAssets = existsSync2(publicDir) ? new Elysia11().get("/favicon.ico", file(join2(publicDir, "favicon.ico"))).use(await staticPlugin({ assets: publicDir, prefix: "/public" })) : new Elysia11;
23955
24098
  return publicAssets.use(await staticPlugin({
23956
24099
  assets: clientDir,
@@ -23995,7 +24138,7 @@ async function createProductionBrowserEventsPlugin(sync, websocket, development)
23995
24138
  }
23996
24139
  async function setupProdTemplate(embedded, clientDir, instance) {
23997
24140
  if (embedded) {
23998
- const templatePath = join4(embedded.clientDir, "index.html");
24141
+ const templatePath = join3(embedded.clientDir, "index.html");
23999
24142
  if (!existsSync5(templatePath)) {
24000
24143
  throw new Error("[furin] Embedded app is missing its HTML template (index.html).");
24001
24144
  }
@@ -24003,7 +24146,7 @@ async function setupProdTemplate(embedded, clientDir, instance) {
24003
24146
  setProductionTemplateContent(html, instance);
24004
24147
  return;
24005
24148
  }
24006
- const templatePath = join4(clientDir, "index.html");
24149
+ const templatePath = join3(clientDir, "index.html");
24007
24150
  if (!existsSync5(templatePath)) {
24008
24151
  throw new Error("[furin] No pre-built assets found. Run `bun run build` first.");
24009
24152
  }
@@ -25449,6 +25592,10 @@ function AwaitInner({ resolve, children }) {
25449
25592
  // src/furin.ts
25450
25593
  init_defer();
25451
25594
  init_not_found();
25595
+ var DEFAULT_PAGES_DIRS = {
25596
+ nextjs: "src/app",
25597
+ tanstack: "src/routes"
25598
+ };
25452
25599
  function configurePageCache(instance, ctx, pageCache) {
25453
25600
  if (pageCache !== undefined && ctx?.adapter?.capabilities.publicCache === "platform") {
25454
25601
  throw new Error(`[furin] pageCache cannot be configured with the ${JSON.stringify(ctx.adapter.name)} adapter: its platform caches public SSG, ISR, and PPR pages.`);
@@ -25492,13 +25639,14 @@ async function createFurinApp(options) {
25492
25639
  logger,
25493
25640
  pageCache,
25494
25641
  pagesDir,
25642
+ style,
25495
25643
  sync
25496
25644
  } = options;
25497
25645
  const prefix = normalizePrefix(options.prefix);
25498
25646
  const cwd = process.cwd();
25499
- const paramPagesDir = resolve14(cwd, pagesDir ?? "src/pages");
25647
+ const paramPagesDir = resolve14(cwd, pagesDir ?? DEFAULT_PAGES_DIRS[style]);
25500
25648
  const ctx = getCompileContext(paramPagesDir, prefix);
25501
- const resolvedPagesDir = ctx?.rootPath ? dirname15(ctx.rootPath) : paramPagesDir;
25649
+ const resolvedPagesDir = ctx?.rootPath ? dirname12(ctx.rootPath) : paramPagesDir;
25502
25650
  const normalizedPagesDir = resolvedPagesDir.replaceAll("\\", "/");
25503
25651
  const instance = createInstance(prefix, normalizedPagesDir);
25504
25652
  instance.syncPath = resolveSyncPath(sync);
@@ -25521,7 +25669,7 @@ async function createFurinApp(options) {
25521
25669
  }),
25522
25670
  sync: sync || undefined
25523
25671
  };
25524
- const mode = development ? await (await Promise.resolve().then(() => (init_runtime2(), exports_runtime))).createDevRuntime(instance, resolvedPagesDir, modeOptions) : await createProdRuntime(instance, ctx, clientDir, modeOptions);
25672
+ const mode = development ? await (await Promise.resolve().then(() => (init_runtime2(), exports_runtime))).createDevRuntime(instance, resolvedPagesDir, style, modeOptions) : await createProdRuntime(instance, ctx, clientDir, modeOptions);
25525
25673
  const app = new Elysia18({
25526
25674
  name: `furin-${prefix}-${normalizedPagesDir}`,
25527
25675
  prefix: prefix || undefined,
@@ -25540,14 +25688,18 @@ async function createFurinApp(options) {
25540
25688
  }
25541
25689
  var mountedPrefixes = new WeakMap;
25542
25690
  async function furin(options) {
25691
+ if (options.style !== "nextjs" && options.style !== "tanstack") {
25692
+ throw new Error(`[furin] furin() requires style: "nextjs" or "tanstack", received ${JSON.stringify(options.style)}.`);
25693
+ }
25543
25694
  const registration = {
25544
- pagesDir: options?.pagesDir ?? "src/pages",
25545
- prefix: normalizePrefix(options?.prefix)
25695
+ pagesDir: options.pagesDir ?? DEFAULT_PAGES_DIRS[options.style],
25696
+ prefix: normalizePrefix(options.prefix),
25697
+ style: options.style
25546
25698
  };
25547
25699
  if (recordFurinRegistration(registration)) {
25548
25700
  return (parentApp) => parentApp;
25549
25701
  }
25550
- const { app, hasSync, instance } = await createFurinApp(options ?? {});
25702
+ const { app, hasSync, instance } = await createFurinApp(options);
25551
25703
  let mounted = false;
25552
25704
  return (parentApp) => {
25553
25705
  if (mounted) {