@teyik0/furin 0.9.0-alpha.0 → 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 (100) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/runtime-build.d.ts +7 -3
  3. package/dist/adapter/vercel.js +31 -6
  4. package/dist/build/client.d.ts +1 -1
  5. package/dist/build/entry-template.d.ts +3 -12
  6. package/dist/build/entry-template.ts +3 -15
  7. package/dist/build/hydrate.d.ts +6 -1
  8. package/dist/build/index.d.ts +1 -1
  9. package/dist/build/index.js +565 -401
  10. package/dist/build/route-metadata.d.ts +2 -2
  11. package/dist/build/route-types.d.ts +1 -1
  12. package/dist/build/types.d.ts +10 -4
  13. package/dist/cli/dev-worker.ts +10 -4
  14. package/dist/cli/index.js +624 -445
  15. package/dist/client/chunks/{client-xy6g38kx.js → client-a7spxfnn.js} +24 -5
  16. package/dist/client/chunks/{client-rjhxgt64.js → client-d9v49jwz.js} +1 -1
  17. package/dist/client/chunks/{client-k29262a4.js → client-rdxyrw11.js} +1 -1
  18. package/dist/client/define-route.d.ts +14 -0
  19. package/dist/client/internal/runtime-types.d.ts +8 -0
  20. package/dist/client/link.js +20 -17
  21. package/dist/client/router/link-utils.d.ts +3 -2
  22. package/dist/client/router/search/index.js +2 -2
  23. package/dist/client/router/types.d.ts +9 -3
  24. package/dist/client.js +22 -6
  25. package/dist/config.d.ts +4 -0
  26. package/dist/config.js +4 -1
  27. package/dist/define-route.d.ts +53 -12
  28. package/dist/furin.d.ts +13 -3
  29. package/dist/furin.js +815 -661
  30. package/dist/plugin/route-config.d.ts +3 -3
  31. package/dist/plugin/route-manifest.d.ts +46 -0
  32. package/dist/plugin/route-tree.d.ts +13 -29
  33. package/dist/routes.d.ts +2 -2
  34. package/dist/server/dev/runtime.d.ts +2 -1
  35. package/dist/server/internal.d.ts +6 -0
  36. package/dist/server/internal.js +97 -114
  37. package/dist/server/registrations.d.ts +4 -2
  38. package/dist/server/render/index.d.ts +0 -1
  39. package/dist/server/render/index.ts +0 -1
  40. package/dist/server/render/shell.d.ts +1 -13
  41. package/dist/server/render/shell.ts +1 -90
  42. package/dist/server/router/defined-route.d.ts +4 -0
  43. package/dist/server/router/discovery.d.ts +14 -4
  44. package/dist/server/router/hmr.d.ts +12 -12
  45. package/dist/server/router/patterns.d.ts +4 -12
  46. package/dist/server/router/types.d.ts +16 -1
  47. package/dist/server/static-export.js +128 -158
  48. package/dist/server/sync/drizzle/index.d.ts +8 -10
  49. package/dist/shared/not-found.d.ts +1 -1
  50. package/dist/shared/route-specificity.d.ts +10 -1
  51. package/package.json +8 -11
  52. package/src/adapter/package.ts +11 -37
  53. package/src/adapter/runtime-build.ts +5 -4
  54. package/src/adapter/static.ts +1 -1
  55. package/src/adapter/vercel.ts +2 -1
  56. package/src/build/client.ts +3 -3
  57. package/src/build/discover-pages-process.ts +1 -1
  58. package/src/build/elysia-aot.ts +2 -2
  59. package/src/build/entry-template.ts +3 -15
  60. package/src/build/hydrate.ts +12 -6
  61. package/src/build/index.ts +19 -9
  62. package/src/build/route-metadata.ts +15 -8
  63. package/src/build/route-types.ts +18 -43
  64. package/src/build/types.ts +12 -5
  65. package/src/cli/config.ts +6 -0
  66. package/src/cli/dev-worker.ts +10 -4
  67. package/src/cli/dev.ts +41 -26
  68. package/src/cli/index.ts +30 -14
  69. package/src/client/define-route.ts +29 -4
  70. package/src/client/internal/runtime-types.ts +8 -0
  71. package/src/client/link.tsx +21 -22
  72. package/src/client/router/context.ts +8 -7
  73. package/src/client/router/link-utils.ts +16 -8
  74. package/src/client/router/provider.tsx +5 -0
  75. package/src/client/router/types.ts +40 -14
  76. package/src/config.ts +5 -0
  77. package/src/define-route.ts +85 -16
  78. package/src/furin.ts +31 -7
  79. package/src/plugin/dev-routes.ts +8 -17
  80. package/src/plugin/route-config.ts +77 -62
  81. package/src/plugin/route-manifest.ts +437 -0
  82. package/src/plugin/route-modules.ts +6 -1
  83. package/src/plugin/route-registry.ts +7 -21
  84. package/src/plugin/route-tree.ts +71 -181
  85. package/src/routes.ts +2 -2
  86. package/src/server/dev/runtime.ts +16 -22
  87. package/src/server/internal.ts +4 -1
  88. package/src/server/registrations.ts +5 -2
  89. package/src/server/render/index.ts +0 -1
  90. package/src/server/render/shell.ts +1 -90
  91. package/src/server/render/static-params.ts +2 -10
  92. package/src/server/router/defined-route.ts +8 -0
  93. package/src/server/router/discovery.ts +237 -196
  94. package/src/server/router/hmr.ts +45 -63
  95. package/src/server/router/patterns.ts +41 -117
  96. package/src/server/router/types.ts +17 -1
  97. package/src/server/sync/drizzle/index.ts +18 -19
  98. package/src/shared/not-found.ts +1 -1
  99. package/src/shared/route-specificity.ts +34 -2
  100. package/src/shared/utils/index.ts +1 -1
