@timber-js/app 0.2.0-alpha.244 → 0.2.0-alpha.245

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 (75) hide show
  1. package/dist/_chunks/{actions-D_LiN5xG.js → actions-C7_xl9iA.js} +9 -5
  2. package/dist/_chunks/actions-C7_xl9iA.js.map +1 -0
  3. package/dist/_chunks/als-registry-C-iwbtvI.js.map +1 -1
  4. package/dist/_chunks/{cli-check-BE9BnXwi.js → cli-check-CetL-6Us.js} +2 -2
  5. package/dist/_chunks/{cli-check-BE9BnXwi.js.map → cli-check-CetL-6Us.js.map} +1 -1
  6. package/dist/_chunks/{codegen-vaCyFyVN.js → codegen-BxJGInWa.js} +76 -20
  7. package/dist/_chunks/codegen-BxJGInWa.js.map +1 -0
  8. package/dist/_chunks/{convention-lint-DkSDlsPH.js → convention-lint-BWbKAV4x.js} +17 -9
  9. package/dist/_chunks/convention-lint-BWbKAV4x.js.map +1 -0
  10. package/dist/cli.js +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/native/rsc/manifest.json +1 -0
  13. package/dist/native/rsc/routing/descendant-params.js +28 -0
  14. package/dist/native/rsc/routing/descendant-params.js.map +1 -0
  15. package/dist/native/rsc/server/als-registry.js.map +1 -1
  16. package/dist/native/rsc/server/request-context.js +1 -1
  17. package/dist/native/rsc/server/request-context.js.map +1 -1
  18. package/dist/native/rsc/server/route-element-builder.js +3 -2
  19. package/dist/native/rsc/server/route-element-builder.js.map +1 -1
  20. package/dist/native/rsc/server/segment-lifetime/read-rule.js +7 -3
  21. package/dist/native/rsc/server/segment-lifetime/read-rule.js.map +1 -1
  22. package/dist/native/rsc/server/segment-lifetime/read-scope.js +3 -1
  23. package/dist/native/rsc/server/segment-lifetime/read-scope.js.map +1 -1
  24. package/dist/native/rsc/server/segment-lifetime/segment-key.js +2 -1
  25. package/dist/native/rsc/server/segment-lifetime/segment-key.js.map +1 -1
  26. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js +1 -1
  27. package/dist/native/rsc/server/segment-lifetime/slot-outlets.js.map +1 -1
  28. package/dist/native/ssr/server/als-registry.js.map +1 -1
  29. package/dist/native/ssr/server/request-context.js +1 -1
  30. package/dist/native/ssr/server/request-context.js.map +1 -1
  31. package/dist/native/ssr/server/segment-lifetime/read-rule.js +7 -3
  32. package/dist/native/ssr/server/segment-lifetime/read-rule.js.map +1 -1
  33. package/dist/native/ssr/server/segment-lifetime/read-scope.js.map +1 -1
  34. package/dist/routing/codegen-types.d.ts +9 -0
  35. package/dist/routing/codegen-types.d.ts.map +1 -1
  36. package/dist/routing/codegen.d.ts.map +1 -1
  37. package/dist/routing/descendant-params.d.ts +46 -0
  38. package/dist/routing/descendant-params.d.ts.map +1 -0
  39. package/dist/routing/index.js +1 -1
  40. package/dist/routing/route-options-lint.d.ts.map +1 -1
  41. package/dist/routing/route-options.d.ts +1 -1
  42. package/dist/routing/route-options.d.ts.map +1 -1
  43. package/dist/server/als-registry.d.ts +13 -0
  44. package/dist/server/als-registry.d.ts.map +1 -1
  45. package/dist/server/index.js +1 -1
  46. package/dist/server/internal.js +1 -1
  47. package/dist/server/internal.js.map +1 -1
  48. package/dist/server/route-element-builder.d.ts.map +1 -1
  49. package/dist/server/segment-lifetime/read-rule.d.ts +8 -1
  50. package/dist/server/segment-lifetime/read-rule.d.ts.map +1 -1
  51. package/dist/server/segment-lifetime/read-scope.d.ts +8 -2
  52. package/dist/server/segment-lifetime/read-scope.d.ts.map +1 -1
  53. package/dist/server/segment-lifetime/segment-key.d.ts +7 -2
  54. package/dist/server/segment-lifetime/segment-key.d.ts.map +1 -1
  55. package/dist/server/segment-lifetime/slot-outlets.d.ts.map +1 -1
  56. package/dist/server/types.d.ts +3 -2
  57. package/dist/server/types.d.ts.map +1 -1
  58. package/docs/api/30-api-server.mdx +2 -2
  59. package/package.json +1 -1
  60. package/src/routing/codegen-types.ts +9 -0
  61. package/src/routing/codegen.ts +34 -20
  62. package/src/routing/descendant-params.ts +76 -0
  63. package/src/routing/route-options-lint.ts +28 -9
  64. package/src/routing/route-options.ts +3 -2
  65. package/src/server/als-registry.ts +13 -0
  66. package/src/server/request-context.ts +1 -1
  67. package/src/server/route-element-builder.ts +9 -2
  68. package/src/server/segment-lifetime/read-rule.ts +32 -3
  69. package/src/server/segment-lifetime/read-scope.ts +11 -2
  70. package/src/server/segment-lifetime/segment-key.ts +18 -3
  71. package/src/server/segment-lifetime/slot-outlets.ts +3 -1
  72. package/src/server/types.ts +3 -2
  73. package/dist/_chunks/actions-D_LiN5xG.js.map +0 -1
  74. package/dist/_chunks/codegen-vaCyFyVN.js.map +0 -1
  75. package/dist/_chunks/convention-lint-DkSDlsPH.js.map +0 -1
@@ -16,6 +16,61 @@ import { existsSync } from "node:fs";
16
16
  function buildSchemaParamType(p, fallback) {
17
17
  return `typeof schema['segmentParams'] extends Record<${JSON.stringify(p.bracketName)}, infer V> ? InferCodecType<V> : ${fallback ?? p.type}`;
18
18
  }
19
+ // src/routing/descendant-params.ts
20
+ /**
21
+ * The params a segment's `children` chain defines below it: what a layout may
22
+ * name in `key.segmentParams` besides the params on its path
23
+ * (design/53-segment-lifetime.md §"Keying on a descendant's param").
24
+ *
25
+ * Read by the build lint (`route-options-lint.ts`), codegen (`codegen.ts`) and
26
+ * the runtime read scope (`server/segment-lifetime/read-scope.ts`), so the three
27
+ * agree on what a layout can key.
28
+ *
29
+ * - **`children` only.** A slot's subtree is excluded at every depth: a
30
+ * main-chain layout reads the main route's params, so a name only a slot
31
+ * defines could never be present in what it reads.
32
+ * - **Intercepting directories count**, read through `effectiveUrlSegment`
33
+ * (`(.)[id]` defines `id`): a children-path interception publishes the
34
+ * intercepted params into the same store.
35
+ * - **Only params a page binds.** A param counts only when a `page` sits at or
36
+ * below the segment defining it: a layout never renders for a `route.ts`,
37
+ * or for a directory with no page, so a name only those define would never
38
+ * be present when the key is read.
39
+ * - **Memoized per node**, one post-order pass over the tree however many
40
+ * layouts ask. Keyed weakly on the node object, which the scanner (build)
41
+ * and the manifest (runtime) each build once.
42
+ */
43
+ var MEMO = /* @__PURE__ */ new WeakMap();
44
+ var RENDERS_PAGE = /* @__PURE__ */ new WeakMap();
45
+ /** Whether a page sits at or below `node` on its `children` chain. */
46
+ function rendersPage(node) {
47
+ let found = RENDERS_PAGE.get(node);
48
+ if (found === void 0) {
49
+ found = !!node.page || node.children.some(rendersPage);
50
+ RENDERS_PAGE.set(node, found);
51
+ }
52
+ return found;
53
+ }
54
+ /**
55
+ * Every param a segment on `node`'s `children` chain defines, at any depth,
56
+ * by name, with the segment that defines it (its bracket form, for codegen).
57
+ * Excludes `node`'s own param. A name defined in several branches appears
58
+ * once: the scanner already requires one bracket form per name across the
59
+ * tree (`validateUniqueBracketForms`).
60
+ */
61
+ function childrenChainParams(node) {
62
+ const memo = MEMO.get(node);
63
+ if (memo) return memo;
64
+ const params = /* @__PURE__ */ new Map();
65
+ for (const child of node.children) {
66
+ if (!rendersPage(child)) continue;
67
+ const identity = effectiveUrlSegment(child);
68
+ if (identity.paramName && !params.has(identity.paramName)) params.set(identity.paramName, identity);
69
+ for (const [name, deeper] of childrenChainParams(child)) if (!params.has(name)) params.set(name, deeper);
70
+ }
71
+ MEMO.set(node, params);
72
+ return params;
73
+ }
19
74
  // src/routing/link-codegen.ts
20
75
  /**
21
76
  * The `searchParams` prop type, emitted identically on every Link variant
@@ -255,11 +310,7 @@ function collectRoutes(node, ancestorParams, parentTreePath, routes, hasSchema,
255
310
  const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;
256
311
  const urlSegment = effectiveUrlSegment(node);
257
312
  const params = [...ancestorParams];
258
- if (urlSegment.paramName) params.push({
259
- name: urlSegment.paramName,
260
- bracketName: bracketNameForSegment(urlSegment),
261
- type: paramTypeForSegment(urlSegment.segmentType)
262
- });
313
+ if (urlSegment.paramName) params.push(paramEntry(urlSegment.paramName, urlSegment));
263
314
  const isPage = !!node.page;
264
315
  const isApiRoute = !!node.route;
265
316
  const hostsCode = !!node.layout || !!node.middleware || !!node.access;
@@ -268,6 +319,7 @@ function collectRoutes(node, ancestorParams, parentTreePath, routes, hasSchema,
268
319
  urlPath: node.urlPath,
269
320
  segmentPath: treePath || "/",
270
321
  params,
322
+ descendantParams: hostsCode ? [...childrenChainParams(node)].map(([name, segment]) => paramEntry(name, segment)) : [],
271
323
  isApiRoute,
272
324
  isRoutable: isPage || isApiRoute,
273
325
  isSlotRoute: insideSlot,
@@ -312,9 +364,13 @@ function dedupeRoutesByUrlPath(routes) {
312
364
  }
313
365
  return [...byPath.values()];
314
366
  }
315
- /**
316
- * Determine the TypeScript type for a segment's param.
317
- */
367
+ function paramEntry(name, segment) {
368
+ return {
369
+ name,
370
+ bracketName: bracketNameForSegment(segment),
371
+ type: paramTypeForSegment(segment.segmentType)
372
+ };
373
+ }
318
374
  /**
319
375
  * Derive the bracket key for schema/codegen lookup.
320
376
  * For bare segments like `[id]` this is the segmentName itself.
@@ -424,11 +480,12 @@ function formatDeclarationFile(routes, importBase, hasSchema, appDir) {
424
480
  lines.push("");
425
481
  const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);
426
482
  const dynamicRoutes = routes.filter((r) => r.params.length > 0);
427
- if (dynamicRoutes.length > 0) {
483
+ const serverRoutes = routes.filter((r) => r.params.length > 0 || r.descendantParams.length > 0);
484
+ if (serverRoutes.length > 0) {
428
485
  lines.push("declare module '@timber-js/app/server' {");
429
486
  if (hasSchema) lines.push(" import type { AllSegmentParams } from '@timber-js/app'");
430
- for (const route of dynamicRoutes) {
431
- const paramsType = formatParamsType(route.params, hasSchema);
487
+ for (const route of serverRoutes) {
488
+ const paramsType = formatParamsType(route.params, hasSchema, route.descendantParams);
432
489
  lines.push(` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`);
433
490
  }
434
491
  lines.push(hasSchema ? " export function getSegmentParams(): Partial<AllSegmentParams>" : " export function getSegmentParams(): Record<string, string | string[]>");
@@ -465,15 +522,14 @@ function formatDeclarationFile(routes, importBase, hasSchema, appDir) {
465
522
  return lines.join("\n");
466
523
  }
467
524
  /**
468
- * Format the params type for a route entry.
525
+ * Format the params type for a route entry. `optional` params (those a
526
+ * descendant defines) may be absent: `name?: T | undefined`.
469
527
  */