@@ -1,7 +1,14 @@
1
1
  // biome-ignore-all lint/performance/noAwaitInLoops: route discovery walks filesystem entries sequentially for deterministic ordering
2
2
  import { existsSync } from "node:fs";
3
3
  import type { RuntimePage, RuntimeRoute } from "../../client/internal/runtime-types.ts";
4
- import { scanRouteManifest } from "../../plugin/route-tree.ts";
4
+ import {
5
+ type ManifestBoundary,
6
+ type ManifestRoute,
7
+ type RouteInstanceSpec,
8
+ type RouteManifest,
9
+ type RouteStyle,
10
+ scanRouteManifest,
11
+ } from "../../plugin/route-manifest.ts";
5
12
  import type { ErrorComponent } from "../../shared/error.ts";
6
13
  import type { NotFoundComponent } from "../../shared/not-found.ts";
7
14
  import { collectRouteChainFromRoute, validateRouteChain } from "../../shared/utils/index.ts";
@@ -10,7 +17,7 @@ import { type CompileContext, type CompiledModule, getCompileContext } from "../
10
17
  import { adaptDefinedLayout, adaptDefinedPage, isDefinedRouteTerminal } from "./defined-route.ts";
11
18
  import { resolveMode } from "./patterns.ts";
12
19
  import { routeModuleSourceVersion } from "./source-version.ts";