470
- function formatParamsType(params, hasSchema) {
471
- if (params.length === 0) return "{}";
472
- return `{ ${params.map((p) => {
473
- const codecType = hasSchema ? buildSchemaParamType(p) : p.type;
474
- return `${p.name}: ${codecType}`;
475
- }).join("; ")} }`;
528
+ function formatParamsType(params, hasSchema, optional = []) {
529
+ if (params.length === 0 && optional.length === 0) return "{}";
530
+ const codecType = (p) => hasSchema ? buildSchemaParamType(p) : p.type;
531
+ return `{ ${[...params.map((p) => `${p.name}: ${codecType(p)}`), ...optional.map((p) => `${p.name}?: (${codecType(p)}) | undefined`)].join("; ")} }`;
476
532
  }
477
- export { generateRouteMap as t };
533
+ export { childrenChainParams as n, generateRouteMap as t };
478
534
 
479
- //# sourceMappingURL=codegen-vaCyFyVN.js.map
535
+ //# sourceMappingURL=codegen-BxJGInWa.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codegen-BxJGInWa.js","names":[],"sources":["../../src/routing/codegen-shared.ts","../../src/routing/descendant-params.ts","../../src/routing/link-codegen.ts","../../src/routing/codegen.ts"],"sourcesContent":["/**\n * Shared codegen helpers — import-path computation and codec chain type\n * builders.\n *\n * Extracted from `codegen.ts` so `link-codegen.ts` can use the same\n * helpers without a cyclic import.\n */\n\nimport { relative, posix } from 'node:path';\nimport type { ParamEntry } from './codegen-types.ts';\n\n/**\n * Compute a relative import specifier for a codec/page file, stripping\n * the .ts/.tsx extension and resolving against the codegen output dir.\n */\nexport function codecImportPath(codecFilePath: string, importBase: string | undefined): string {\n const absPath = codecFilePath.replace(/\\.(ts|tsx)$/, '');\n if (importBase) {\n return './' + relative(importBase, absPath).replace(/\\\\/g, '/');\n }\n return './' + posix.basename(absPath);\n}\n\n/**\n * Build a TypeScript type expression for a single param using the global\n * schema's InferCodecType. Falls back to the param's base type when\n * schema doesn't declare this param (schemas are opt-in per key).\n *\n * Uses `infer` to extract the codec value rather than direct indexing\n * because TypeScript doesn't narrow index validity inside a conditional\n * type's true branch — `typeof schema.segmentParams[K]` produces TS2538\n * even when the condition proves K is a valid key. In .d.ts files that\n * error is suppressed and the type silently becomes `any`.\n */\nexport function buildSchemaParamType(p: ParamEntry, fallback?: string): string {\n const key = JSON.stringify(p.bracketName);\n const fb = fallback ?? p.type;\n return `typeof schema['segmentParams'] extends Record<${key}, infer V> ? InferCodecType<V> : ${fb}`;\n}\n","/**\n * The params a segment's `children` chain defines below it: what a layout may\n * name in `key.segmentParams` besides the params on its path\n * (design/53-segment-lifetime.md §\"Keying on a descendant's param\").\n *\n * Read by the build lint (`route-options-lint.ts`), codegen (`codegen.ts`) and\n * the runtime read scope (`server/segment-lifetime/read-scope.ts`), so the three\n * agree on what a layout can key.\n *\n * - **`children` only.** A slot's subtree is excluded at every depth: a\n * main-chain layout reads the main route's params, so a name only a slot\n * defines could never be present in what it reads.\n * - **Intercepting directories count**, read through `effectiveUrlSegment`\n * (`(.)[id]` defines `id`): a children-path interception publishes the\n * intercepted params into the same store.\n * - **Only params a page binds.** A param counts only when a `page` sits at or\n * below the segment defining it: a layout never renders for a `route.ts`,\n * or for a directory with no page, so a name only those define would never\n * be present when the key is read.\n * - **Memoized per node**, one post-order pass over the tree however many\n * layouts ask. Keyed weakly on the node object, which the scanner (build)\n * and the manifest (runtime) each build once.\n */\n\nimport { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';\nimport type { SegmentType } from './types.ts';\n\n/** The fields of a scanned or manifest segment node this walk reads. */\ninterface DescendantNode {\n segmentName: string;\n segmentType: SegmentType;\n paramName?: string;\n paramPrefix?: string;\n paramSuffix?: string;\n interceptedSegmentName?: string;\n page?: unknown;\n children: readonly DescendantNode[];\n}\n\nconst MEMO = new WeakMap<DescendantNode, ReadonlyMap<string, UrlSegmentIdentity>>();\nconst RENDERS_PAGE = new WeakMap<DescendantNode, boolean>();\n\n/** Whether a page sits at or below `node` on its `children` chain. */\nfunction rendersPage(node: DescendantNode): boolean {\n let found = RENDERS_PAGE.get(node);\n if (found === undefined) {\n found = !!node.page || node.children.some(rendersPage);\n RENDERS_PAGE.set(node, found);\n }\n return found;\n}\n\n/**\n * Every param a segment on `node`'s `children` chain defines, at any depth,\n * by name, with the segment that defines it (its bracket form, for codegen).\n * Excludes `node`'s own param. A name defined in several branches appears\n * once: the scanner already requires one bracket form per name across the\n * tree (`validateUniqueBracketForms`).\n */\nexport function childrenChainParams(node: DescendantNode): ReadonlyMap<string, UrlSegmentIdentity> {\n const memo = MEMO.get(node);\n if (memo) return memo;\n const params = new Map<string, UrlSegmentIdentity>();\n for (const child of node.children) {\n if (!rendersPage(child)) continue;\n const identity = effectiveUrlSegment(child);\n if (identity.paramName && !params.has(identity.paramName)) {\n params.set(identity.paramName, identity);\n }\n for (const [name, deeper] of childrenChainParams(child)) {\n if (!params.has(name)) params.set(name, deeper);\n }\n }\n MEMO.set(node, params);\n return params;\n}\n","/**\n * Typed `<Link>` codegen — interface augmentation generation.\n *\n * Extracted from `codegen.ts` to keep that file under the project's\n * 500-line cap. This module owns everything that emits the\n * `interface LinkFunction { ... }` augmentation blocks in the generated\n * `.timber/timber-routes.d.ts`.\n *\n * Two augmentation blocks are emitted:\n *\n * 1. **Per-route discriminated union** (`formatTypedLinkOverloads`) —\n * one call signature whose props is a union keyed on `href`. TS\n * narrows by literal href and reports prop errors against the\n * matched variant. See TIM-835 and `design/09-typescript.md`.\n *\n * 2. **Catch-all overloads** (`formatLinkCatchAllOverloads`) — external\n * href literals (`http://`, `mailto:`, etc.) and a computed-string\n * `<H extends string>` signature for runtime-computed paths.\n *\n * Block ordering is critical for error UX: per-route is emitted FIRST\n * so that, after TS's \"later overload set ordered first\" merge rule,\n * the discriminated union ends up LAST in resolution order — the\n * overload TS reports against on failure.\n */\n\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { classifyUrlSegment } from './segment-classify.ts';\n\n/**\n * The `searchParams` prop type, emitted identically on every Link variant\n * — per-route pattern, resolved template, and catch-all.\n *\n * TIM-1343: there is no per-route narrowing any more. `params.ts` is gone,\n * so codegen has no definition to read a `SearchParamsDefinition<T>` from.\n * Type safety moved to the value's construction site instead: callers write\n * `definition.buildSearchParams({ ... })`, which checks `Partial<T>` there\n * and returns a query STRING — the only shape that survives the RSC Flight\n * boundary. A plain record is the uncodec'd escape hatch. See `client/link.tsx` §\"searchParams prop shapes\".\n *\n * Declared once so the three emission sites cannot drift apart.\n */\nexport const SEARCH_PARAMS_PROP_TYPE = 'string | Record<string, unknown>';\n\n/**\n * Link base props in every emitted call signature: the real `LinkBaseProps`\n * from `@timber-js/app/client`, by reference.\n *\n * Until TIM-1621 this was an inline copy of the type. It drifted —\n * `replace` and `transitionTypes` were never added, so typed `<Link>`\n * rejected both — and its `onNavigate` came from `./client/link.js`, a\n * path relative to `.timber/` that never resolved, so that prop was\n * silently `any`. A reference cannot drift.\n */\nexport const LINK_BASE_PROPS_TYPE = \"import('@timber-js/app/client').LinkBaseProps\";\n\n// eslint-disable-next-line no-template-curly-in-string -- codegen output\nconst DOLLAR_STRING = '${string}';\n\n/**\n * Build the TypeScript type of every URL a route resolves to — a type\n * EXPRESSION, ready to drop into a declaration:\n *\n * '/venues' → '/venues'\n * '/products/[id]' → `/products/${string}`\n * '/img-[id].png' → `/img-${string}.png`\n * '/blog/[...slug]' → `/blog/${string}`\n * '/docs/[[...path]]' → '/docs' | `/docs/${string}`\n * '/[[...path]]' → '/' | `/${string}`\n *\n * An optional catch-all that is omitted drops its segment AND its slash\n * (`interpolateParams('/docs/[[...path]]', {})` is `/docs`), and\n * `/docs/${string}` does not match `/docs` — so a trailing optional\n * catch-all needs the bare prefix as a second member. Before TIM-1621 this\n * emitted only the template, and `<Link href=\"/docs\">` matched no route.\n *\n * Emitted once per route as `Routes[P]['href']` — the type `href()`\n * returns — and reused for `<Link>`'s resolved-template variants, so the\n * two cannot disagree about what a route's URLs look like.\n */\nexport function buildResolvedPattern(route: RouteEntry): string {\n return resolvedMembers(route)\n .map((m) => (m.includes(DOLLAR_STRING) ? `\\`${m}\\`` : `'${m}'`))\n .join(' | ');\n}\n\n/**\n * `<Link>`'s query-bearing href type: each member of `buildResolvedPattern`\n * that ends in a static part, with `?${string}` appended. `href(pattern,\n * params, search)` can return such a value, and a `/venues?${string}` is\n * not wide `string`, so without this it would match no Link overload.\n * `null` when every member ends in `${string}` (which already matches a query).\n */\nexport function buildResolvedPatternWithQuery(route: RouteEntry): string | null {\n // A member ending in `${string}` already matches any query, so it needs no\n // `?` form — emitting one anyway doubled the union and pushed real routes\n // out of the truncated \"not assignable to\" list in diagnostics.\n const members = resolvedMembers(route).filter((m) => !m.endsWith(DOLLAR_STRING));\n if (members.length === 0) return null;\n return members.map((m) => `\\`${m}?${DOLLAR_STRING}\\``).join(' | ');\n}\n\n/**\n * Template-literal bodies (no delimiters) of a route's URLs: one per\n * route, plus the bare prefix for a trailing optional catch-all.\n */\nfunction resolvedMembers(route: RouteEntry): string[] {\n const parts = route.urlPath.split('/');\n let omittedAt: number | null = null;\n const templateParts = parts.map((part, i) => {\n const seg = classifyUrlSegment(part);\n switch (seg.kind) {\n case 'optional-catch-all':\n // Only a trailing optional catch-all is valid; omitted, it takes the\n // slash before it along.\n if (i === parts.length - 1) omittedAt = i;\n return DOLLAR_STRING;\n case 'catch-all':\n return DOLLAR_STRING;\n case 'dynamic':\n return `${seg.prefix ?? ''}${DOLLAR_STRING}${seg.suffix ?? ''}`;\n default:\n return part;\n }\n });\n const template = templateParts.join('/');\n if (omittedAt === null) return [template];\n // Built from the TEMPLATE parts, so a dynamic ancestor stays a placeholder:\n // `/[org]/[[...path]]` omitted is `/${string}`, not the literal `/[org]`.\n return [templateParts.slice(0, omittedAt).join('/') || '/', template];\n}\n\n/**\n * Format the segmentParams type for Link overloads.\n *\n * Link params accept `string | number` for single dynamic segments\n * (convenience — values are stringified at runtime). Catch-all and\n * optional catch-all remain `string[]` / `string[] | undefined`.\n *\n * With a global schema, the schema codec's inferred type wins. Without\n * one, a URL segment is a raw string (widened to string | number for\n * Link convenience) — per-segment codec chains were deleted in TIM-1342.\n */\nexport function formatLinkParamsType(params: ParamEntry[], hasSchema?: boolean): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const fields = params.map((p) => {\n const fallback = p.type === 'string' ? 'string | number' : p.type;\n const codecType = hasSchema ? buildSchemaParamType(p, fallback) : fallback;\n return `${p.name}: ${codecType}`;\n });\n return `{ ${fields.join('; ')} }`;\n}\n\n/**\n * Catch-all call signatures for `<Link>` — external hrefs and computed\n * `string` variables. Emitted from codegen in a SEPARATE\n * `declare module` block (declared AFTER the per-route block) so the TS\n * \"later overload set ordered first\" rule places these catch-all\n * signatures ahead of per-route in resolution order, leaving per-route\n * as the final overload whose error message is reported on failure.\n *\n * The conditional `string extends H ? ... : never` protection preserves\n * TIM-624's guarantee that unknown internal path literals don't match\n * the catch-all — typos like `<Link href=\"/typo\" />` still error.\n */\nexport function formatLinkCatchAllOverloads(): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n const catchAllSearchParams = SEARCH_PARAMS_PROP_TYPE;\n\n // ExternalHref inlined here rather than referenced as an exported\n // alias so the generated .d.ts stands alone without source imports.\n /* eslint-disable no-template-curly-in-string -- codegen output */\n const externalHref =\n '`http://${string}` | `https://${string}` | `mailto:${string}` | `tel:${string}` | `ftp://${string}` | `//${string}` | `#${string}` | `?${string}`';\n /* eslint-enable no-template-curly-in-string */\n\n lines.push(' // Typed Link overloads — catch-all (block 2 / emitted second)');\n lines.push(' interface LinkFunction {');\n\n // (1) External/literal-protocol hrefs.\n //\n // TIM-833: `segmentParams` is permissively typed as\n // `Record<string, unknown>` (not `never`) so generic wrappers that\n // forward a `LinkProps`-shaped object can compile when the wrapper\n // happens to bottom out at an external href. There are no dynamic\n // segments to interpolate for an external href, so this prop is\n // ignored at runtime — accepting an open-shape object instead of\n // forbidding it removes a footgun without changing behavior.\n lines.push(` (props: ${baseProps} & {`);\n lines.push(` href: ${externalHref}`);\n lines.push(` segmentParams?: Record<string, unknown>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }): import('react').JSX.Element`);\n\n // (2) Computed/variable href — non-literal `string` only.\n //\n // `string extends H` is true only when H is the wide `string` type,\n // not a specific literal. For literal hrefs, this overload must NOT\n // be selectable so the per-route discriminated union (block 1) is\n // the resolution target.\n //\n // TIM-833 follow-up: the previous shape used `string extends H ? {...} : never`\n // on the WHOLE props type. For literal H, that collapsed `props` to\n // `never`, and JSX type inference then read `(never).children` as\n // `never` — producing the misleading\n // `'children' prop expects type 'never' which requires multiple\n // children, but only a single child was provided` (TS2745) error,\n // which buried the actual prop-mismatch message under a noise diagnostic.\n //\n // Fix: move the `: never` from the whole props onto just the `href`\n // field. The overload remains uncallable for literal H (since `\"/x\"`\n // is not assignable to `never`), but `children` retains its real\n // `ReactNode` type so JSX inference no longer collapses to never.\n // The diagnostic surface becomes: TS reports the per-route block's\n // error chain (the helpful \"Type 'number' is not assignable to type\n // 'string'\" message) WITHOUT a leading TS2745 noise line.\n lines.push(` <H extends string>(`);\n lines.push(` props: ${baseProps} & {`);\n lines.push(` href: string extends H ? H : never`);\n lines.push(` segmentParams?: Record<string, string | number | string[]>`);\n lines.push(` searchParams?: ${catchAllSearchParams}`);\n lines.push(` }`);\n lines.push(` ): import('react').JSX.Element`);\n\n lines.push(' }');\n return lines;\n}\n\n/**\n * Generate typed per-route Link call signatures via LinkFunction\n * interface merging.\n *\n * TIM-835: This emits a SINGLE call signature whose props is a\n * discriminated union keyed on `href`. TypeScript narrows the union by\n * the literal `href` at the call site, then checks the rest of the\n * props against the matched variant. When `segmentParams` or\n * `searchParams` is wrong, TS reports the error against the matched\n * variant — naming the user's actual `href` and the offending field.\n *\n * Before TIM-835, this function emitted N separate per-route overloads\n * (one per route, sometimes two for dynamic routes). When ALL overloads\n * failed, TS would pick an arbitrary failed overload (heuristically the\n * \"last tried\") to render the diagnostic, often pointing at a route\n * completely unrelated to the one the user wrote. The discriminated\n * union sidesteps overload-resolution heuristics entirely.\n *\n * Open property shapes (`Record<string, unknown>` instead of `never`)\n * for `segmentParams` on routes that don't declare them keep generic\n * `LinkProps`-spreading wrappers compiling. (Aligned with TIM-833.)\n *\n * TIM-832: this function still emits the per-route block FIRST and the\n * catch-all block follows, so per-route remains the LAST overload set in\n * resolution order — the one TS reports against on failure. With a\n * discriminated union there is only one call signature in this block,\n * so the resolved-template-vs-pattern ordering reduces to placing the\n * pattern variant before the resolved-template variant inside the union.\n */\nexport function formatTypedLinkOverloads(routes: RouteEntry[], hasSchema?: boolean): string[] {\n const lines: string[] = [];\n const baseProps = LINK_BASE_PROPS_TYPE;\n\n // Build the union variants. Each route contributes one variant for the\n // pattern href (e.g. '/products/[id]'); for dynamic routes, a variant for\n // the resolved-template href (e.g. `/products/${string}`); and, when its\n // URL can end in a static part, a query-bearing variant (`/venues?${string}`).\n //\n // The PATTERN variant must be listed BEFORE the resolved-template\n // variant for the same route so that when the user writes the literal\n // pattern href (`<Link href=\"/products/[id]\" />`), TS narrows to the\n // pattern variant (which carries the typed `segmentParams` shape)\n // rather than the looser resolved-template variant. Without this\n // ordering, TS would silently match the resolved-template variant\n // first — swallowing typed-segmentParams type errors.\n const variants: string[] = [];\n for (const route of routes) {\n const hasDynamicParams = route.params.length > 0;\n // For routes with no dynamic params, accept an absent OR open-shape\n // segmentParams. `Record<string, unknown>` keeps generic spreads\n // compiling and gives a readable error if a non-object is passed.\n const paramsProp = hasDynamicParams\n ? `segmentParams: ${formatLinkParamsType(route.params, hasSchema)}`\n : 'segmentParams?: Record<string, unknown>';\n\n // TIM-1343: searchParams is no longer typed per-route. There is no\n // convention file to read a definition from, so codegen has nothing to\n // narrow with — the value is either a query string built by\n // `definition.buildSearchParams()` (which type-checks its own\n // `Partial<T>` at that call) or a plain String()-coerced record.\n const searchParamsProp = `searchParams?: ${SEARCH_PARAMS_PROP_TYPE}`;\n\n // Pattern variant FIRST (more specific).\n variants.push(\n `${baseProps} & { href: '${route.urlPath}'; ${paramsProp}; ${searchParamsProp} }`\n );\n\n // Resolved-template variant SECOND (looser, matches interpolated hrefs).\n // TIM-835: `Record<string, never>` for segmentParams forbids ANY\n // provided keys on the resolved-template variant. Without this, the\n // resolved-template would shadow the pattern variant for literal pattern\n // hrefs (`<Link href=\"/products/[id]\" segmentParams={...} />`) because\n // both variants accept the literal '/products/[id]' and the looser\n // variant would silently swallow segmentParams type errors.\n if (hasDynamicParams) {\n variants.push(\n `${baseProps} & { href: ${buildResolvedPattern(route)}; segmentParams?: Record<string, never>; ${searchParamsProp} }`\n );\n }\n\n // Query-bearing variant LAST (TIM-1621): what `href(pattern, params,\n // search)` returns, and any literal href with an inline query, for URLs\n // that end in a static part (`/venues?…`, `/docs?…`). It forbids both\n // props: the params are already interpolated and the query is already in\n // the string. A template ending in `${string}` already matches a query,\n // so those routes get no `?` variant — and their template variant still\n // accepts `searchParams`, which template types cannot prevent. That\n // combination throws in `resolveHref` at render instead.\n const queryPattern = buildResolvedPatternWithQuery(route);\n if (queryPattern) {\n variants.push(\n `${baseProps} & { href: ${queryPattern}; segmentParams?: Record<string, never>; searchParams?: never }`\n );\n }\n }\n\n lines.push(' interface LinkFunction {');\n if (variants.length === 0) {\n // No page routes — emit nothing. The catch-all block in the second\n // augmentation still provides external/computed-string signatures.\n lines.push(' }');\n return lines;\n }\n lines.push(' (');\n lines.push(' props:');\n for (const variant of variants) {\n lines.push(` | (${variant})`);\n }\n lines.push(` ): import('react').JSX.Element`);\n lines.push(' }');\n\n return lines;\n}\n","/**\n * Route map codegen.\n *\n * Walks the scanned RouteTree and generates a TypeScript declaration file\n * mapping every route to its params and searchParams shapes.\n *\n * This runs at build time and in dev (regenerated on file changes).\n * No runtime overhead — purely static type generation.\n */\n\nimport { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { RouteTree, SegmentNode } from './types.ts';\nimport type { ParamEntry, RouteEntry } from './codegen-types.ts';\nimport { buildSchemaParamType } from './codegen-shared.ts';\nimport { effectiveUrlSegment, type UrlSegmentIdentity } from './segment-classify.ts';\nimport { childrenChainParams } from './descendant-params.ts';\nimport {\n buildResolvedPattern,\n formatLinkCatchAllOverloads,\n formatTypedLinkOverloads,\n} from './link-codegen.ts';\n\n/** Options for route map generation. */\nexport interface CodegenOptions {\n /** Absolute path to the app/ directory. Required for page searchParams detection. */\n appDir?: string;\n /**\n * Absolute path to the directory where the .d.ts file will be written.\n * Used to compute correct relative import paths for page files.\n * Defaults to appDir when not provided (preserves backward compat for tests).\n */\n outputDir?: string;\n /**\n * Whether a global schema (app/schema.ts) exists.\n * Auto-detected from appDir when not explicitly set.\n */\n hasSchema?: boolean;\n}\n\n/**\n * Generate a TypeScript declaration file string from a scanned route tree.\n *\n * The output is a `declare module '@timber-js/app'` block containing the Routes\n * interface that maps every route path to its params and searchParams shape.\n */\nexport function generateRouteMap(tree: RouteTree, options: CodegenOptions = {}): string {\n // Auto-detect schema from appDir when not explicitly set\n const hasSchema = options.hasSchema ?? detectSchema(options.appDir);\n\n const routes: RouteEntry[] = [];\n collectRoutes(tree.root, [], '', routes, hasSchema, false);\n\n // Sort routes alphabetically for deterministic output\n routes.sort((a, b) => a.urlPath.localeCompare(b.urlPath));\n\n // When outputDir differs from appDir, import paths must be relative to outputDir\n const importBase = options.outputDir ?? options.appDir;\n\n return formatDeclarationFile(routes, importBase, hasSchema, options.appDir);\n}\n\n/** Schema file extensions to check, in priority order. */\nconst SCHEMA_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx'];\n\n/**\n * Detect whether app/schema.{ts,tsx,js,jsx} exists.\n */\nfunction detectSchema(appDir: string | undefined): boolean {\n if (!appDir) return false;\n return SCHEMA_EXTENSIONS.some((ext) => existsSync(join(appDir, `schema${ext}`)));\n}\n\n/**\n * Recursively walk the segment tree and collect route entries.\n *\n * A route entry is created for any segment that has a `page` or `route` file.\n * Params accumulate from ancestor dynamic segments.\n */\nfunction collectRoutes(\n node: SegmentNode,\n ancestorParams: ParamEntry[],\n parentTreePath: string,\n routes: RouteEntry[],\n hasSchema: boolean,\n insideSlot: boolean,\n insideIntercepting = false\n): void {\n // Build the tree path (includes groups, slots — uniquely identifies this segment).\n // Root node has empty segmentName, producing treePath = ''.\n const treePath = node.segmentName ? `${parentTreePath}/${node.segmentName}` : parentTreePath;\n // Accumulate params from this segment.\n //\n // The segment is read through `effectiveUrlSegment` for the same reason the\n // runtime coercer is: an intercepting node's own `segmentType` is\n // 'intercepting' and its `paramName` is unset — the param it binds lives in\n // the intercepted name (`(.)[albumSlug]` → `[albumSlug]`). Reading the node\n // directly emitted `{}` for a segment the router does bind and coerce, so\n // the types disagreed with the values for every intercepting page with a\n // dynamic intercepted segment, and for its descendants, which lost the\n // ancestor param too.\n const urlSegment = effectiveUrlSegment(node);\n const params = [...ancestorParams];\n if (urlSegment.paramName) params.push(paramEntry(urlSegment.paramName, urlSegment));\n\n // Check if this segment is a leaf route (has page or route file)\n const isPage = !!node.page;\n const isApiRoute = !!node.route;\n\n // A segment that hosts code but is not itself addressable — a layout,\n // middleware, or access check above the leaf — still gets a `$segment`\n // module, so `getSegmentParams(SEGMENT_PATH)` is callable from it and needs\n // a matching typed overload. Emitting only leaves left those call sites on\n // the broad `Record<string, string | string[]>` signature, which since\n // TIM-1342 (which deleted `defineSegmentParams`) is their ONLY typed path.\n // design/41-global-params.md's Type Summary promises layouts and middleware\n // exact accumulated params.\n //\n // `isRoutable: false` keeps them out of the urlPath-keyed emissions — the\n // `Routes` interface and `<Link>` variants — where they would publish a URL\n // that no request can reach. They belong only to the segmentPath-keyed\n // APIs: `getSegmentParams`, `useSegmentParams`, `TimberSegmentParams`.\n const hostsCode = !!node.layout || !!node.middleware || !!node.access;\n\n if (isPage || isApiRoute || hostsCode) {\n const entry: RouteEntry = {\n urlPath: node.urlPath,\n segmentPath: treePath || '/',\n params,\n // A page renders only for its own route; a layout, middleware or\n // access.ts runs for the routes below, so their params may be present.\n descendantParams: hostsCode\n ? [...childrenChainParams(node)].map(([name, segment]) => paramEntry(name, segment))\n : [],\n isApiRoute,\n isRoutable: isPage || isApiRoute,\n isSlotRoute: insideSlot,\n isInterceptingRoute: insideIntercepting,\n hasSchema,\n };\n\n routes.push(entry);\n }\n\n // Recurse into children. An intercepting subtree is flagged, and the flag is\n // sticky — the descendants are where the false URLs are. See\n // `RouteEntry.isInterceptingRoute` for what the flag drops and why dedupe\n // alone was not enough.\n for (const child of node.children) {\n const childIntercepting = insideIntercepting || child.segmentType === 'intercepting';\n collectRoutes(child, params, treePath, routes, hasSchema, insideSlot, childIntercepting);\n }\n\n // Recurse into slots (they share the parent's URL path, but may have their own pages)\n for (const slot of Object.values(node.slots)) {\n collectRoutes(slot, params, treePath, routes, hasSchema, true, insideIntercepting);\n }\n}\n\n/**\n * Dedupe route entries by urlPath for urlPath-keyed emissions (the Routes\n * interface and typed Link variants).\n *\n * Parallel-slot pages share their parent's urlPath; emitting one entry per\n * slot page produced duplicate interface keys (TS2300/TS2717 under\n * skipLibCheck:false) and duplicate overloads. The non-slot entry is the\n * canonical one; when only slot entries exist (parent has no page), the\n * lexicographically smallest segmentPath wins so output is independent of\n * slot scan order.\n *\n * The loser is discarded outright. It used to donate its `searchParams`\n * definition to the winner, because a slot could carry one the parent page\n * lacked; since TIM-1343 no route entry carries a searchParams definition at\n * all, there is nothing left to merge.\n *\n * segmentPath-keyed emissions (getSegmentParams, useSegmentParams,\n * TimberSegmentParams) must NOT use this — segmentPaths are already unique\n * and slot entries feed those APIs directly.\n */\nfunction dedupeRoutesByUrlPath(routes: RouteEntry[]): RouteEntry[] {\n const byPath = new Map<string, RouteEntry>();\n for (const route of routes) {\n const existing = byPath.get(route.urlPath);\n if (!existing) {\n byPath.set(route.urlPath, route);\n continue;\n }\n\n const routeWins =\n (existing.isSlotRoute && !route.isSlotRoute) ||\n (!!existing.isSlotRoute === !!route.isSlotRoute &&\n route.segmentPath.localeCompare(existing.segmentPath) < 0);\n byPath.set(route.urlPath, routeWins ? route : existing);\n }\n return [...byPath.values()];\n}\n\nfunction paramEntry(name: string, segment: UrlSegmentIdentity): ParamEntry {\n return {\n name,\n bracketName: bracketNameForSegment(segment),\n type: paramTypeForSegment(segment.segmentType),\n };\n}\n\n/**\n * Derive the bracket key for schema/codegen lookup.\n * For bare segments like `[id]` this is the segmentName itself.\n * For affixed segments like `img-[id].png` this is `[id]` — the bare bracket form.\n */\nfunction bracketNameForSegment(node: UrlSegmentIdentity): string {\n if (node.paramPrefix || node.paramSuffix) {\n return `[${node.paramName}]`;\n }\n return node.segmentName;\n}\n\nfunction paramTypeForSegment(segmentType: string): ParamEntry['type'] {\n switch (segmentType) {\n case 'catch-all':\n return 'string[]';\n case 'optional-catch-all':\n return 'string[] | undefined';\n default:\n return 'string';\n }\n}\n\n/**\n * Emit the schema-based type exports: TimberSegmentParams, TimberRoute,\n * AllSegmentParams, RoutesWithParams.\n *\n * These types use InferCodecType references so they stay in sync with\n * the schema without hardcoding resolved types.\n *\n * Design doc: design/41-global-params.md §Codegen Output\n */\nfunction formatSchemaTypes(routes: RouteEntry[]): string[] {\n const lines: string[] = [];\n\n lines.push('/** Union of all valid route patterns. */');\n lines.push('export type TimberRoute = keyof TimberSegmentParams;');\n lines.push('');\n lines.push('/** Maps each segment path to its accumulated segment params. */');\n lines.push('export interface TimberSegmentParams {');\n\n for (const route of routes) {\n if (route.params.length === 0) {\n lines.push(` '${route.segmentPath}': {};`);\n } else {\n lines.push(` '${route.segmentPath}': {`);\n for (const p of route.params) {\n lines.push(` ${p.name}: ${buildSchemaParamType(p)};`);\n }\n lines.push(' };');\n }\n }\n\n lines.push('}');\n lines.push('');\n\n // AllSegmentParams — flat union of all param types across all routes\n lines.push('/** All segment params (union of all route params). */');\n lines.push('export type AllSegmentParams = {');\n lines.push(\n ' [K in keyof TimberSegmentParams as TimberSegmentParams[K] extends Record<string, never>'\n );\n lines.push(' ? never');\n lines.push(' : K]: TimberSegmentParams[K];');\n lines.push('} extends infer U');\n lines.push(' ? { [K in keyof U[keyof U]]: U[keyof U][K] }');\n lines.push(' : never;');\n lines.push('');\n\n // RoutesWithParams — filter routes by required param keys\n lines.push(\n '/** Filters TimberRoute to routes whose accumulated params include all listed keys. */'\n );\n lines.push('export type RoutesWithParams<K extends keyof AllSegmentParams> = {');\n lines.push(' [R in TimberRoute]: K extends keyof TimberSegmentParams[R] ? R : never;');\n lines.push('}[TimberRoute];');\n\n return lines;\n}\n\n/**\n * Format the collected routes into a TypeScript declaration file.\n */\nfunction formatDeclarationFile(\n routes: RouteEntry[],\n importBase?: string,\n hasSchema?: boolean,\n appDir?: string\n): string {\n const lines: string[] = [];\n\n lines.push('// This file is auto-generated by timber.js route map codegen.');\n lines.push('// Do not edit manually. Regenerated on build and in dev mode.');\n lines.push('');\n // export {} makes this file a module, so all declare module blocks are\n // augmentations rather than ambient replacements. Without this, the\n // declare module blocks would replace the original module types entirely\n // (removing exports like bindUseQueryStates that aren't listed here).\n lines.push('export {};');\n lines.push('');\n\n if (hasSchema) {\n // Schema-based codegen: import schema and InferCodecType\n // Compute the schema import path relative to the output directory\n const schemaImport =\n appDir && importBase\n ? './' + relative(importBase, join(appDir, 'schema')).replace(/\\\\/g, '/')\n : '../app/schema';\n lines.push(`import type schema from '${schemaImport}';`);\n lines.push(\"import type { InferCodecType, SegmentParamCodec } from '@timber-js/app/params';\");\n lines.push('');\n // Collect all unique bracket keys from routes for key validation\n const allBracketKeys = new Set<string>();\n for (const route of routes) {\n for (const p of route.params) {\n allBracketKeys.add(p.bracketName);\n }\n }\n\n // Augment the ValidDynamicSegmentKeysRegistry so defineSchema constrains keys\n // to known filesystem segments. Unknown keys produce inline TS errors.\n if (allBracketKeys.size > 0) {\n lines.push(\"declare module '@timber-js/app/params' {\");\n lines.push(' interface ValidDynamicSegmentKeysRegistry {');\n for (const key of [...allBracketKeys].sort()) {\n lines.push(` ${JSON.stringify(key)}: true;`);\n }\n lines.push(' }');\n lines.push('}');\n lines.push('');\n }\n // Guard: detect when the schema or params imports silently degraded to\n // `any` because TypeScript could not resolve the import specifier.\n // In a .d.ts an unresolved import does NOT error — every downstream\n // type silently becomes `any`, which satisfies every assertion. Only\n // an explicit IsAny check catches it.\n lines.push('type _IsAny<T> = 0 extends 1 & T ? true : false;');\n lines.push('type _AssertSchemaNotAny<_T extends false = _IsAny<typeof schema>> = true;');\n lines.push('type _AssertCodecTypeNotAny<_T extends false = _IsAny<SegmentParamCodec>> = true;');\n lines.push('');\n // Type-level validation: each schema value must be a Codec or Standard Schema.\n // Running `pnpm run typecheck` will surface errors for invalid values.\n lines.push('type _AssertSchemaValues = {');\n lines.push(\n \" [K in keyof typeof schema['segmentParams']]: typeof schema['segmentParams'][K] extends SegmentParamCodec ? true : ['Error: value for', K, 'is not a valid Codec or Standard Schema'];\"\n );\n lines.push('};');\n // Generic constraint enforces that all values are `true` — if any value is\n // an error tuple, TS reports a real diagnostic instead of silently computing it.\n lines.push(\n 'type _EnforceSchemaValues<_T extends Record<string, true> = _AssertSchemaValues> = true;'\n );\n lines.push('');\n }\n\n // urlPath-keyed emissions use the deduped list (slot pages share their\n // parent's urlPath); segmentPath-keyed emissions below keep all entries.\n //\n // Intercepting subtrees are dropped outright rather than deduped: their\n // computed urlPath is not a route any request can reach, so a path that\n // happens NOT to collide with a real one would otherwise be published as a\n // real route. See `RouteEntry.isInterceptingRoute`.\n const uniqueByUrlPath = dedupeRoutesByUrlPath(\n routes.filter((r) => r.isRoutable && !r.isInterceptingRoute)\n );\n\n lines.push(\"declare module '@timber-js/app' {\");\n lines.push(' interface Routes {');\n\n // TIM-1343: no `searchParams` member. With `params.ts` gone there is no\n // convention file to read a definition from, so the framework has nothing\n // to type it with — and an always-`{}` member is a claim that every route\n // has no search params, which is false. Search-param types now come from\n // the definition object itself, wherever the app chooses to keep it.\n for (const route of uniqueByUrlPath) {\n const paramsType = formatParamsType(route.params, hasSchema);\n\n lines.push(` '${route.urlPath}': {`);\n lines.push(` segmentParams: ${paramsType}`);\n // TIM-1621: every URL the route resolves to — what `href()` returns.\n // Built by the same function as `<Link>`'s resolved-template variants.\n lines.push(` href: ${buildResolvedPattern(route)}`);\n lines.push(` }`);\n }\n\n lines.push(' }');\n\n // When a global schema exists, emit segment param types inside the\n // @timber-js/app module augmentation so that declare module blocks\n // for @timber-js/app/server and @timber-js/app/client can reference\n // AllSegmentParams via `import type { AllSegmentParams } from '@timber-js/app'`.\n if (hasSchema) {\n lines.push('');\n lines.push(...formatSchemaTypes(routes).map((l) => ` ${l}`));\n }\n\n lines.push('}');\n lines.push('');\n\n // useQueryStates + typed Link are urlPath-keyed → deduped list.\n const pageRoutes = uniqueByUrlPath.filter((r) => !r.isApiRoute);\n // getSegmentParams / useSegmentParams are segmentPath-keyed → full list,\n // so slot segments keep their own typed overloads.\n const dynamicRoutes = routes.filter((r) => r.params.length > 0);\n // The server overloads also type what a segment's descendants define, as\n // optional: a layout reads them at runtime, and may key on them (design/53).\n const serverRoutes = routes.filter((r) => r.params.length > 0 || r.descendantParams.length > 0);\n\n // Generate @timber-js/app/server augmentation — typed getSegmentParams\n if (serverRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/server' {\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n for (const route of serverRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema, route.descendantParams);\n lines.push(\n ` export function getSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function getSegmentParams(): Partial<AllSegmentParams>'\n : ' export function getSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('}');\n lines.push('');\n }\n\n // Generate overloads for @timber-js/app/client\n\n if (dynamicRoutes.length > 0 || pageRoutes.length > 0) {\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n if (hasSchema) {\n lines.push(\" import type { AllSegmentParams } from '@timber-js/app'\");\n }\n lines.push('');\n\n // useSegmentParams overloads\n if (dynamicRoutes.length > 0) {\n for (const route of dynamicRoutes) {\n const paramsType = formatParamsType(route.params, hasSchema);\n lines.push(\n ` export function useSegmentParams(segmentPath: '${route.segmentPath}'): ${paramsType}`\n );\n }\n lines.push(\n hasSchema\n ? ' export function useSegmentParams(): Partial<AllSegmentParams>'\n : ' export function useSegmentParams(): Record<string, string | string[]>'\n );\n lines.push('');\n }\n\n // Typed Link overloads — per-route with DIRECT types (no conditionals).\n // Direct types preserve TypeScript's excess property checking.\n //\n // TIM-832: per-route and catch-all are emitted as TWO separate\n // augmentation blocks. Per TS's merging rule \"later overload sets\n // ordered first\", the catch-all block (declared SECOND in this file)\n // ends up FIRST in the merged call-signature list at resolution time,\n // which puts the per-route block LAST — so its error message is the\n // one TypeScript reports when no overload matches. This gives users a\n // clear prop-mismatch error (e.g. \"'string | undefined' is not\n // assignable to 'string | number' on id\") instead of the old\n // confusing \"Type 'string' is not assignable to type 'never'\" cascade.\n if (pageRoutes.length > 0) {\n lines.push(' // Typed Link overloads — per-route (block 1 / emitted first)');\n lines.push(...formatTypedLinkOverloads(pageRoutes, hasSchema));\n lines.push('');\n }\n\n lines.push('}');\n lines.push('');\n }\n\n // TIM-832: catch-all block — emitted as a SEPARATE `declare module`\n // augmentation so TS's \"later overload set first\" rule orders it ahead\n // of the per-route block above at resolution time, leaving per-route as\n // the \"last overload\" whose error TypeScript reports.\n lines.push(\"declare module '@timber-js/app/client' {\");\n lines.push(\" import type { SearchParamsDefinition } from '@timber-js/app/search-params'\");\n lines.push('');\n lines.push(...formatLinkCatchAllOverloads());\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Format the params type for a route entry. `optional` params (those a\n * descendant defines) may be absent: `name?: T | undefined`.\n */\nfunction formatParamsType(\n params: ParamEntry[],\n hasSchema?: boolean,\n optional: ParamEntry[] = []\n): string {\n if (params.length === 0 && optional.length === 0) {\n return '{}';\n }\n\n // Without a schema a URL segment is an uninterpreted string — that IS\n // its type. Per-segment codec chains used to narrow it here; TIM-1342\n // deleted them along with params.ts.\n const codecType = (p: ParamEntry) => (hasSchema ? buildSchemaParamType(p) : p.type);\n const fields = [\n ...params.map((p) => `${p.name}: ${codecType(p)}`),\n ...optional.map((p) => `${p.name}?: (${codecType(p)}) | undefined`),\n ];\n return `{ ${fields.join('; ')} }`;\n}\n\n// TIM-1341: `useQueryStates` no longer has a route-string form, so the\n// generated `.d.ts` emits no overloads for it. Its source signature —\n// `useQueryStates(codecs, options?)` — is fully generic over the codec map\n// and needs no per-route augmentation. Reaching another route's codecs is\n// done by importing that route's `searchParams` definition from its\n// `params.ts` and calling `definition.useQueryStates()`, which is typed by\n// inference and cannot fail at runtime on an unpopulated registry.\n// See design/23-search-params.md §\"Client Access\".\n\n// Link overload formatters and helpers (`formatTypedLinkOverloads`,\n// `formatLinkCatchAllOverloads`, `formatLinkParamsType`,\n// `buildResolvedPattern`, `LINK_BASE_PROPS_TYPE`) were extracted to\n// `./link-codegen.ts` (TIM-835) to keep this file under the 500-line\n// cap. They are imported at the top of this file.\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,SAAgB,qBAAqB,GAAe,UAA2B;CAG7E,OAAO,iDAFK,KAAK,UAAU,EAAE,WAE2B,EAAI,mCADjD,YAAY,EAAE;AAE3B;;;;;;;;;;;;;;;;;;;;;;;;;ACCA,IAAM,uBAAO,IAAI,QAAiE;AAClF,IAAM,+BAAe,IAAI,QAAiC;;AAG1D,SAAS,YAAY,MAA+B;CAClD,IAAI,QAAQ,aAAa,IAAI,IAAI;CACjC,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,CAAC,CAAC,KAAK,QAAQ,KAAK,SAAS,KAAK,WAAW;EACrD,aAAa,IAAI,MAAM,KAAK;CAC9B;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,oBAAoB,MAA+D;CACjG,MAAM,OAAO,KAAK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yProblem } from "./key-headers-CVpa6fpW
2
2
  import { t as writeFileAtomic } from "./write-file-atomic-DW8m_Atv.js";
3
3
  import { a as fileHasAnyExport, c as fileHasStarExport, d as patternBinds, f as tryParse, i as fileDefaultExportIsLocalValue, l as getCsrfExport, o as fileHasDefaultExport, p as readFileCached, r as TRANSPARENT_WRAPPERS, s as fileHasDirective, u as isScriptExtension } from "./scanner-B6V2RqqF.js";
4
4
  import { x as swallow } from "./logger-D1sWX2I0.js";
5
- import { t as generateRouteMap } from "./codegen-vaCyFyVN.js";
5
+ import { n as childrenChainParams, t as generateRouteMap } from "./codegen-BxJGInWa.js";
6
6
  import { t as HTTP_METHODS } from "./route-methods-Dk2kZc0n.js";
7
7
  import { join } from "node:path";
8
8
  import { existsSync } from "node:fs";
@@ -216,7 +216,7 @@ var ROUTE_OPTIONS_EXPORT = {
216
216
  * `server/route-module-loader.ts`; `lifetime` and `key`, in
217
217
  * `server/segment-lifetime/segment-key.ts`). A key's `searchParams` and
218
218
  * `cookies` name definitions, so they are the one place a non-literal value is
219
- * accepted; `segmentParams` is checked against the segment's path by
219
+ * accepted; `segmentParams` is checked against the params the segment can key by
220
220
  * `routing/route-options-lint.ts`. The whole object follows one rule so that
221
221
  * every key is checkable: this reader accepts one spelling —
222
222
  * `export const xOptions = { … }` of literal values, optionally behind
@@ -513,7 +513,7 @@ function checkRouteOptions(node, warnings, position, layoutLifetimeDefault, ance
513
513
  for (const [kind, file] of files) {
514
514
  if (!file || !isScriptExtension(file.extension)) continue;
515
515
  const { options, problems } = readRouteOptions(file.filePath, kind);
516
- problems.push(...inertOptions(options, here), ...paramsOffPath(options, pathParams), ...keyWithoutDocument(options, kind === "layout" ? layoutLifetimeDefault : "request"));
516
+ problems.push(...inertOptions(options, here), ...unkeyableParams(options, pathParams, kind === "layout" && here === "main" ? descendantsOf(node) : []), ...keyWithoutDocument(options, kind === "layout" ? layoutLifetimeDefault : "request"));
517
517
  if (problems.length === 0) continue;
518
518
  warnings.push({
519
519
  id: `ROUTE_OPTIONS_INVALID:${file.filePath}`,
@@ -545,14 +545,22 @@ function keyWithoutDocument(options, defaultLifetime) {
545
545
  if (options?.key === void 0 || (options.lifetime ?? defaultLifetime) === "document") return [];
546
546
  return ["key applies only to lifetime: 'document'. Declare `lifetime: 'document'` or remove key."];
547
547
  }
548
+ /** The params a layout's `children` chain defines below it, its path's excluded. */
549
+ function descendantsOf(node) {
550
+ return [...childrenChainParams(node).keys()];
551
+ }
548
552
  /**
549
553
  * A key's `segmentParams` must name params on the segment's path — the
550
- * segment's own and every ancestor's, slots included. Anything else could
551
- * never change, so the key would silently ignore what the author meant
552
- * (design/53 §"Segment keys").
554
+ * segment's own and every ancestor's, slots included — or, for a main-chain
555
+ * layout, a param a page on its `children` chain binds (design/53 §"Keying on
556
+ * a descendant's param"). A page never renders for a deeper route. A slot
557
+ * layout's key reads the slot's own record, and a slot's intercepting routes
558
+ * take no keys, so it keeps its path params. Any other name is never in the params the segment reads, so
559
+ * the key would silently ignore what the author meant (design/53 §"Segment
560
+ * keys").
553
561
  */
554
- function paramsOffPath(options, pathParams) {
555
- return (options?.key?.segmentParams ?? []).filter((name) => !pathParams.includes(name)).map((name) => `key.segmentParams names "${name}", which is not a param on this segment's path. ` + (pathParams.length > 0 ? `Params on the path: ${pathParams.join(", ")}.` : "This path has no params."));
562
+ function unkeyableParams(options, pathParams, descendants) {
563
+ return (options?.key?.segmentParams ?? []).filter((name) => !pathParams.includes(name) && !descendants.includes(name)).map((name) => `key.segmentParams names "${name}", which is not a param on this segment's path` + (descendants.length > 0 ? " or one its child routes define. " : ". ") + (pathParams.length > 0 ? `Params on the path: ${pathParams.join(", ")}.` : "This path has no params.") + (descendants.length > 0 ? ` Params its child routes define: ${descendants.join(", ")}.` : ""));
556
564
  }
557
565
  var OPTION_EXPORT_NAMES = [
558
566
  ...Object.values(ROUTE_OPTIONS_EXPORT),
@@ -971,4 +979,4 @@ function formatConventionWarnings(warnings, options = {}) {
971
979
  }
972
980
  export { CODEGEN_OUTPUT as a, writeRouteCodegen as c, readRouteOptions as i, buildDirToRouteMap as l, formatConventionWarnings as n, ENV_DTS_FILENAME as o, lintConventions as r, flushCodegenWrites as s, checkAppDirExists as t };
973
981
 
974
- //# sourceMappingURL=convention-lint-DkSDlsPH.js.map
982
+ //# sourceMappingURL=convention-lint-BWbKAV4x.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"convention-lint-BWbKAV4x.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/shared/route-options-export.ts","../../src/routing/route-options.ts","../../src/routing/route-options-lint.ts","../../src/shared/layout-defaults.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFileAtomic(segmentFile, content))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '/// <reference types=\"react/canary\" />',\n '/// <reference types=\"react-dom/canary\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\n/**\n * Write `timber-env.d.ts` only when its content differs.\n *\n * Its content is constant per timber version, so almost every call is a no-op\n * — and a file that is not rewritten cannot be read half-written. It is not\n * replaced atomically because it lives in the user's project root, often\n * committed: a rename would turn a symlink into a regular file, reset its\n * permissions, and a process killed mid-write would leave a temp file next to\n * their source. The in-place write happens only on first run or a timber\n * upgrade.\n */\nasync function writeEnvDts(envPath: string): Promise<void> {\n const existing = await readFile(envPath, 'utf-8').catch(() => null);\n if (existing !== TIMBER_ENV_DTS) await writeFile(envPath, TIMBER_ENV_DTS, 'utf-8');\n}\n\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n // The type checker can read these while they are being rewritten — an\n // editor's TS server during `timber dev`, a `tsgo` run during `vite\n // build`. A truncating write shows it an empty route map for the length\n // of the write, and every typed route degrades to `any` (TIM-1562).\n // The generated files under `.timber/` are replaced atomically.\n Promise.all([\n writeFileAtomic(routesPath, content),\n writeEnvDts(envPath),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * The export a layout or page declares its options under (design/53\n * §\"Route-module options\"). One table for both readers: the build-time source\n * reader (`routing/route-options.ts`) and the runtime module loader\n * (`server/route-module-loader.ts`), which cannot import the source reader\n * because it pulls in `node:fs` and Vite's parser.\n */\n\nexport type RouteOptionsKind = 'layout' | 'page';\n\nexport const ROUTE_OPTIONS_EXPORT = {\n layout: 'layoutOptions',\n page: 'pageOptions',\n} as const satisfies Record<RouteOptionsKind, string>;\n","/**\n * Route-module options: `export const layoutOptions = { … }` in a layout and\n * `export const pageOptions = { … }` in a page, read from source.\n *\n * Design doc: design/53-segment-lifetime.md §\"Route-module options\".\n *\n * `prerender` is read here at build time, before any route module loads:\n * `plugins/prerender-sugar.ts` decides from it which pages to wrap in\n * `cache.component(...)`. Every other option is validated here and read at\n * runtime from the loaded module (`deferSuspenseFor`, in\n * `server/route-module-loader.ts`; `lifetime` and `key`, in\n * `server/segment-lifetime/segment-key.ts`). A key's `searchParams` and\n * `cookies` name definitions, so they are the one place a non-literal value is\n * accepted; `segmentParams` is checked against the params the segment can key by\n * `routing/route-options-lint.ts`. The whole object follows one rule so that\n * every key is checkable: this reader accepts one spelling —\n * `export const xOptions = { … }` of literal values, optionally behind\n * `satisfies` / `as` — and reports the others it can see as problems.\n * `routing/convention-lint.ts` turns problems into build errors:\n *\n * - a spread, a computed key, a getter or method, or a non-literal value\n * - an unknown key (a misspelled `prerendr`)\n * - `pageOptions` in a layout or `layoutOptions` in a page\n * - options in a `'use client'` file, whose exports the server never sees\n * - the removed floating exports, `export const prerender` and\n * `export const deferSuspenseFor`\n * - `let`, a destructured binding, a specifier or a named re-export\n * (`export { pageOptions } from`, `export * as pageOptions from`)\n *\n * What it cannot see is not reported: `export * from` is not followed, a\n * file that does not parse reads as having no options (the compiler reports\n * it), and MDX pages are not read at all, so `prerender` in an MDX page does\n * nothing and its `deferSuspenseFor` is unvalidated.\n */\n\nimport { headerKeyProblem } from '../shared/key-headers.ts';\nimport { existsSync } from 'node:fs';\nimport type {\n LayoutOptions,\n PageOptions,\n RoutePrerender,\n SegmentKey,\n SegmentLifetime,\n} from '../server/types.ts';\nimport { patternBinds, TRANSPARENT_WRAPPERS, tryParse } from './export-detect.ts';\nimport { readFileCached } from './file-cache.ts';\nimport { ROUTE_OPTIONS_EXPORT, type RouteOptionsKind } from '../shared/route-options-export.ts';\n\nconst OPTIONS_TYPE = { layout: 'LayoutOptions', page: 'PageOptions' } as const;\n\n/** Floating exports the options objects replaced (design/53). */\nconst REMOVED_EXPORTS = ['prerender', 'deferSuspenseFor'] as const;\n\nexport interface RouteOptionsRead {\n /**\n * The declared options. Undefined when the file declares none or when any\n * problem was found — a half-read object is never acted on.\n */\n options: LayoutOptions | PageOptions | undefined;\n /** One line per problem, each naming what to write instead. */\n problems: string[];\n}\n\n// ─── AST access ────────────────────────────────────────────────────────────\n\n/** An ESTree node as oxc's `parseAst` produces it, read field by field. */\ntype Node = { readonly type: string; readonly [field: string]: unknown };\n\nfunction isNode(value: unknown): value is Node {\n return (\n typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'\n );\n}\n\nfunction child(node: Node, field: string): Node | undefined {\n const value = node[field];\n return isNode(value) ? value : undefined;\n}\n\nfunction list(node: Node, field: string): unknown[] {\n const value = node[field];\n return Array.isArray(value) ? value : [];\n}\n\n/** Strip `satisfies T`, `as T`, `(x)` and friends, which compile away. */\nfunction unwrap(node: Node): Node {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type)) {\n const inner = child(current, 'expression');\n if (!inner) break;\n current = inner;\n }\n return current;\n}\n\n/** An identifier's name or a string literal's value (`export { x as \"y\" }`). */\nfunction nameOf(node: Node | undefined): string | undefined {\n if (!node) return undefined;\n if (typeof node.value === 'string') return node.value;\n return typeof node.name === 'string' ? node.name : undefined;\n}\n\n/** A literal's value; a template literal with no `${}` counts as a string. */\nfunction literal(node: Node): unknown {\n const n = unwrap(node);\n if (n.type === 'Literal') return n.value;\n if (n.type !== 'TemplateLiteral' || list(n, 'expressions').length > 0) return undefined;\n const [quasi] = list(n, 'quasis');\n // A TemplateElement's `value` is `{ raw, cooked }`, not a node.\n const parts = isNode(quasi) ? quasi.value : undefined;\n const value =\n typeof parts === 'object' && parts !== null && 'cooked' in parts ? parts.cooked : undefined;\n return typeof value === 'string' ? value : undefined;\n}\n\n/** `key: undefined` — the same as leaving the key out, as the types allow. */\nfunction isUndefined(node: Node): boolean {\n const n = unwrap(node);\n return n.type === 'Identifier' && n.name === 'undefined';\n}\n\n// ─── Value readers, one per option ────────────────────────────────────────\n\ntype Read<T> = { value: T } | { problem: string };\n\n/** A numeric literal is never negative (`-1` is a unary expression), so finite is enough. */\nfunction readNonNegativeNumber(node: Node, label: string): Read<number> {\n const value = literal(node);\n if (typeof value === 'number' && Number.isFinite(value)) return { value };\n return { problem: `${label} must be a non-negative number literal.` };\n}\n\nfunction readPrerender(node: Node): Read<RoutePrerender> {\n const value = literal(node);\n if (typeof value === 'boolean') return { value };\n const n = unwrap(node);\n if (n.type !== 'ObjectExpression') {\n return {\n problem: 'prerender must be `true`, `false`, or an object literal `{ ttl?, tags? }`.',\n };\n }\n const result: { ttl?: number; tags?: string[] } = {};\n for (const entry of readProperties(n, 'prerender')) {\n if ('problem' in entry) return entry;\n if (entry.key === 'ttl') {\n const ttl = readNonNegativeNumber(entry.value, 'prerender.ttl');\n if ('problem' in ttl) return ttl;\n result.ttl = ttl.value;\n } else if (entry.key === 'tags') {\n const tags = readStringArray(entry.value);\n if (!tags) return { problem: 'prerender.tags must be an array of string literals.' };\n result.tags = tags;\n } else {\n return { problem: `Unknown key \"${entry.key}\" in prerender. Allowed: ttl, tags.` };\n }\n }\n return { value: result };\n}\n\nfunction readStringArray(node: Node): string[] | undefined {\n const n = unwrap(node);\n if (n.type !== 'ArrayExpression') return undefined;\n const result: string[] = [];\n for (const element of list(n, 'elements')) {\n const value = isNode(element) ? literal(element) : undefined;\n if (typeof value !== 'string') return undefined;\n result.push(value);\n }\n return result;\n}\n\n/**\n * One reader per option key. Typed against the public option types, so an\n * option added to `PageOptions` / `LayoutOptions` without a reader here (or a\n * reader without the option) fails typecheck — the two lists cannot drift.\n */\ntype Readers<T> = {\n [K in keyof Required<T>]: (\n node: Node\n ) => Read<NonNullable<T[K]> extends SegmentKey ? BuildTimeKey : NonNullable<T[K]>>;\n};\n\nconst deferSuspenseFor = (node: Node) => readNonNegativeNumber(node, 'deferSuspenseFor');\n\nconst LIFETIMES: readonly SegmentLifetime[] = ['request', 'document'];\n\nfunction readLifetime(node: Node): Read<SegmentLifetime> {\n const value = literal(node);\n const lifetime = LIFETIMES.find((l) => l === value);\n if (lifetime) return { value: lifetime };\n return { problem: \"lifetime must be 'request' or 'document'.\" };\n}\n\n/**\n * What the build can read of a segment key: the param and header names. `searchParams`\n * and `cookies` name definitions — code the build cannot evaluate — so only\n * their shape is checked here; their values take effect from the loaded\n * module (`server/segment-lifetime/`). The route-options lint checks the\n * param names against what the segment can key (its path, and for a layout its\n * child routes' params).\n */\ntype BuildTimeKey = Pick<SegmentKey, 'segmentParams' | 'headers'>;\n\nfunction readHeaderNames(node: Node): Read<string[]> {\n const names = readStringArray(node);\n if (!names) return { problem: 'key.headers must be an array of header-name string literals.' };\n for (const name of names) {\n const problem = headerKeyProblem(name);\n if (problem) return { problem };\n }\n return { value: names };\n}\n\n/** A value written in place, which cannot be a definition imported or declared elsewhere. */\nfunction isInlineValue(node: Node): boolean {\n const type = unwrap(node).type;\n return (\n literal(node) !== undefined ||\n type === 'ObjectExpression' ||\n type === 'ArrayExpression' ||\n type === 'Literal' ||\n type === 'TemplateLiteral'\n );\n}\n\nfunction readKey(node: Node): Read<BuildTimeKey> {\n const n = unwrap(node);\n if (n.type !== 'ObjectExpression') {\n return {\n problem:\n 'key must be an object literal `{ segmentParams?, searchParams?, cookies?, headers? }`.',\n };\n }\n const result: BuildTimeKey = {};\n for (const entry of readProperties(n, 'key')) {\n if ('problem' in entry) return entry;\n if (entry.key === 'segmentParams') {\n const names = readStringArray(entry.value);\n if (!names) return { problem: 'key.segmentParams must be an array of string literals.' };\n result.segmentParams = names;\n } else if (entry.key === 'searchParams') {\n if (isInlineValue(entry.value)) {\n return {\n problem:\n 'key.searchParams must name a search-params definition (`defineSearchParams`, or a `.pick()` of one).',\n };\n }\n } else if (entry.key === 'cookies') {\n const array = unwrap(entry.value);\n const elements = list(array, 'elements');\n const definitions = elements.every(\n (e) => isNode(e) && e.type !== 'SpreadElement' && !isInlineValue(e)\n );\n if (array.type !== 'ArrayExpression' || !definitions) {\n return {\n problem: 'key.cookies must be an array literal of cookie definitions (`defineCookie`).',\n };\n }\n } else if (entry.key === 'headers') {\n const headers = readHeaderNames(entry.value);\n if ('problem' in headers) return headers;\n result.headers = headers.value;\n } else {\n return {\n problem: `Unknown key \"${entry.key}\" in key. Allowed: segmentParams, searchParams, cookies, headers.`,\n };\n }\n }\n return { value: result };\n}\n\nconst READERS = {\n layout: {\n lifetime: readLifetime,\n key: readKey,\n prerender: readPrerender,\n deferSuspenseFor,\n } satisfies Readers<LayoutOptions>,\n page: {\n lifetime: readLifetime,\n key: readKey,\n prerender: readPrerender,\n deferSuspenseFor,\n } satisfies Readers<PageOptions>,\n};\n\n// ─── Object literal ───────────────────────────────────────────────────────\n\ntype Entry = { key: string; value: Node } | { problem: string };\n\n/**\n * The `key: value` entries of an object literal, or a problem per entry that\n * has none. `key: undefined` entries are dropped: they mean \"not set\".\n */\nfunction readProperties(object: Node, label: string): Entry[] {\n return list(object, 'properties').flatMap((prop): Entry[] => {\n if (!isNode(prop) || prop.type === 'SpreadElement') {\n return [{ problem: `${label} cannot use a spread; write every key in the literal.` }];\n }\n if (prop.computed === true) {\n return [{ problem: `${label} cannot use a computed key; write the key name.` }];\n }\n const value = child(prop, 'value');\n const key = nameOf(child(prop, 'key'));\n if (prop.kind !== 'init' || prop.method === true || !value || key === undefined) {\n return [{ problem: `${label} entries must be plain \\`key: value\\` pairs.` }];\n }\n return isUndefined(value) ? [] : [{ key, value }];\n });\n}\n\nfunction readOptionsObject(init: Node, kind: RouteOptionsKind, problems: string[]) {\n const name = ROUTE_OPTIONS_EXPORT[kind];\n const object = unwrap(init);\n if (object.type !== 'ObjectExpression') {\n problems.push(`${name} must be an object literal: \\`export const ${name} = { … }\\`.`);\n return undefined;\n }\n const readers: Record<string, (node: Node) => Read<unknown>> = READERS[kind];\n const options: Record<string, unknown> = {};\n for (const entry of readProperties(object, name)) {\n if ('problem' in entry) {\n problems.push(entry.problem);\n continue;\n }\n const reader = Object.hasOwn(readers, entry.key) ? readers[entry.key] : undefined;\n if (!reader) {\n problems.push(\n `Unknown key \"${entry.key}\" in ${name}. Allowed: ${Object.keys(readers).join(', ')}.`\n );\n continue;\n }\n const read = reader(entry.value);\n if ('problem' in read) problems.push(read.problem);\n else options[entry.key] = read.value;\n }\n return options;\n}\n\n// ─── File ─────────────────────────────────────────────────────────────────\n\nconst NONE: RouteOptionsRead = Object.freeze({ options: undefined, problems: [] });\n\n/** Every name the reader reacts to; a file containing none of them is not parsed. */\nconst MENTIONS = /Options|prerender|deferSuspenseFor/;\n\n/**\n * Read a layout's `layoutOptions` or a page's `pageOptions` from source.\n *\n * A missing or unparseable file reads as no options and no problems: the\n * compiler reports syntax errors, and guessing at a half-written file would\n * misreport it. `.ts` files are parsed as TypeScript, not TSX, so an\n * angle-bracket cast does not hide a file from this check.\n */\nexport function readRouteOptions(filePath: string, kind: RouteOptionsKind): RouteOptionsRead {\n if (!existsSync(filePath)) return NONE;\n const source = readFileCached(filePath);\n // Runs on every page and layout on each rescan; most declare nothing.\n if (!MENTIONS.test(source)) return NONE;\n const program = tryParse(source, /\\.[mc]?ts$/.test(filePath) ? 'ts' : 'tsx');\n if (!program) return NONE;\n\n const own = ROUTE_OPTIONS_EXPORT[kind];\n const otherKind: RouteOptionsKind = kind === 'page' ? 'layout' : 'page';\n const other = ROUTE_OPTIONS_EXPORT[otherKind];\n const problems: string[] = [];\n let init: Node | undefined;\n\n /** An export of a watched name in a form the build cannot read. */\n const report = (name: string | undefined) => {\n if (name === own) {\n problems.push(\n `${own} must be declared in this file as \\`export const ${own} = { … } satisfies ${OPTIONS_TYPE[kind]}\\`. ` +\n '`let`, destructuring, `export { … }` and re-exports cannot be read at build time.'\n );\n } else if (name === other) {\n problems.push(\n `${other} configures a ${otherKind}; this file is a ${kind}. Use \\`export const ${own}\\`.`\n );\n } else if (name && (REMOVED_EXPORTS as readonly string[]).includes(name)) {\n problems.push(\n `\\`export const ${name}\\` was removed. Move it into the options object: ` +\n `\\`export const ${own} = { ${name}: … } satisfies ${OPTIONS_TYPE[kind]}\\`.`\n );\n }\n };\n const watched = [own, other, ...REMOVED_EXPORTS];\n\n for (const stmt of program.body) {\n if (!isNode(stmt) || stmt.exportKind === 'type') continue;\n // `export * as pageOptions from` names an export; bare `export * from` does not.\n if (stmt.type === 'ExportAllDeclaration') report(nameOf(child(stmt, 'exported')));\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n for (const spec of list(stmt, 'specifiers')) {\n if (isNode(spec) && spec.exportKind !== 'type') report(nameOf(child(spec, 'exported')));\n }\n const decl = child(stmt, 'declaration');\n if (!decl) continue;\n if (decl.type !== 'VariableDeclaration') {\n report(nameOf(child(decl, 'id'))); // function or class\n continue;\n }\n for (const declarator of list(decl, 'declarations')) {\n if (!isNode(declarator)) continue;\n const id = child(declarator, 'id');\n const value = child(declarator, 'init');\n if (id?.type !== 'Identifier') {\n for (const name of watched) if (patternBinds(id, name)) report(name);\n } else if (id.name === own && decl.kind === 'const' && value) {\n init = value;\n } else {\n report(nameOf(id));\n }\n }\n }\n\n if (init && isClientModule(program.body)) {\n problems.push(\n `A 'use client' ${kind} cannot declare ${own}: the server sees a client reference, ` +\n `not the object. Move ${own} to a server ${kind} that renders the client component.`\n );\n }\n const options = init ? readOptionsObject(init, kind, problems) : undefined;\n return { options: problems.length === 0 ? options : undefined, problems };\n}\n\n/** Whether the module starts with a 'use client' directive. */\nfunction isClientModule(body: readonly unknown[]): boolean {\n for (const stmt of body) {\n if (\n !isNode(stmt) ||\n stmt.type !== 'ExpressionStatement' ||\n typeof stmt.directive !== 'string'\n ) {\n return false;\n }\n if (stmt.directive === 'use client') return true;\n }\n return false;\n}\n","/**\n * Convention-lint check for route-module options (design/53 §\"Route-module\n * options\"): `layoutOptions` / `pageOptions` the build cannot read, and\n * options declared where nothing reads them. Called from\n * `lintConventions` in `convention-lint.ts`.\n */\n\nimport type { ConventionWarning } from './convention-lint.ts';\nimport { fileHasAnyExport, isScriptExtension } from './export-detect.ts';\nimport { childrenChainParams } from './descendant-params.ts';\nimport { readRouteOptions } from './route-options.ts';\nimport type { RouteFile, SegmentNode } from './types.ts';\nimport type { LayoutOptions, PageOptions, SegmentLifetime } from '../server/types.ts';\nimport { ROUTE_OPTIONS_EXPORT, type RouteOptionsKind } from '../shared/route-options-export.ts';\n\n/**\n * Fail the build on a `layoutOptions` / `pageOptions` the build cannot read.\n *\n * Proven from source and fatal in the sense the error level requires: the\n * developer declared an option that would otherwise silently do nothing — a\n * misspelled key, a value the build cannot read, an options object in the\n * wrong file kind, or a floating `export const prerender` that no longer\n * prerenders. See `routing/route-options.ts` for what is accepted.\n */\nexport function checkRouteOptions(\n node: SegmentNode,\n warnings: ConventionWarning[],\n position: RoutePosition,\n /** `layoutDefaults.lifetime`, resolved (design/53 §\"App-wide defaults\"). */\n layoutLifetimeDefault: SegmentLifetime,\n /** The params named on the path above this segment. */\n ancestorParams: readonly string[] = []\n): void {\n const here: RoutePosition = node.segmentType === 'intercepting' ? 'intercepting' : position;\n const pathParams = node.paramName ? [...ancestorParams, node.paramName] : ancestorParams;\n const files: Array<[RouteOptionsKind, RouteFile | undefined]> = [\n ['layout', node.layout],\n ['page', node.page],\n ];\n for (const [kind, file] of files) {\n if (!file || !isScriptExtension(file.extension)) continue;\n const { options, problems } = readRouteOptions(file.filePath, kind);\n problems.push(\n ...inertOptions(options, here),\n ...unkeyableParams(\n options,\n pathParams,\n kind === 'layout' && here === 'main' ? descendantsOf(node) : []\n ),\n ...keyWithoutDocument(options, kind === 'layout' ? layoutLifetimeDefault : 'request')\n );\n if (problems.length === 0) continue;\n warnings.push({\n id: `ROUTE_OPTIONS_INVALID:${file.filePath}`,\n summary: `${kind}.${file.extension} has invalid ${ROUTE_OPTIONS_EXPORT[kind]}: ${file.filePath}`,\n details:\n ` File: ${file.filePath}\\n\\n` +\n problems.map((problem) => ` - ${problem}\\n`).join('') +\n '\\n Options are read from source at build time, so they must be one object\\n' +\n ' literal of literal values.\\n',\n level: 'error',\n });\n }\n if (node.default && isScriptExtension(node.default.extension)) {\n const declared = fileHasAnyExport(node.default.filePath, OPTION_EXPORT_NAMES);\n if (declared.size > 0) {\n warnings.push({\n id: `ROUTE_OPTIONS_INVALID:${node.default.filePath}`,\n summary: `default.${node.default.extension} takes no route options: ${node.default.filePath}`,\n details:\n ` File: ${node.default.filePath}\\n\\n` +\n ` default.tsx exports ${[...declared].join(', ')}, which nothing reads.\\n` +\n ' To fix: remove the export; declare options on the slot page or layout.\\n',\n level: 'error',\n });\n }\n }\n for (const child of node.children) {\n checkRouteOptions(child, warnings, here, layoutLifetimeDefault, pathParams);\n }\n for (const slot of Object.values(node.slots)) {\n const slotPosition = here === 'intercepting' ? here : 'slot';\n checkRouteOptions(slot, warnings, slotPosition, layoutLifetimeDefault, pathParams);\n }\n}\n\n/**\n * A `key` applies only to a `'document'` segment; on any other it would\n * silently do nothing. A layout that declares no lifetime takes the app's\n * `layoutDefaults.lifetime`, so under a `'document'` default it may declare a\n * key alone. A page always defaults to `'request'`.\n */\nfunction keyWithoutDocument(\n options: LayoutOptions | PageOptions | undefined,\n defaultLifetime: SegmentLifetime\n): string[] {\n if (options?.key === undefined || (options.lifetime ?? defaultLifetime) === 'document') return [];\n return [\n \"key applies only to lifetime: 'document'. Declare `lifetime: 'document'` or remove key.\",\n ];\n}\n\n/** The params a layout's `children` chain defines below it, its path's excluded. */\nfunction descendantsOf(node: SegmentNode): string[] {\n return [...childrenChainParams(node).keys()];\n}\n\n/**\n * A key's `segmentParams` must name params on the segment's path — the\n * segment's own and every ancestor's, slots included — or, for a main-chain\n * layout, a param a page on its `children` chain binds (design/53 §\"Keying on\n * a descendant's param\"). A page never renders for a deeper route. A slot\n * layout's key reads the slot's own record, and a slot's intercepting routes\n * take no keys, so it keeps its path params. Any other name is never in the params the segment reads, so\n * the key would silently ignore what the author meant (design/53 §\"Segment\n * keys\").\n */\nfunction unkeyableParams(\n options: LayoutOptions | PageOptions | undefined,\n pathParams: readonly string[],\n descendants: readonly string[]\n): string[] {\n const declared = options?.key?.segmentParams ?? [];\n return declared\n .filter((name) => !pathParams.includes(name) && !descendants.includes(name))\n .map(\n (name) =>\n `key.segmentParams names \"${name}\", which is not a param on this segment's path` +\n (descendants.length > 0 ? ' or one its child routes define. ' : '. ') +\n (pathParams.length > 0\n ? `Params on the path: ${pathParams.join(', ')}.`\n : 'This path has no params.') +\n (descendants.length > 0\n ? ` Params its child routes define: ${descendants.join(', ')}.`\n : '')\n );\n}\n\n/**\n * Where a segment sits decides which options take effect there.\n * - `main`: the matched route chain. Every option applies.\n * - `slot`: a parallel slot. `prerender` applies to slot pages (the sugar\n * walks slots); `deferSuspenseFor` does not — the hold is read from the\n * main chain's modules only (`server/route-module-loader.ts`).\n * - `intercepting`: an intercepting route and everything under it. It renders\n * only on a soft navigation, through the slot resolver, and the sugar skips\n * it, so no option applies.\n */\ntype RoutePosition = 'main' | 'slot' | 'intercepting';\n\nconst OPTION_EXPORT_NAMES = [\n ...Object.values(ROUTE_OPTIONS_EXPORT),\n 'prerender',\n 'deferSuspenseFor',\n] as const;\n\nfunction inertOptions(\n options: LayoutOptions | PageOptions | undefined,\n position: RoutePosition\n): string[] {\n if (!options || position === 'main') return [];\n const inert = Object.keys(options).filter(\n (key) => position === 'intercepting' || key === 'deferSuspenseFor'\n );\n return inert.map((key) =>\n position === 'intercepting'\n ? `${key} has no effect on an intercepting route: it renders only on a soft navigation, ` +\n 'through the slot that intercepts it. Declare it on the route being intercepted.'\n : `${key} has no effect in a parallel slot: the hold is read from the main route's ` +\n 'layouts and page. Declare it there.'\n );\n}\n","/**\n * The app's layout defaults (`layoutDefaults` in `timber.config.ts`), as every\n * reader takes them: the build lint (`routing/route-options-lint.ts`), the\n * runtime config the RSC entry reads (`plugins/entries.ts`), and through it\n * the main chain and slot layouts (`server/segment-lifetime/segment-key.ts`).\n *\n * See design/53-segment-lifetime.md §\"App-wide defaults\".\n */\n\nimport type { SegmentLifetime } from '../server/types.ts';\nimport { isHeaderList } from './key-headers.ts';\n\n/** What a layout takes when it declares no lifetime, or a key without `headers`. */\nexport interface ResolvedLayoutDefaults {\n lifetime: SegmentLifetime;\n /** The `key.headers` of a `'document'` layout whose key omits `headers`. */\n headers: readonly string[] | undefined;\n}\n\n/**\n * No defaults: what a page takes, and a layout at or below an intercepting\n * directory, which could not opt out of one.\n */\nexport const NO_LAYOUT_DEFAULTS: ResolvedLayoutDefaults = {\n lifetime: 'request',\n headers: undefined,\n};\n\n/**\n * Resolve the configured value. Anything config validation reports as\n * malformed reads as no default: a lifetime other than `'document'` is\n * `'request'`, and headers that are not an array of strings are none —\n * slower, never wrong. A header the key may not name is a fatal config error\n * (`config-validation.ts`), and the runtime refuses it again when it reads a\n * layout's key.\n */\nexport function resolveLayoutDefaults(value: unknown): ResolvedLayoutDefaults {\n if (typeof value !== 'object' || value === null) return NO_LAYOUT_DEFAULTS;\n const lifetime = 'lifetime' in value && value.lifetime === 'document' ? 'document' : 'request';\n const key = 'key' in value && typeof value.key === 'object' ? value.key : null;\n const headers = key !== null && 'headers' in key ? key.headers : undefined;\n return { lifetime, headers: isHeaderList(headers) ? headers : undefined };\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and either\n * fatal to rendering or a declaration that provably does nothing — a CSRF\n * exemption the gate never reads, a route option the build cannot read, a\n * middleware.ts in a slot. The developer believes the declaration is in\n * effect, so silence would ship the wrong behavior. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport { HTTP_METHODS } from '../server/route-methods.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n getCsrfExport,\n isScriptExtension,\n} from './export-detect.ts';\nimport { checkRouteOptions } from './route-options-lint.ts';\nimport type { LayoutDefaults } from '../config-types.ts';\nimport { resolveLayoutDefaults } from '../shared/layout-defaults.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(\n tree: RouteTree,\n appDir: string,\n /** The config the checks depend on, as the build resolved it. */\n config: { layoutDefaults: LayoutDefaults | undefined }\n): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n // Check 8: middleware.ts inside a parallel slot subtree (silently dead)\n checkSlotMiddleware(tree.root, warnings);\n\n // Check 9: `export const csrf` anywhere but route.ts, or in a form the\n // scanner cannot read (TIM-1543)\n checkCsrfExports(tree.root, warnings);\n if (tree.proxy) checkCsrfExport(tree.proxy, 'proxy.ts', warnings);\n if (tree.globalError) checkCsrfExport(tree.globalError, 'global-error', warnings);\n\n // Check 10: layoutOptions / pageOptions the build cannot read, unknown\n // keys, and the removed floating exports (design/53)\n const { lifetime } = resolveLayoutDefaults(config.layoutDefaults);\n checkRouteOptions(tree.root, warnings, 'main', lifetime);\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: CSRF Exemption Export ──────────────────────────────────────────\n\n/** Single-file segment conventions other than route.ts. */\nconst NON_ROUTE_FILE_KEYS = [\n 'page',\n 'layout',\n 'middleware',\n 'access',\n 'error',\n 'default',\n 'denied',\n] as const satisfies readonly (keyof SegmentNode)[];\n\n/**\n * Fail the build on a `csrf` export the CSRF gate would not honor.\n *\n * Both findings are proven from source, and both are fatal in the sense\n * the error level requires: the developer wrote an exemption that silently\n * does nothing, so a legitimate cross-site POST they meant to accept gets\n * a 403 in production, or they believe a page or action is exempt when\n * the gate still protects it. The exemption exists only on route.ts —\n * server actions always get the check (design/08 §\"Per-route exemption\").\n * A `'use server'` module cannot export it at all: plugin-rsc rejects every\n * non-async-function export there.\n */\nfunction checkCsrfExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) checkCsrfExport(node.route, 'route.ts', warnings);\n for (const key of NON_ROUTE_FILE_KEYS) {\n const file = node[key];\n if (file) checkCsrfExport(file, key, warnings);\n }\n // Status files and metadata routes (sitemap.ts, opengraph-image.tsx, …).\n // JSON status files are skipped by the script-extension check.\n for (const [name, file] of Object.entries(node.statusFiles ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const [name, file] of Object.entries(node.metadataRoutes ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const child of node.children) checkCsrfExports(child, warnings);\n for (const slot of Object.values(node.slots)) checkCsrfExports(slot, warnings);\n}\n\nfunction checkCsrfExport(file: RouteFile, convention: string, warnings: ConventionWarning[]): void {\n if (!isScriptExtension(file.extension)) return;\n const found = getCsrfExport(file.filePath);\n if (found === 'absent') return;\n const isRoute = convention === 'route.ts';\n if (isRoute && found === 'exempt') return;\n warnings.push({\n id: `CSRF_EXPORT_INVALID:${file.filePath}`,\n summary: isRoute\n ? `route.ts csrf export must be exactly \\`export const csrf = false\\`: ${file.filePath}`\n : `\\`csrf\\` can only be exported from route.ts, not ${convention}: ${file.filePath}`,\n details:\n ` File: ${file.filePath}\\n\\n` +\n (isRoute\n ? ' The CSRF gate reads this export from source before any module loads, so only\\n' +\n ' the literal form counts. Other values, `let`, and re-exports are not read.\\n\\n' +\n ' To fix: write `export const csrf = false;` in this file, or remove the export.\\n'\n : ' The per-route CSRF exemption applies only to route.ts handlers. Pages, layouts\\n' +\n ' and server actions always get the CSRF check.\\n\\n' +\n ' To fix: remove the export. To accept a cross-site POST, handle it in a route.ts\\n' +\n ' that exports `const csrf = false`.\\n'),\n level: 'error',\n });\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // Only script extensions need the 'use client' check — .json status files\n // never reach React at all, and are not in `statusFiles`.\n if (!isScriptExtension(file.extension)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: Slot Middleware ─────────────────────────────────────────────────\n\n/**\n * Error when middleware.ts appears inside a parallel slot subtree.\n *\n * Middleware is collected from the main matched segment chain only\n * (route-matcher.ts `collectMiddlewareChain`). The slot resolver never\n * walks `middleware` on its matched chain, so a middleware.ts under any\n * `@slot/` directory silently never executes. `access.ts` in slot chains\n * DOES run (via SlotAccessGate), making the asymmetry invisible unless\n * you know to look.\n *\n * This is a build error rather than a warning: the file provably cannot\n * run and its presence misleads the author into thinking the slot is\n * middleware-protected.\n *\n * See design/07-routing.md §\"Parallel Routes\"\n */\nfunction checkSlotMiddleware(node: SegmentNode, warnings: ConventionWarning[]): void {\n for (const [slotName, slotRoot] of Object.entries(node.slots)) {\n collectSlotMiddleware(slotRoot, slotName, warnings);\n }\n for (const child of node.children) {\n checkSlotMiddleware(child, warnings);\n }\n}\n\n/**\n * Walk a slot subtree and report every middleware.ts found.\n */\nfunction collectSlotMiddleware(\n node: SegmentNode,\n slotName: string,\n warnings: ConventionWarning[]\n): void {\n if (node.middleware) {\n warnings.push({\n id: `SLOT_MIDDLEWARE:${node.middleware.filePath}`,\n summary: `middleware.ts inside slot @${slotName} never executes: ${node.middleware.filePath}`,\n details:\n ` File: ${node.middleware.filePath}\\n\\n` +\n ` Middleware is collected from the main route chain only.\\n` +\n ` The slot resolver does not run middleware — this file is silently dead.\\n` +\n ` (access.ts in slots does run via SlotAccessGate; middleware.ts does not.)\\n\\n` +\n ` To fix: Move the middleware logic into access.ts for slot-scoped auth,\\n` +\n ` or into a middleware.ts on the main route chain outside the slot.\\n`,\n level: 'error',\n });\n }\n for (const child of node.children) {\n collectSlotMiddleware(child, slotName, warnings);\n }\n for (const [nestedSlotName, nestedSlot] of Object.entries(node.slots)) {\n collectSlotMiddleware(nestedSlot, nestedSlotName, warnings);\n }\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push(style('dim', w.details));\n }\n }\n\n return lines.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,mBAAmB,MAAiB,QAA0C;CAC5F,MAAM,sBAAM,IAAI,IAAyB;CAEzC,SAAS,KAAK,MAAmB,QAAgB,UAAwB;EACvE,IAAI,IAA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AW,GAAG,OAAO;CAElC,MAAM,SAAS,SAAS,QAAQ,MAAM,EAAE,UAAU,OAAO;CACzD,MAAM,QAAQ,SAAS,QAAQ,MAAM,EAAE,UAAU,MAAM;CAEvD,MAAM,QAAkB,CAAC;CAEzB,IAAI,OAAO,SAAS,GAAG;EACrB,MAAM,KACJ,GAAG,MAAM,CAAC,OAAO,MAAM,GAAG,UAAU,EAAE,GAAG,MAAM,OAAO,GAAG,OAAO,OAAO,sBAAsB,OAAO,WAAW,IAAI,MAAM,GAAG,EAAE,GAChI;EACA,KAAK,MAAM,KAAK,QAAQ;GACtB,MAAM,KAAK,EAAE;GACb,MAAM,KAAK,KAAK,MAAM,OAAO,GAAG,EAAE,GAAG,EAAE,SAAS;GAChD,MAAM,KAAK,MAAM,OAAO,EAAE,OAAO,CAAC;EACpC;CACF;CAEA,IAAI,MAAM,SAAS,GAAG;EACpB,IAAI,OAAO,SAAS,GAAG,MAAM,KAAK,EAAE;EACpC,MAAM,KACJ,GAAG,MAAM,CAAC,UAAU,MAAM,GAAG,UAAU,EAAE,GAAG,MAAM,UAAU,GAAG,MAAM,OAAO,wBAAwB,MAAM,WAAW,IAAI,MAAM,GAAG,EAAE,GACtI;EACA,KAAK,MAAM,KAAK,OAAO;GACrB,MAAM,KAAK,EAAE;GACb,MAAM,KAAK,KAAK,MAAM,UAAU,GAAG,EAAE,GAAG,EAAE,SAAS;GACnD,MAAM,KAAK,MAAM,OAAO,EAAE,OAAO,CAAC;EACpC;CACF;CAEA,OAAO,MAAM,KAAK,IAAI;AACxB"}
package/dist/cli.js CHANGED
@@ -179,7 +179,7 @@ async function runPreview(options, _deps) {
179
179
  * `--project` names the tsconfig handed to tsgo.
180
180
  */
181
181
  async function runCheck(options, _deps) {
182
- const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-BE9BnXwi.js");
182
+ const { checkRoutes, runTypeCheck } = await import("./_chunks/cli-check-CetL-6Us.js");
183
183
  const { root } = await checkRoutes({ viteConfigFile: options.config }, _deps);
184
184
  await runTypeCheck({
185
185
  root,
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { a as generateManifestModule, c as formatMissingPeers, i as VIRTUAL_IDS, l as reportConfigErrors, n as timberDevServer, o as generateSchemaModule, s as checkPeerDependencies, u as validateConfig } from "./_chunks/dev-server-BZxFJNih.js";
2
2
  import { i as resolveRenderTimeoutMs } from "./_chunks/render-timeout-MrrqD1wd.js";
3
3
  import { n as scanRoutes } from "./_chunks/scanner-B6V2RqqF.js";
4
- import { c as writeRouteCodegen, i as readRouteOptions, l as buildDirToRouteMap, n as formatConventionWarnings, r as lintConventions, s as flushCodegenWrites, t as checkAppDirExists } from "./_chunks/convention-lint-DkSDlsPH.js";
4
+ import { c as writeRouteCodegen, i as readRouteOptions, l as buildDirToRouteMap, n as formatConventionWarnings, r as lintConventions, s as flushCodegenWrites, t as checkAppDirExists } from "./_chunks/convention-lint-BWbKAV4x.js";
5
5
  import { r as validateSchemaAgainstRoutes, t as collectLeafRoutes } from "./_chunks/walkers-BAZoAlfI.js";
6
6
  import { i as poisonPillSource, r as markerFor, t as EXPLICIT_MARKERS } from "./_chunks/poison-rules-Bmz-lCPi.js";
7
7
  import { t as writeFileAtomic } from "./_chunks/write-file-atomic-DW8m_Atv.js";
@@ -61,6 +61,7 @@
61
61
  "params/resolve-schema.ts": "params/resolve-schema.js",
62
62
  "routes/href.ts": "routes/href.js",
63
63
  "routing/collision-probe.ts": "routing/collision-probe.js",
64
+ "routing/descendant-params.ts": "routing/descendant-params.js",
64
65
  "routing/interception-overlap.ts": "routing/interception-overlap.js",
65
66
  "routing/interception.ts": "routing/interception.js",
66
67
  "routing/segment-classify.ts": "routing/segment-classify.js",
@@ -0,0 +1,28 @@
1
+ import { effectiveUrlSegment } from "./segment-classify.js";
2
+ // src/routing/descendant-params.ts
3
+ var MEMO = new WeakMap();
4
+ var RENDERS_PAGE = new WeakMap();
5
+ function rendersPage(node) {
6
+ let found = RENDERS_PAGE.get(node);
7
+ if (found === void 0) {
8
+ found = !!node.page || node.children.some(rendersPage);
9
+ RENDERS_PAGE.set(node, found);
10
+ }
11
+ return found;
12
+ }
13
+ function childrenChainParams(node) {
14
+ const memo = MEMO.get(node);
15
+ if (memo) return memo;
16
+ const params = new Map();
17
+ for (const child of node.children) {
18
+ if (!rendersPage(child)) continue;
19
+ const identity = effectiveUrlSegment(child);
20
+ if (identity.paramName && !params.has(identity.paramName)) params.set(identity.paramName, identity);
21
+ for (const [name, deeper] of childrenChainParams(child)) if (!params.has(name)) params.set(name, deeper);
22
+ }
23
+ MEMO.set(node, params);
24
+ return params;
25
+ }
26
+ export { childrenChainParams };
27
+
28
+ //# sourceMappingURL=descendant-params.js.map