13
- import type { ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
20
+ import type { ResolvedLayout, ResolvedRoute, RootLayout, SegmentBoundary } from "./types.ts";
14
21
 
15
22
  export function isModuleNotFoundError(err: unknown): boolean {
16
23
  if (!err || (typeof err !== "object" && typeof err !== "string")) {
@@ -63,7 +70,9 @@ export function loadProdRoutes(ctx: CompileContext): {
63
70
  } {
64
71
  const rootExport = ctx.modules[ctx.rootPath]?.route;
65
72
  if (!isDefinedRouteTerminal(rootExport) || typeof rootExport.layout !== "function") {
66
- throw new Error("[furin] root.tsx: defineRootRoute().layout() not found in CompileContext.");
73
+ throw new Error(
74
+ `[furin] ${ctx.rootPath}: defineRootRoute().layout() not found in CompileContext.`
75
+ );
67
76
  }
68
77
  const rootRoute = adaptDefinedLayout(rootExport, undefined, ctx.rootPath);
69
78
 
@@ -75,28 +84,41 @@ export function loadProdRoutes(ctx: CompileContext): {
75
84
  }
76
85
 
77
86
  const root: RootLayout = {
78
- error: resolveModuleComponent(ctx.rootConventions?.errorPath),
79
- notFound: resolveModuleComponent(ctx.rootConventions?.notFoundPath),
87
+ error: rootRoute.errorComponent ?? resolveModuleComponent(ctx.rootConventions?.errorPath),
88
+ notFound:
89
+ rootRoute.notFoundComponent ?? resolveModuleComponent(ctx.rootConventions?.notFoundPath),
80
90
  path: ctx.rootPath,
81
91
  route: rootRoute,
82
92
  };
83
93
 
84
94
  const routes: ResolvedRoute[] = [];
85
95
  for (const { pattern, path, mode } of ctx.routes) {
86
- const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, path, root, ctx);
96
+ const meta = ctx.routeMetadata?.[path];
97
+ const layouts = meta?.layouts ?? [];
98
+ const page = resolveCompiledRuntimePage(ctx.modules[path] ?? {}, layouts, root, ctx);
87
99
  if (!page) {
88
100
  throw new Error(`[furin] ${path}: invalid page module in CompileContext.`);
89
101
  }
90
102
  const routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
91
103
  validateRouteChain(routeChain, root.route, path);
92
- const meta = ctx.routeMetadata?.[path];
93
- const boundaries = (meta?.segmentBoundaries ?? []).map((b) => ({
94
- ...b,
95
- error: resolveModuleComponent(b.errorPath),
96
- notFound: resolveModuleComponent(b.notFoundPath),
97
- })) as SegmentBoundary[];
104
+ const boundaries = (meta?.segmentBoundaries ?? []).map(
105
+ (boundary): SegmentBoundary => ({
106
+ ...boundary,
107
+ error: boundary.fromRoute
108
+ ? routeBoundaryComponent<ErrorComponent>(ctx, boundary.errorPath, "errorComponent")
109
+ : resolveModuleComponent(boundary.errorPath),
110
+ notFound: boundary.fromRoute
111
+ ? routeBoundaryComponent<NotFoundComponent>(
112
+ ctx,
113
+ boundary.notFoundPath,
114
+ "notFoundComponent"
115
+ )
116
+ : resolveModuleComponent(boundary.notFoundPath),
117
+ })
118
+ );
98
119
 
99
120
  routes.push({
121
+ layouts,
100
122
  mode,
101
123
  page,
102
124
  path,
@@ -112,62 +134,45 @@ export function loadProdRoutes(ctx: CompileContext): {
112
134
  return { root, routes };
113
135
  }
114
136
 
137
+ /** A TanStack-style boundary component, read from the route module's `.error()` / `.notFound()`. */
138
+ function routeBoundaryComponent<T>(
139
+ ctx: CompileContext,
140
+ modulePath: string | undefined,
141
+ field: "errorComponent" | "notFoundComponent"
142
+ ): T | undefined {
143
+ const route = modulePath ? ctx.modules[modulePath]?.route : undefined;
144
+ return isDefinedRouteTerminal(route) ? (route[field] as T | undefined) : undefined;
145
+ }
146
+
115
147
  function resolveCompiledRuntimePage(
116
148
  module: { route?: unknown },
117
- path: string,
149
+ layouts: readonly ResolvedLayout[],
118
150
  root: RootLayout,
119
151
  context: CompileContext
120
152
  ): RuntimePage | undefined {
121
153
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
122
154
  return;
123
155
  }
124
- const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
125
- const parent = resolveCompiledLayoutParent(path, pagesDir, root.route, context);
156
+ let parent = root.route;
157
+ for (const { path } of layouts) {
158
+ const layout = context.modules[path]?.route;
159
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
160
+ throw invalidNestedLayoutError(path);
161
+ }
162
+ parent = adaptDefinedLayout(layout, parent, path);
163
+ }
126
164
  return adaptDefinedPage(module.route, parent);
127
165
  }
128
166
 
129
167
  export function invalidNestedLayoutError(layoutPath: string): Error {
130
168
  return new Error(
131
- `[furin] ${layoutPath}: _route.tsx must export \`route = defineRoute(id).config({ mode }).layout(({ children }) => ...)\`, with the file's id. For example, in blog/_route.tsx:
132
- export const route = defineRoute("/blog/_route")
169
+ `[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:
170
+ export const route = defineRoute("/board")
133
171
  .config({ mode: "ssr" })
134
172
  .layout(({ children }) => <section>{children}</section>);`
135
173
  );
136
174
  }
137
175
 
138
- function resolveCompiledLayoutParent(
139
- pagePath: string,
140
- pagesDir: string,
141
- rootRoute: RuntimeRoute,
142
- context: CompileContext
143
- ): RuntimeRoute {
144
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
145
- if (pageDirectory.length <= pagesDir.length) {
146
- return rootRoute;
147
- }
148
- const segments = pageDirectory.slice(pagesDir.length + 1).split("/");
149
- let directory = pagesDir;
150
- let parent = rootRoute;
151
-
152
- for (const segment of segments) {
153
- directory = `${directory}/${segment}`;
154
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
155
- const layoutModule = context.modules[candidate];
156
- if (!layoutModule) {
157
- continue;
158
- }
159
- const layout = layoutModule.route;
160
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
161
- throw invalidNestedLayoutError(candidate);
162
- }
163
- parent = adaptDefinedLayout(layout, parent, candidate);
164
- break;
165
- }
166
- }
167
-
168
- return parent;
169
- }
170
-
171
176
  /**
172
177
  * Normalises OS-native path separators to POSIX "/" so the slash-based path
173
178
  * arithmetic in the scan (relative slicing, `lastIndexOf("/")`,
@@ -185,16 +190,31 @@ function routeRelativePath(pagesDir: string, absolutePath: string): string {
185
190
  return path.startsWith(`${dir}/`) ? path.slice(dir.length + 1) : path;
186
191
  }
187
192
 
188
- export async function scanPages(pagesDir: string): Promise<{
193
+ /** Layouts wrapping a manifest route, shallow → deep, the root excluded. */
194
+ export function manifestLayouts(manifest: RouteManifest, route: ManifestRoute): ResolvedLayout[] {
195
+ const byPath = new Map(manifest.routes.map((entry) => [entry.sourcePath, entry]));
196
+ const layouts: ResolvedLayout[] = [];
197
+ for (let parent = route.parentPath; parent !== undefined; ) {
198
+ const layout = byPath.get(parent);
199
+ if (!layout) {
200
+ break;
201
+ }
202
+ layouts.unshift({ path: layout.sourcePath, pattern: layout.pattern });
203
+ parent = layout.parentPath;
204
+ }
205
+ return layouts;
206
+ }
207
+
208
+ export async function scanPages(instance: RouteInstanceSpec): Promise<{
189
209
  root: RootLayout;
190
210
  routes: ResolvedRoute[];
191
211
  }> {
192
- // Normalise once at the entry point; scanRootLayout and scanPageFiles (which
193
- // also normalises every route-manifest path) then operate purely on
194
- // POSIX-separated paths.
195
- const dir = toPosixPath(pagesDir);
196
- const root = await scanRootLayout(dir);
197
- const routes = await scanPageFiles(dir, root);
212
+ // Normalise once at the entry point: the manifest and every lookup below
213
+ // operate purely on POSIX-separated paths.
214
+ const pagesDir = toPosixPath(instance.pagesDir);
215
+ const manifest = scanRouteManifest({ ...instance, pagesDir });
216
+ const root = await scanRootLayout(manifest, pagesDir, instance.style);
217
+ const routes = await scanPageFiles(manifest, pagesDir, instance.style, root);
198
218
  if (routes.some((route) => route.routeChain.some((entry) => entry.requestLoader))) {
199
219
  await annotateScannedRequestKeys(routes);
200
220
  }
@@ -219,12 +239,22 @@ const CONVENTION_EXAMPLES = {
219
239
  }`,
220
240
  } as const;
221
241
 
222
- export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
223
- const rootPath = `${pagesDir}/root.tsx`;
242
+ const ROOT_FILE_NAMES: { [Style in RouteStyle]: string } = {
243
+ nextjs: "layout.tsx",
244
+ tanstack: "__root.tsx",
245
+ };
246
+
247
+ export async function scanRootLayout(
248
+ manifest: RouteManifest,
249
+ pagesDir: string,
250
+ style: RouteStyle
251
+ ): Promise<RootLayout> {
252
+ const { rootPath } = manifest;
253
+ const rootFile = ROOT_FILE_NAMES[style];
224
254
  const ctx = getCompileContext();
225
255
  if (!(existsSync(rootPath) || ctx?.modules[rootPath])) {
226
256
  throw new Error(
227
- `[furin] root.tsx: not found in ${pagesDir}. Every pages directory needs a root layout:\n${ROOT_EXAMPLE}`
257
+ `[furin] ${rootFile}: not found in ${pagesDir}. Every pages directory needs a root layout:\n${ROOT_EXAMPLE}`
228
258
  );
229
259
  }
230
260
 
@@ -239,20 +269,29 @@ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
239
269
  const rootExport = mod.route;
240
270
  if (!isDefinedRouteTerminal(rootExport)) {
241
271
  throw new Error(
242
- `[furin] ${rootPath}: root.tsx must export \`route = defineRootRoute().config({ mode }).layout(...)\`:\n${ROOT_EXAMPLE}`
272
+ `[furin] ${rootPath}: ${rootFile} must export \`route = defineRootRoute().config({ mode }).layout(...)\`:\n${ROOT_EXAMPLE}`
243
273
  );
244
274
  }
245
275
 
246
276
  if (!rootExport.layout) {
247
277
  throw new Error(
248
- `[furin] ${rootPath}: root.tsx: defineRootRoute() must end with .layout(({ children }) => ...):\n${ROOT_EXAMPLE}`
278
+ `[furin] ${rootPath}: ${rootFile}: defineRootRoute() must end with .layout(({ children }) => ...):\n${ROOT_EXAMPLE}`
249
279
  );
250
280
  }
251
281
  const rootRoute = adaptDefinedLayout(rootExport, undefined, rootPath);
282
+ if (style === "tanstack") {
283
+ return {
284
+ error: rootRoute.errorComponent,
285
+ notFound: rootRoute.notFoundComponent,
286
+ path: rootPath,
287
+ route: rootRoute,
288
+ };
289
+ }
252
290
 
291
+ const rootBoundary = manifest.boundaries.find((boundary) => boundary.directory === pagesDir);
253
292
  const [notFoundEntry, errorEntry] = await Promise.all([
254
- loadConventionComponent<NotFoundComponent>(pagesDir, "not-found"),
255
- loadConventionComponent<ErrorComponent>(pagesDir, "error"),
293
+ loadConventionComponent<NotFoundComponent>(rootBoundary?.notFoundPath, "not-found"),
294
+ loadConventionComponent<ErrorComponent>(rootBoundary?.errorPath, "error"),
256
295
  ]);
257
296
  return {
258
297
  error: errorEntry?.component,
@@ -264,12 +303,7 @@ export async function scanRootLayout(pagesDir: string): Promise<RootLayout> {
264
303
  };
265
304
  }
266
305
 
267
- const CONVENTION_FILE_NAMES = ["not-found", "error"] as const;
268
- const SOURCE_MODULE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"] as const;
269
-
270
- export function getSourceModuleCandidates(dir: string, name: string): string[] {
271
- return SOURCE_MODULE_EXTENSIONS.map((ext) => `${dir}/${name}${ext}`);
272
- }
306
+ type ConventionName = "error" | "not-found";
273
307
 
274
308
  /**
275
309
  * Result of a convention-file lookup. The `path` is the absolute module path
@@ -282,55 +316,58 @@ interface ConventionLookup<T> {
282
316
  }
283
317
 
284
318
  async function loadConventionComponent<T>(
285
- dir: string,
286
- name: (typeof CONVENTION_FILE_NAMES)[number]
319
+ filePath: string | undefined,
320
+ name: ConventionName
287
321
  ): Promise<ConventionLookup<T> | undefined> {
322
+ if (filePath === undefined) {
323
+ return;
324
+ }
288
325
  const ctx = getCompileContext();
289
- for (const filePath of getSourceModuleCandidates(dir, name)) {
290
- if (existsSync(filePath) || ctx?.modules[filePath]) {
291
- const moduleSpecifier =
292
- isDevelopment() && existsSync(filePath)
293
- ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}`
294
- : filePath;
295
- const mod = (ctx?.modules[filePath] ?? (await import(moduleSpecifier))) as {
296
- default?: T;
297
- };
298
- if (mod.default) {
299
- return { component: mod.default, path: filePath };
300
- }
301
- const exportNames = Object.keys(mod).join(", ") || "none";
302
- throw new Error(
303
- `[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:\n${CONVENTION_EXAMPLES[name]}`
304
- );
305
- }
326
+ const moduleSpecifier =
327
+ isDevelopment() && existsSync(filePath)
328
+ ? `${filePath}?furin-server&t=${routeModuleSourceVersion(filePath)}`
329
+ : filePath;
330
+ const mod = (ctx?.modules[filePath] ?? (await import(moduleSpecifier))) as {
331
+ default?: T;
332
+ };
333
+ if (mod.default) {
334
+ return { component: mod.default, path: filePath };
306
335
  }
336
+ const exportNames = Object.keys(mod).join(", ") || "none";
337
+ throw new Error(
338
+ `[furin] ${filePath}: ${name}.tsx must default-export a React component (found exports: ${exportNames}). For example:\n${CONVENTION_EXAMPLES[name]}`
339
+ );
307
340
  }
308
341
 
309
- async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<ResolvedRoute[]> {
342
+ async function scanPageFiles(
343
+ manifest: RouteManifest,
344
+ pagesDir: string,
345
+ style: RouteStyle,
346
+ root: RootLayout
347
+ ): Promise<ResolvedRoute[]> {
310
348
  const routes: ResolvedRoute[] = [];
311
- const notFoundCache = new Map<string, ConventionLookup<NotFoundComponent> | undefined>();
312
- const errorCache = new Map<string, ConventionLookup<ErrorComponent> | undefined>();
349
+ const boundaryCache = new Map<string, Promise<SegmentBoundary>>();
313
350
 
314
- for (const { pattern, sourcePath } of scanRouteManifest(pagesDir)) {
315
- if (pattern === undefined) {
351
+ for (const manifestRoute of manifest.routes) {
352
+ if (manifestRoute.kind !== "page") {
316
353
  continue;
317
354
  }
318
- const absolutePath = toPosixPath(sourcePath);
355
+ const { pattern } = manifestRoute;
356
+ const absolutePath = manifestRoute.sourcePath;
319
357
  const relativePath = routeRelativePath(pagesDir, absolutePath);
358
+ const layouts = manifestLayouts(manifest, manifestRoute);
320
359
 
321
- const segmentBoundaries = await collectSegmentBoundaries(
322
- absolutePath,
323
- pagesDir,
324
- notFoundCache,
325
- errorCache
326
- );
360
+ const directoryBoundaries =
361
+ style === "nextjs"
362
+ ? await collectSegmentBoundaries(absolutePath, manifest.boundaries, boundaryCache)
363
+ : [];
327
364
 
328
365
  if (isDevelopment()) {
329
- const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, pagesDir);
330
- devRoute.segmentBoundaries = alignSegmentBoundaryDepths(
331
- segmentBoundaries,
332
- devRoute.routeChain
333
- );
366
+ const devRoute = await buildDevRoute(absolutePath, relativePath, pattern, root, layouts);
367
+ devRoute.segmentBoundaries =
368
+ style === "nextjs"
369
+ ? alignSegmentBoundaryDepths(directoryBoundaries, devRoute.routeChain)
370
+ : routeDefinedBoundaries(root, devRoute.routeChain, devRoute.page, absolutePath);
334
371
  routes.push(devRoute);
335
372
  continue;
336
373
  }
@@ -339,7 +376,7 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
339
376
  const pageMod = (ctx?.modules[absolutePath] ?? (await import(absolutePath))) as {
340
377
  route?: unknown;
341
378
  };
342
- const page = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
379
+ const page = await resolveRuntimePage(pageMod, layouts, root.route);
343
380
  if (!page) {
344
381
  throw new Error(`[furin] ${relativePath}: no valid defineRoute(id).page() export found`);
345
382
  }
@@ -349,12 +386,16 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
349
386
  validateRouteChain(routeChain, root.route, relativePath);
350
387
 
351
388
  routes.push({
389
+ layouts,
352
390
  mode: resolveMode(page, routeChain),
353
391
  page,
354
392
  path: absolutePath,
355
393
  pattern,
356
394
  routeChain,
357
- segmentBoundaries: alignSegmentBoundaryDepths(segmentBoundaries, routeChain),
395
+ segmentBoundaries:
396
+ style === "nextjs"
397
+ ? alignSegmentBoundaryDepths(directoryBoundaries, routeChain)
398
+ : routeDefinedBoundaries(root, routeChain, page, absolutePath),
358
399
  tags: collectRouteTags(routeChain, page),
359
400
  });
360
401
  }
@@ -362,53 +403,75 @@ async function scanPageFiles(pagesDir: string, root: RootLayout): Promise<Resolv
362
403
  return routes;
363
404
  }
364
405
 
406
+ /**
407
+ * TanStack-style boundaries come from `.error()` / `.notFound()` on the
408
+ * routes themselves. A route's boundary sits in its parent's outlet, so it
409
+ * also catches the route's own failure: depth = its chain index - 1. The
410
+ * root's sits inside the root layout (depth 0). `path` is the route file, so
411
+ * only the root's boundary is the root directory's.
412
+ */
413
+ export function routeDefinedBoundaries(
414
+ root: RootLayout,
415
+ routeChain: readonly RuntimeRoute[],
416
+ page: RuntimePage,
417
+ pagePath: string
418
+ ): SegmentBoundary[] {
419
+ const entries: { depth: number; path: string | undefined; route: RuntimeRoute | RuntimePage }[] =
420
+ [
421
+ { depth: 0, path: root.path, route: routeChain[0] ?? root.route },
422
+ // The chain ends with the page's own entry: layouts sit between it and the root.
423
+ ...routeChain
424
+ .slice(1, -1)
425
+ .map((route, index) => ({ depth: index, path: route.sourcePath, route })),
426
+ { depth: Math.max(routeChain.length - 2, 0), path: pagePath, route: page },
427
+ ];
428
+ const pagesDir = root.path.slice(0, root.path.lastIndexOf("/"));
429
+ return entries.flatMap(({ depth, path, route }): SegmentBoundary[] => {
430
+ const { errorComponent, notFoundComponent } = route;
431
+ if (path === undefined || !(errorComponent || notFoundComponent)) {
432
+ return [];
433
+ }
434
+ return [
435
+ {
436
+ depth,
437
+ error: errorComponent,
438
+ errorPath: errorComponent ? path : undefined,
439
+ fromRoute: true,
440
+ notFound: notFoundComponent,
441
+ notFoundPath: notFoundComponent ? path : undefined,
442
+ path: path === root.path ? pagesDir : path,
443
+ },
444
+ ];
445
+ });
446
+ }
447
+
365
448
  async function resolveRuntimePage(
366
449
  module: { route?: unknown },
367
- absolutePath: string,
368
- pagesDir: string,
450
+ layouts: readonly ResolvedLayout[],
369
451
  rootRoute: RuntimeRoute
370
452
  ): Promise<RuntimePage | undefined> {
371
453
  if (!isDefinedRouteTerminal(module.route) || typeof module.route.page !== "function") {
372
454
  return;
373
455
  }
374
- const parent = await resolveDefinedLayoutParent(absolutePath, pagesDir, rootRoute);
456
+ const parent = await resolveDefinedLayoutParent(layouts, rootRoute);
375
457
  return adaptDefinedPage(module.route, parent);
376
458
  }
377
459
 
378
460
  async function resolveDefinedLayoutParent(
379
- pagePath: string,
380
- pagesDir: string,
461
+ layouts: readonly ResolvedLayout[],
381
462
  rootRoute: RuntimeRoute
382
463
  ): Promise<RuntimeRoute> {
383
- const pageDirectory = pagePath.slice(0, pagePath.lastIndexOf("/"));
384
- if (pageDirectory.length <= pagesDir.length) {
385
- return rootRoute;
386
- }
387
- const relativeDirectory = pageDirectory.slice(pagesDir.length + 1);
388
- const segments = relativeDirectory.split("/");
389
- let directory = pagesDir;
390
464
  let parent = rootRoute;
391
-
392
- for (const segment of segments) {
393
- directory = `${directory}/${segment}`;
394
- for (const candidate of getSourceModuleCandidates(directory, "_route")) {
395
- if (!existsSync(candidate)) {
396
- continue;
397
- }
398
- const layoutModule = (await import(
399
- isDevelopment()
400
- ? `${candidate}?furin-server&t=${routeModuleSourceVersion(candidate)}`
401
- : candidate
402
- )) as { route?: unknown };
403
- const layout = layoutModule.route;
404
- if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
405
- throw invalidNestedLayoutError(candidate);
406
- }
407
- parent = adaptDefinedLayout(layout, parent, candidate);
408
- break;
465
+ for (const { path } of layouts) {
466
+ const layoutModule = (await import(
467
+ isDevelopment() ? `${path}?furin-server&t=${routeModuleSourceVersion(path)}` : path
468
+ )) as { route?: unknown };
469
+ const layout = layoutModule.route;
470
+ if (!isDefinedRouteTerminal(layout) || typeof layout.layout !== "function") {
471
+ throw invalidNestedLayoutError(path);
409
472
  }
473
+ parent = adaptDefinedLayout(layout, parent, path);
410
474
  }
411
-
412
475
  return parent;
413
476
  }
414
477
 
@@ -432,66 +495,43 @@ function alignSegmentBoundaryDepths(
432
495
  }
433
496
 
434
497
  /**
435
- * Walks every directory from `pagesDir` down to the directory containing
436
- * `pageAbsolutePath` and records the OWN (not inherited) error.tsx /
437
- * not-found.tsx declared there. Directories without any convention file are
438
- * omitted so consumers can treat each entry as "a place where the user
439
- * authored a boundary on purpose".
440
- *
441
- * Uses the shared per-directory caches so sibling pages don't re-import the
442
- * same convention modules.
498
+ * The Next.js-style `error` / `not-found` boundaries of the directories from
499
+ * the pages root down to the page's own directory, shallow → deep. Each
500
+ * entry holds only the files declared IN that directory, never inherited.
501
+ * The cache shares the imported modules between sibling pages.
443
502
  */
444
503
  async function collectSegmentBoundaries(
445
504
  pageAbsolutePath: string,
446
- pagesDir: string,
447
- notFoundCache: Map<string, ConventionLookup<NotFoundComponent> | undefined>,
448
- errorCache: Map<string, ConventionLookup<ErrorComponent> | undefined>
505
+ boundaries: readonly ManifestBoundary[],
506
+ cache: Map<string, Promise<SegmentBoundary>>
449
507
  ): Promise<SegmentBoundary[]> {
450
508
  const pageDir = pageAbsolutePath.slice(0, pageAbsolutePath.lastIndexOf("/"));
451
-
452
- // Accumulate directories from shallow → deep starting at pagesDir.
453
- const dirs: string[] = [pagesDir];
454
- if (pageDir.length > pagesDir.length) {
455
- const relativeTail = pageDir.slice(pagesDir.length + 1); // skip leading "/"
456
- const parts = relativeTail.split("/");
457
- let acc = pagesDir;
458
- for (const part of parts) {
459
- acc = `${acc}/${part}`;
460
- dirs.push(acc);
461
- }
462
- }
463
-
464
- const boundaries: SegmentBoundary[] = [];
465
- for (let depth = 0; depth < dirs.length; depth += 1) {
466
- const dir = dirs[depth] as string;
467
-
468
- const [errorEntry, notFoundEntry] = await Promise.all([
469
- errorCache.has(dir)
470
- ? Promise.resolve(errorCache.get(dir))
471
- : loadConventionComponent<ErrorComponent>(dir, "error").then((r) => {
472
- errorCache.set(dir, r);
473
- return r;
474
- }),
475
- notFoundCache.has(dir)
476
- ? Promise.resolve(notFoundCache.get(dir))
477
- : loadConventionComponent<NotFoundComponent>(dir, "not-found").then((r) => {
478
- notFoundCache.set(dir, r);
479
- return r;
480
- }),
481
- ]);
482
- if (errorEntry || notFoundEntry) {
483
- boundaries.push({
484
- depth,
485
- error: errorEntry?.component,
486
- errorPath: errorEntry?.path,
487
- notFound: notFoundEntry?.component,
488
- notFoundPath: notFoundEntry?.path,
489
- path: dir,
490
- });
491
- }
492
- }
493
-
494
- return boundaries;
509
+ const enclosing = boundaries.filter(
510
+ ({ directory }) => pageDir === directory || pageDir.startsWith(`${directory}/`)
511
+ );
512
+ return await Promise.all(
513
+ enclosing.map((boundary) => {
514
+ const cached = cache.get(boundary.directory);
515
+ if (cached) {
516
+ return cached;
517
+ }
518
+ const loaded = Promise.all([
519
+ loadConventionComponent<ErrorComponent>(boundary.errorPath, "error"),
520
+ loadConventionComponent<NotFoundComponent>(boundary.notFoundPath, "not-found"),
521
+ ]).then(
522
+ ([errorEntry, notFoundEntry]): SegmentBoundary => ({
523
+ depth: 0,
524
+ error: errorEntry?.component,
525
+ errorPath: errorEntry?.path,
526
+ notFound: notFoundEntry?.component,
527
+ notFoundPath: notFoundEntry?.path,
528
+ path: boundary.directory,
529
+ })
530
+ );
531
+ cache.set(boundary.directory, loaded);
532
+ return loaded;
533
+ })
534
+ );
495
535
  }
496
536
 
497
537
  async function buildDevRoute(
@@ -499,7 +539,7 @@ async function buildDevRoute(
499
539
  relativePath: string,
500
540
  pattern: string,
501
541
  root: RootLayout,
502
- pagesDir: string
542
+ layouts: ResolvedLayout[]
503
543
  ): Promise<ResolvedRoute> {
504
544
  // Import via the virtual namespace (registerDevPagePlugin must be called first)
505
545
  // so page files stay out of --hot's module graph. We still extract the route
@@ -514,7 +554,7 @@ async function buildDevRoute(
514
554
  )) as {
515
555
  route?: unknown;
516
556
  };
517
- const resolvedPage = await resolveRuntimePage(pageMod, absolutePath, pagesDir, root.route);
557
+ const resolvedPage = await resolveRuntimePage(pageMod, layouts, root.route);
518
558
  if (resolvedPage) {
519
559
  page = resolvedPage;
520
560
  routeChain = collectRouteChainFromRoute(page._route as RuntimeRoute);
@@ -532,6 +572,7 @@ async function buildDevRoute(
532
572
  };
533
573
 
534
574
  return {
575
+ layouts,
535
576
  mode: page ? resolveMode(page, routeChain) : "ssr",
536
577
  // Still lazily re-imported on each request for fresh code.
537
578
  page: page ?? devStubPage,