@timber-js/app 0.2.0-alpha.236 → 0.2.0-alpha.238

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 (105) hide show
  1. package/dist/_chunks/chains-CmzbpG-6.js +1 -0
  2. package/dist/_chunks/{chains-BsGKkMTK.js → chains-DMoHX4yH.js} +2 -2
  3. package/dist/_chunks/{chains-BsGKkMTK.js.map → chains-DMoHX4yH.js.map} +1 -1
  4. package/dist/_chunks/{classify-cmE0Gins.js → classify-BwyAd-dZ.js} +3 -3
  5. package/dist/_chunks/{classify-cmE0Gins.js.map → classify-BwyAd-dZ.js.map} +1 -1
  6. package/dist/_chunks/{cli-check-BwiahbTC.js → cli-check-DQAD9MLo.js} +3 -3
  7. package/dist/_chunks/{cli-check-BwiahbTC.js.map → cli-check-DQAD9MLo.js.map} +1 -1
  8. package/dist/_chunks/{cli-schema-sync-Brw7kTmm.js → cli-schema-sync-C_xNLqBj.js} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js → cli-schema-sync-CmGls3dc.js} +2 -2
  10. package/dist/_chunks/{cli-schema-sync-B2ldclRO.js.map → cli-schema-sync-CmGls3dc.js.map} +1 -1
  11. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js → client-dep-entries-C5BTQtFS.js} +2 -2
  12. package/dist/_chunks/{client-dep-entries-C1nMlLKV.js.map → client-dep-entries-C5BTQtFS.js.map} +1 -1
  13. package/dist/_chunks/{convention-lint-CLpuzY5h.js → convention-lint-GQA6WTRo.js} +2 -2
  14. package/dist/_chunks/{convention-lint-CLpuzY5h.js.map → convention-lint-GQA6WTRo.js.map} +1 -1
  15. package/dist/_chunks/dev-server--4_Ogy_6.js +1 -0
  16. package/dist/_chunks/{dev-server-lrdpD7Ws.js → dev-server-Cr3_Fu5A.js} +244 -26
  17. package/dist/_chunks/dev-server-Cr3_Fu5A.js.map +1 -0
  18. package/dist/_chunks/{flight-source-node-BO_xD9jC.js → flight-source-node-BsrlUjMO.js} +7 -3
  19. package/dist/_chunks/flight-source-node-BsrlUjMO.js.map +1 -0
  20. package/dist/_chunks/{scanner-CrB_h6FA.js → interception-CtNt9jPt.js} +169 -1043
  21. package/dist/_chunks/interception-CtNt9jPt.js.map +1 -0
  22. package/dist/_chunks/{live-graph-ChuFfmLi.js → live-graph-HcLScfiV.js} +4 -4
  23. package/dist/_chunks/{live-graph-ChuFfmLi.js.map → live-graph-HcLScfiV.js.map} +1 -1
  24. package/dist/_chunks/{metadata-routes-BL26HCDd.js → metadata-routes-MXNjWOt5.js} +60 -2
  25. package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -0
  26. package/dist/_chunks/{node-response-DNNnKnoS.js → node-response-omewa8e6.js} +20 -3
  27. package/dist/_chunks/node-response-omewa8e6.js.map +1 -0
  28. package/dist/_chunks/{poison-scan-CJ9QfJWb.js → poison-scan-DONdiCGX.js} +2 -2
  29. package/dist/_chunks/{poison-scan-CJ9QfJWb.js.map → poison-scan-DONdiCGX.js.map} +1 -1
  30. package/dist/_chunks/render-timeout-MrrqD1wd.js.map +1 -1
  31. package/dist/_chunks/scanner-DSAJjH0x.js +1043 -0
  32. package/dist/_chunks/scanner-DSAJjH0x.js.map +1 -0
  33. package/dist/_chunks/{walkers-BUvpsb2Q.js → walkers-96YopJds.js} +3 -3
  34. package/dist/_chunks/{walkers-BUvpsb2Q.js.map → walkers-96YopJds.js.map} +1 -1
  35. package/dist/analyze/crawl-entry.js +3 -3
  36. package/dist/analyze/graph-command.js +2 -2
  37. package/dist/cli.js +3 -3
  38. package/dist/config-types.d.ts +11 -0
  39. package/dist/config-types.d.ts.map +1 -1
  40. package/dist/config-validation.d.ts.map +1 -1
  41. package/dist/index.js +6 -155
  42. package/dist/index.js.map +1 -1
  43. package/dist/native/rsc/server/abort-scope.js +6 -2
  44. package/dist/native/rsc/server/abort-scope.js.map +1 -1
  45. package/dist/native/rsc/server/flight-source-node.js +6 -2
  46. package/dist/native/rsc/server/flight-source-node.js.map +1 -1
  47. package/dist/native/rsc/server/pipeline-helpers.js +2 -2
  48. package/dist/native/rsc/server/pipeline-helpers.js.map +1 -1
  49. package/dist/native/rsc/server/pipeline-metadata-route.js +2 -2
  50. package/dist/native/rsc/server/pipeline-metadata-route.js.map +1 -1
  51. package/dist/native/rsc/server/render-timeout.js.map +1 -1
  52. package/dist/native/rsc/server/safe-load.js +14 -2
  53. package/dist/native/rsc/server/safe-load.js.map +1 -1
  54. package/dist/native/ssr/server/abort-scope.js +6 -2
  55. package/dist/native/ssr/server/abort-scope.js.map +1 -1
  56. package/dist/native/ssr/server/flight-source-node.js +6 -2
  57. package/dist/native/ssr/server/flight-source-node.js.map +1 -1
  58. package/dist/native/ssr/server/pipeline-helpers.js +2 -2
  59. package/dist/native/ssr/server/pipeline-helpers.js.map +1 -1
  60. package/dist/native/ssr/server/pipeline-metadata-route.js +2 -2
  61. package/dist/native/ssr/server/pipeline-metadata-route.js.map +1 -1
  62. package/dist/native/ssr/server/render-timeout.js +3 -4
  63. package/dist/native/ssr/server/render-timeout.js.map +1 -1
  64. package/dist/native/ssr/server/safe-load.js +10 -1
  65. package/dist/native/ssr/server/safe-load.js.map +1 -1
  66. package/dist/plugins/dev-precompile.d.ts +42 -14
  67. package/dist/plugins/dev-precompile.d.ts.map +1 -1
  68. package/dist/plugins/dev-server.d.ts.map +1 -1
  69. package/dist/routing/index.js +3 -2
  70. package/dist/routing/manifest-codegen.d.ts +2 -0
  71. package/dist/routing/manifest-codegen.d.ts.map +1 -1
  72. package/dist/server/abort-scope.d.ts +7 -0
  73. package/dist/server/abort-scope.d.ts.map +1 -1
  74. package/dist/server/flight-source-node.d.ts.map +1 -1
  75. package/dist/server/internal.js +46 -7
  76. package/dist/server/internal.js.map +1 -1
  77. package/dist/server/render-timeout.d.ts.map +1 -1
  78. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  79. package/dist/server/safe-load.d.ts +22 -0
  80. package/dist/server/safe-load.d.ts.map +1 -1
  81. package/docs/api/34-api-config.mdx +18 -0
  82. package/package.json +1 -1
  83. package/src/config-types.ts +11 -0
  84. package/src/config-validation.ts +15 -8
  85. package/src/plugins/dev-precompile.ts +108 -20
  86. package/src/plugins/dev-server.ts +12 -11
  87. package/src/routing/manifest-codegen.ts +2 -2
  88. package/src/server/abort-scope.ts +20 -1
  89. package/src/server/flight-source-node.ts +11 -2
  90. package/src/server/pipeline-helpers.ts +2 -2
  91. package/src/server/pipeline-metadata-route.ts +2 -2
  92. package/src/server/render-timeout.ts +8 -5
  93. package/src/server/rsc-entry/index.ts +5 -0
  94. package/src/server/safe-load.ts +53 -1
  95. package/dist/_chunks/chains-DHmoKxkO.js +0 -1
  96. package/dist/_chunks/dev-server-BGGGhHXx.js +0 -1
  97. package/dist/_chunks/dev-server-lrdpD7Ws.js.map +0 -1
  98. package/dist/_chunks/flight-source-node-BO_xD9jC.js.map +0 -1
  99. package/dist/_chunks/metadata-routes-BL26HCDd.js.map +0 -1
  100. package/dist/_chunks/node-response-DNNnKnoS.js.map +0 -1
  101. package/dist/_chunks/scanner-CrB_h6FA.js.map +0 -1
  102. package/dist/_chunks/segment-keys-Y60KNc8C.js +0 -61
  103. package/dist/_chunks/segment-keys-Y60KNc8C.js.map +0 -1
  104. package/dist/_chunks/tree-match-Bqdr9szG.js +0 -168
  105. package/dist/_chunks/tree-match-Bqdr9szG.js.map +0 -1
@@ -1,12 +1,170 @@
1
- import { i as DEFAULT_PAGE_EXTENSIONS, n as classifyUrlSegment, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
2
- import { n as treePathDepth, t as computeSegmentTreePaths } from "./segment-keys-Y60KNc8C.js";
3
- import { t as matchUrlParts } from "./tree-match-Bqdr9szG.js";
4
- import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-BL26HCDd.js";
5
- import { b as swallow } from "./logger-DDLtp5e-.js";
6
- import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
7
- import { parseAst } from "vite";
8
- import { basename, extname, join } from "node:path";
9
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
1
+ import { c as computeSegmentTreePaths, l as treePathDepth } from "./metadata-routes-MXNjWOt5.js";
2
+ import { n as classifyUrlSegment, r as effectiveUrlSegment } from "./segment-classify-Ho8jXWeC.js";
3
+ // src/server/tree-match.ts
4
+ /**
5
+ * Match URL path parts against a segment tree.
6
+ *
7
+ * Walks the tree depth-first with backtracking, applying priority
8
+ * ordering globally across group boundaries. Returns the matched
9
+ * segment chain and collected params, or null if no route matches.
10
+ *
11
+ * By default, a match requires a terminal node (one with `page` or
12
+ * `route`) at the leaf. Pass `{ requireTerminal: false }` to match
13
+ * any segment (used by metadata route matching).
14
+ *
15
+ * @param root The root segment node to start matching from.
16
+ * @param parts URL path parts (e.g. ['blog', 'hello-world']).
17
+ * Empty array matches the root itself (if terminal).
18
+ */
19
+ function matchUrlParts(root, parts, options) {
20
+ const chain = [];
21
+ const params = {};
22
+ if (matchNode(root, parts, 0, chain, params, options?.requireTerminal ?? true)) return {
23
+ chain,
24
+ params
25
+ };
26
+ return null;
27
+ }
28
+ /**
29
+ * Flatten children through group segments.
30
+ *
31
+ * Groups are transparent for URL matching — their non-group descendants
32
+ * are returned with the chain of group nodes leading to them. This lets
33
+ * the caller apply priority ordering (static > dynamic > catch-all >
34
+ * optional-catch-all) across all groups uniformly instead of per-group.
35
+ */
36
+ function collectEffectiveChildren(node, groupChain = []) {
37
+ const result = [];
38
+ for (const child of node.children) if (child.segmentType === "group") {
39
+ const nested = collectEffectiveChildren(child, [...groupChain, child]);
40
+ result.push(...nested);
41
+ } else result.push({
42
+ child,
43
+ groupChain
44
+ });
45
+ return result;
46
+ }
47
+ /** A node is terminal if it can serve a response (has a page or route handler). */
48
+ function isTerminal(node) {
49
+ return !!(node.page || node.route);
50
+ }
51
+ /**
52
+ * Specificity tier for a segment. Lower = more specific. Matches the
53
+ * priority order in `matchNode`: static > affixed-dynamic > bare-dynamic >
54
+ * catch-all > optional-catch-all.
55
+ */
56
+ function segmentTier(node) {
57
+ if (node.segmentType === "static") return 0;
58
+ if (node.segmentType === "dynamic" && (node.paramPrefix || node.paramSuffix)) return 1;
59
+ if (node.segmentType === "dynamic") return 2;
60
+ if (node.segmentType === "catch-all") return 3;
61
+ if (node.segmentType === "optional-catch-all") return 4;
62
+ return 2;
63
+ }
64
+ /**
65
+ * Score a bare-dynamic candidate by running `matchNode` against its subtree
66
+ * with the remaining URL parts, then reading the tier of each segment in
67
+ * the matched chain. Returns a tier array that is compared lexicographically
68
+ * — the candidate whose chain has a lower tier at the first differing
69
+ * position is more specific.
70
+ *
71
+ * Delegates entirely to `matchNode`, so every segment type and priority
72
+ * rule is inherited automatically — no second copy to drift.
73
+ */
74
+ function subtreeMatchScore(node, parts, index, requireTerminal) {
75
+ const chain = [];
76
+ if (!matchNode(node, parts, index, chain, {}, requireTerminal)) return [];
77
+ return chain.slice(1).map((seg) => segmentTier(seg));
78
+ }
79
+ /**
80
+ * Compare two tier arrays lexicographically. Negative means `a` is more
81
+ * specific (should be tried first).
82
+ */
83
+ function compareTierArrays(a, b) {
84
+ const len = Math.max(a.length, b.length);
85
+ for (let i = 0; i < len; i++) {
86
+ const ta = i < a.length ? a[i] : 5;
87
+ const tb = i < b.length ? b[i] : 5;
88
+ if (ta !== tb) return ta - tb;
89
+ }
90
+ return 0;
91
+ }
92
+ /** Combined affix length for specificity ordering. */
93
+ function affixLength(node) {
94
+ return (node.paramPrefix?.length ?? 0) + (node.paramSuffix?.length ?? 0);
95
+ }
96
+ /**
97
+ * Recursive depth-first matcher with backtracking.
98
+ *
99
+ * Mutates `chain` and `params` in place for performance; backtracks
100
+ * (restores previous state) when a candidate doesn't lead to a match.
101
+ */
102
+ function matchNode(node, parts, index, chain, params, requireTerminal) {
103
+ chain.push(node);
104
+ if (index >= parts.length) {
105
+ if (!requireTerminal || isTerminal(node)) return true;
106
+ for (const child of node.children) if (child.segmentType === "group") {
107
+ if (matchNode(child, parts, index, chain, params, requireTerminal)) return true;
108
+ }
109
+ const effective = collectEffectiveChildren(node);
110
+ for (const { child, groupChain } of effective) if (child.segmentType === "optional-catch-all" && (!requireTerminal || isTerminal(child))) {
111
+ chain.push(...groupChain, child);
112
+ return true;
113
+ }
114
+ chain.pop();
115
+ return false;
116
+ }
117
+ const part = parts[index];
118
+ const effective = collectEffectiveChildren(node);
119
+ for (const { child, groupChain } of effective) if (child.segmentType === "static" && child.segmentName === part) {
120
+ chain.push(...groupChain);
121
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
122
+ chain.length -= groupChain.length;
123
+ }
124
+ const affixed = effective.filter(({ child }) => child.segmentType === "dynamic" && child.paramName && (child.paramPrefix || child.paramSuffix));
125
+ affixed.sort((a, b) => affixLength(b.child) - affixLength(a.child));
126
+ for (const { child, groupChain } of affixed) {
127
+ const prefix = child.paramPrefix ?? "";
128
+ const suffix = child.paramSuffix ?? "";
129
+ if (part.length > prefix.length + suffix.length && (!prefix || part.startsWith(prefix)) && (!suffix || part.endsWith(suffix))) {
130
+ const value = part.slice(prefix.length, part.length - (suffix.length || 0));
131
+ chain.push(...groupChain);
132
+ const prev = params[child.paramName];
133
+ params[child.paramName] = value;
134
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
135
+ chain.length -= groupChain.length;
136
+ if (prev !== void 0) params[child.paramName] = prev;
137
+ else delete params[child.paramName];
138
+ }
139
+ }
140
+ const bareDynamic = effective.filter(({ child }) => child.segmentType === "dynamic" && child.paramName && !child.paramPrefix && !child.paramSuffix);
141
+ if (bareDynamic.length > 1 && index + 1 < parts.length) {
142
+ const scores = /* @__PURE__ */ new Map();
143
+ for (const { child } of bareDynamic) scores.set(child, subtreeMatchScore(child, parts, index + 1, requireTerminal));
144
+ bareDynamic.sort((a, b) => compareTierArrays(scores.get(a.child), scores.get(b.child)));
145
+ }
146
+ for (const { child, groupChain } of bareDynamic) {
147
+ chain.push(...groupChain);
148
+ const prev = params[child.paramName];
149
+ params[child.paramName] = part;
150
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
151
+ chain.length -= groupChain.length;
152
+ if (prev !== void 0) params[child.paramName] = prev;
153
+ else delete params[child.paramName];
154
+ }
155
+ for (const { child, groupChain } of effective) if (child.segmentType === "catch-all" && child.paramName && (!requireTerminal || isTerminal(child))) {
156
+ chain.push(...groupChain, child);
157
+ params[child.paramName] = parts.slice(index);
158
+ return true;
159
+ }
160
+ for (const { child, groupChain } of effective) if (child.segmentType === "optional-catch-all" && child.paramName && (!requireTerminal || isTerminal(child))) {
161
+ chain.push(...groupChain, child);
162
+ params[child.paramName] = parts.slice(index);
163
+ return true;
164
+ }
165
+ chain.pop();
166
+ return false;
167
+ }
10
168
  // src/routing/collision-probe.ts
11
169
  /**
12
170
  * Find a URL in this collision space whose winner depends on `children` order,
@@ -1011,1038 +1169,6 @@ function computeInterceptedBase(parentUrlPath, marker) {
1011
1169
  for (let i = 0; i < climb; i++) parts.pop();
1012
1170
  return parts.length === 0 ? "/" : `/${parts.join("/")}`;
1013
1171
  }
1014
- // src/routing/collision-spaces.ts
1015
- /**
1016
- * Validate that no two pages/routes in one collision space answer the same URL.
1017
- *
1018
- * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim
1019
- * /login — the scanner must detect and reject this at build time.
1020
- *
1021
- * Each parallel slot is validated as its OWN collision space: a slot's pages
1022
- * intentionally share URL paths with the parent tree (that's the point of
1023
- * parallel routes), but two route groups INSIDE one slot claiming the same
1024
- * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.
1025
- */
1026
- function validateRouteGroupCollisions(root) {
1027
- validateCollisionSpace(root, "", root.urlPath);
1028
- }
1029
- /**
1030
- * Validate one collision space — the main tree, or one parallel slot.
1031
- *
1032
- * **Two checks, and the difference between them matters.** Two leaves at the
1033
- * same `urlPath` are decided by string equality, which is exact and needs no
1034
- * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs
1035
- * whatever the precedence rules are, and naming the shared path is the clearest
1036
- * thing to tell the author.
1037
- *
1038
- * Everything else is decided by asking the matcher, through the shared oracle
1039
- * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses
1040
- * every pair that matches the same URLs while being *spelled* differently:
1041
- * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority
1042
- * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`
1043
- * because an optional catch-all also matches zero parts. Both built before
1044
- * TIM-1308 with filesystem enumeration order deciding which page renders,
1045
- * which is precisely what this validator and `validateAffixedSiblingConflicts`
1046
- * exist to reject.
1047
- *
1048
- * Segment *kinds* stay distinct without any special-casing here, because the
1049
- * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside
1050
- * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is
1051
- * not reported. So does an affixed sibling against a bare one; the
1052
- * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and
1053
- * duplicating it here would double-report.
1054
- */
1055
- function validateCollisionSpace(spaceRoot, segmentPath, base) {
1056
- const leaves = [];
1057
- collectRoutableLeaves(spaceRoot, /* @__PURE__ */ new Map(), segmentPath, [], leaves, base);
1058
- const collision = findOrderDependentCollision(spaceRoot, leaves, base);
1059
- if (!collision) return;
1060
- throw new Error(`Build error: route collision — two pages/routes answer the same URL.\n URL: ${collision.url}\n File 1: ${collision.first}\n File 2: ${collision.second}\nBoth match it, so which one renders would be decided by filesystem enumeration order — renaming a route group can flip it. Rename or move one of them.\nRoutes are compared by the URLs they match, not by how they are spelled: [id] and [slug] match the same URLs, and an optional catch-all also matches with zero segments.`);
1061
- }
1062
- /**
1063
- * Walk one collision space and collect its routable leaves (page or route
1064
- * files), throwing on an exact `urlPath` collision. Each slot recurses as its
1065
- * OWN space — slots are parallel routes that intentionally share URL paths with
1066
- * their parent tree, but collisions within a single slot are real errors.
1067
- *
1068
- * The early return at an intercepting node drops that subtree's own pages from
1069
- * this space, but not its slots: a slot is its own collision space wherever it
1070
- * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before
1071
- * returning.
1072
- *
1073
- * `chain` accumulates the URL-contributing nodes from the space root down, for
1074
- * the probe oracle. Route groups are excluded because they are transparent for
1075
- * matching, and the space root itself is excluded because `matchUrlParts`
1076
- * matches parts against its *children* — the root consumes nothing.
1077
- */
1078
- function collectRoutableLeaves(node, seen, segmentPath, chain, leaves, base) {
1079
- const currentPath = segmentPath ? `${segmentPath}/${node.segmentName}` : node.segmentName || "(root)";
1080
- if (node.segmentType === "intercepting") {
1081
- validateSlotsInsideInterceptingSubtree(node, currentPath, interceptedBaseOf(node, node.urlPath));
1082
- return;
1083
- }
1084
- const routableFile = node.page ?? node.route;
1085
- if (routableFile) {
1086
- const existing = seen.get(node.urlPath);
1087
- if (existing) throw new Error(`Build error: route collision — multiple route groups produce a page/route at the same URL path.\n URL path: ${urlFromChain(base, chain)}\n File 1: ${existing.filePath} (via ${existing.segmentPath})\n File 2: ${routableFile.filePath} (via ${currentPath})\nEach URL path must map to exactly one page or route handler. Rename or move one of the conflicting files.`);
1088
- seen.set(node.urlPath, {
1089
- filePath: routableFile.filePath,
1090
- segmentPath: currentPath
1091
- });
1092
- leaves.push({
1093
- filePath: routableFile.filePath,
1094
- chain
1095
- });
1096
- }
1097
- for (const child of node.children) collectRoutableLeaves(child, seen, currentPath, child.segmentType === "group" ? chain : [...chain, child], leaves, base);
1098
- for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));
1099
- }
1100
- /**
1101
- * Validate every parallel slot nested anywhere inside an intercepting subtree.
1102
- *
1103
- * Two walks each skip these slots for their own good reason, and together they
1104
- * left them checked by nothing: `collectRoutableLeaves` returns at the
1105
- * intercepting node before it reaches them, and `walkInterceptedLeaves`
1106
- * deliberately does not descend slots — correct for rewrite generation, since a
1107
- * slot inside an intercepting subtree produces no rewrite. But "produces no
1108
- * rewrite" answers the rewrite question and not the resolution one, so
1109
- * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor
1110
- * built with filesystem order picking the page — the ordinary per-slot
1111
- * collision that fails the build anywhere else in the tree (codex, on PR #1002).
1112
- *
1113
- * A slot is its own collision space wherever it sits, so each one is validated
1114
- * as one.
1115
- *
1116
- * **Which interception shape this still applies to.** TIM-1311 answered the
1117
- * question this was written under — whether such a slot renders at all — and
1118
- * the answer is per-shape:
1119
- *
1120
- * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node
1121
- * joins the main route chain, so `route-element-builder.ts` resolves slots on
1122
- * it and below it like any other chain segment. They render, and this is the
1123
- * space where the check is load-bearing.
1124
- * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another
1125
- * slot's subtree, which no renderer descends for slots — so it never renders,
1126
- * and `validateSlotPlacement` now rejects the placement before this runs.
1127
- * That rule subsumes this one for the modal shape rather than conflicting
1128
- * with it, exactly as anticipated.
1129
- *
1130
- * So this walk is reached only for children-path interceptors in a valid tree.
1131
- * It is not narrowed to them: the rule it states — a slot is its own collision
1132
- * space wherever it sits — is shape-independent, and making it conditional on a
1133
- * property the placement validator already guarantees would just be a second
1134
- * place for the two to disagree.
1135
- *
1136
- * The walk covers the whole subtree, not just the interceptor's direct slot
1137
- * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the
1138
- * same reason as `(...)photo/@side`.
1139
- */
1140
- function validateSlotsInsideInterceptingSubtree(node, segmentPath, base) {
1141
- for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, segmentPath, base);
1142
- for (const child of node.children) validateSlotsInsideInterceptingSubtree(child, `${segmentPath}/${child.segmentName}`, childInterceptedBase(child, base));
1143
- }
1144
- /**
1145
- * The URL a leaf answers, built from its space's base and its own chain.
1146
- *
1147
- * Read instead of `node.urlPath` because `urlPath` inside an intercepting
1148
- * subtree is parent-relative and is not an address — the collision URL has to
1149
- * be one the author can actually find. Outside an intercepting subtree the two
1150
- * are identical by construction: the base is the space root's `urlPath` and the
1151
- * chain is every URL-contributing segment below it.
1152
- */
1153
- function urlFromChain(base, chain) {
1154
- if (chain.length === 0) return base || "/";
1155
- const tail = chain.map((n) => n.segmentName).join("/");
1156
- return `${base === "/" ? "" : base}/${tail}`;
1157
- }
1158
- /**
1159
- * The intercepted URL an intercepting directory's own page sits at.
1160
- *
1161
- * `urlPath` inside an intercepting subtree is deliberately parent-relative and
1162
- * is **not** an address (see design/07-routing.md §"Why urlPath Stays
1163
- * Parent-Relative Inside an Intercepting Subtree"), so a collision reported
1164
- * from one names a URL the author cannot find. The intercepted base is the real
1165
- * address, and it is what rewrite generation and the interception collision
1166
- * validator both already use.
1167
- */
1168
- function interceptedBaseOf(node, ownerUrlPath) {
1169
- return computeInterceptedUrlBase(ownerUrlPath, node.interceptionMarker ?? "(.)", node.interceptedSegmentName ?? node.segmentName);
1170
- }
1171
- /**
1172
- * Extend an intercepted base by one child segment.
1173
- *
1174
- * Route groups are transparent and contribute nothing. A nested intercepting
1175
- * node re-bases from its own marker rather than appending — that tree is
1176
- * rejected by `validateInterceptionPlacement`, but collision validation runs
1177
- * first, so it still has to produce a sensible URL rather than one containing a
1178
- * literal "(.)b".
1179
- */
1180
- function childInterceptedBase(child, base) {
1181
- if (child.segmentType === "group") return base;
1182
- if (child.segmentType === "intercepting") return interceptedBaseOf(child, base);
1183
- return base === "/" ? `/${child.segmentName}` : `${base}/${child.segmentName}`;
1184
- }
1185
- // src/routing/slot-placement.ts
1186
- /**
1187
- * Reject every parallel slot that no renderer reaches.
1188
- *
1189
- * **Where slots are resolved.** Two places read `segment.slots`, and both walk
1190
- * the main route chain: `route-element-builder.ts` (the RSC render).
1191
- * It is not reachable from inside a slot. The slot's own
1192
- * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched
1193
- * chain to apply that chain's layouts, error boundaries and access gates
1194
- * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`
1195
- * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and
1196
- * everything below it is dead: the file is scanned, typed, code-split and
1197
- * shipped, and no request can render it.
1198
- *
1199
- * That is the TIM-1278 failure — a directory that silently never renders —
1200
- * and the reason it is a build error rather than a documented limit is that
1201
- * nothing at request time can report it. A slot that does not match renders
1202
- * `default.tsx` or `null`, which is exactly what a slot the resolver never
1203
- * looked at also produces, so the author sees the *designed* behaviour of a
1204
- * non-matching slot and has no signal to distinguish it from a slot that
1205
- * cannot match at all.
1206
- *
1207
- * **Interception is incidental.** TIM-1311 arrived as
1208
- * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the
1209
- * identical `feed/@modal/photo/@side` never renders either, for the same
1210
- * reason and with no marker anywhere. Rejecting only the intercepting spelling
1211
- * would have drawn a line the author cannot see from the directory names.
1212
- *
1213
- * The children-path interception shape is **not** affected and must not be:
1214
- * its intercepting node joins the main chain (`server/children-interception.ts`
1215
- * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary
1216
- * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below
1217
- * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`
1218
- * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot
1219
- * boundary, which is what this walk tracks — not the marker.
1220
- */
1221
- function validateSlotPlacement(root) {
1222
- walkForSlotPlacement(root, "", null);
1223
- }
1224
- /**
1225
- * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or
1226
- * above `node`, or null on the main chain. It is carried rather than recomputed
1227
- * so the error can name the slot that swallows the offender — "this is inside
1228
- * @modal" is the part of the diagnosis the author cannot see from the offending
1229
- * path alone.
1230
- */
1231
- function walkForSlotPlacement(node, path, enclosingSlotPath) {
1232
- for (const [slotName, slotNode] of Object.entries(node.slots)) {
1233
- const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;
1234
- if (enclosingSlotPath !== null) throwNestedSlot(slotPath, enclosingSlotPath);
1235
- walkForSlotPlacement(slotNode, slotPath, slotPath);
1236
- }
1237
- for (const child of node.children) walkForSlotPlacement(child, path ? `${path}/${child.segmentName}` : child.segmentName, enclosingSlotPath);
1238
- }
1239
- function throwNestedSlot(slotPath, enclosingSlotPath) {
1240
- throw new Error(`Build error: parallel slot nested inside another parallel slot.\n Directory: app/${slotPath}\n Inside: app/${enclosingSlotPath}\nA parallel slot is resolved only for a segment on the matched route chain, and a slot's own subtree is never on that chain — the slot resolver walks the slot's matched chain to apply its layouts, error boundaries and access gates, and never looks at slots declared inside it. So app/${slotPath} and everything below it can never render, and no request-time signal can tell you: an unreachable slot produces exactly what a slot that simply did not match produces.\nDeclare the slot on a segment of the main route chain instead, or move its pages into app/${enclosingSlotPath}'s own subtree.\nSee design/07-routing.md §"Parallel Routes".`);
1241
- }
1242
- // src/routing/file-cache.ts
1243
- var cache = /* @__PURE__ */ new Map();
1244
- /**
1245
- * Read a file's text content, returning a cached copy when the file
1246
- * hasn't been modified since the last read (checked via mtime + size).
1247
- *
1248
- * Falls back to a fresh read on any stat/read error.
1249
- */
1250
- function readFileCached(filePath) {
1251
- try {
1252
- const stat = statSync(filePath);
1253
- const entry = cache.get(filePath);
1254
- if (entry && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) return entry.content;
1255
- const content = readFileSync(filePath, "utf-8");
1256
- cache.set(filePath, {
1257
- mtimeMs: stat.mtimeMs,
1258
- size: stat.size,
1259
- content
1260
- });
1261
- return content;
1262
- } catch {
1263
- cache.delete(filePath);
1264
- return readFileSync(filePath, "utf-8");
1265
- }
1266
- }
1267
- // src/routing/export-detect.ts
1268
- /**
1269
- * AST-based export detection for route files.
1270
- *
1271
- * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and
1272
- * default exports, replacing the regex-based approach that was fragile
1273
- * with TypeScript syntax (type exports, `as` aliases, comments, etc.).
1274
- */
1275
- function tryParse(source) {
1276
- try {
1277
- return parseAst(source, { lang: "tsx" });
1278
- } catch {
1279
- return null;
1280
- }
1281
- }
1282
- /**
1283
- * Collect all named export identifiers from a parsed program.
1284
- * Handles: `export function X`, `export const X`, `export { X }`,
1285
- * `export { X } from '...'`, `export { Y as X }`.
1286
- */
1287
- function collectNamedExports(program) {
1288
- const names = /* @__PURE__ */ new Set();
1289
- for (const stmt of program.body) {
1290
- if (stmt.type !== "ExportNamedDeclaration") continue;
1291
- if (stmt.exportKind === "type") continue;
1292
- if (stmt.declaration) {
1293
- if (stmt.declaration.id?.name) names.add(stmt.declaration.id.name);
1294
- if (stmt.declaration.declarations) {
1295
- for (const decl of stmt.declaration.declarations) if (decl.id?.name) names.add(decl.id.name);
1296
- }
1297
- }
1298
- if (stmt.specifiers) for (const spec of stmt.specifiers) {
1299
- if (spec.exportKind === "type") continue;
1300
- if (spec.exported?.name && spec.exported.name !== "default") names.add(spec.exported.name);
1301
- }
1302
- }
1303
- return names;
1304
- }
1305
- /**
1306
- * The specifier exporting a *runtime* default from this statement, if any.
1307
- *
1308
- * Type-only exports erase, so they are not default exports at runtime — and
1309
- * TypeScript spells that two ways, on two different nodes: `export type { X as
1310
- * default }` marks the **statement**, `export { type X as default }` marks the
1311
- * **specifier**. Both have to be checked, or a type alias reads as a component:
1312
- * a status file whose only default is a type has nothing for the error boundary
1313
- * to receive (the renderer's `mod?.default` skips it), so treating it as one
1314
- * would fail a build over a file that cannot break anything.
1315
- *
1316
- * One implementation because two callers must agree on what "has a default
1317
- * export" means: `hasDefaultExport` decides whether to warn that a page has
1318
- * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.
1319
- */
1320
- function defaultSpecifier(stmt) {
1321
- if (stmt.type !== "ExportNamedDeclaration" || !stmt.specifiers) return null;
1322
- if (stmt.exportKind === "type") return null;
1323
- for (const spec of stmt.specifiers) {
1324
- if (spec.exportKind === "type") continue;
1325
- if (spec.exported?.name === "default") return spec;
1326
- }
1327
- return null;
1328
- }
1329
- /**
1330
- * Check whether a program has a default export.
1331
- * Handles: `export default ...`, `export { X as default }`,
1332
- * `export { default } from '...'`. Type-only defaults do not count —
1333
- * see `defaultSpecifier`.
1334
- */
1335
- function hasDefaultExport(program) {
1336
- for (const stmt of program.body) {
1337
- if (stmt.type === "ExportDefaultDeclaration") return true;
1338
- if (defaultSpecifier(stmt)) return true;
1339
- }
1340
- return false;
1341
- }
1342
- /**
1343
- * Check whether a program has any bare `export * from '...'` declarations.
1344
- * Excludes `export * as X from '...'` (namespace re-exports) since those
1345
- * create a namespace object, not individual top-level exports.
1346
- */
1347
- function hasStarExport(program) {
1348
- return program.body.some((stmt) => stmt.type === "ExportAllDeclaration" && !stmt.exported && stmt.exportKind !== "type");
1349
- }
1350
- /**
1351
- * Check if a file has any of the given named exports.
1352
- * Returns the set of matching export names.
1353
- */
1354
- function fileHasAnyExport(filePath, exportNames) {
1355
- const matches = /* @__PURE__ */ new Set();
1356
- try {
1357
- const program = tryParse(readFileCached(filePath));
1358
- if (!program) return matches;
1359
- const exports = collectNamedExports(program);
1360
- for (const name of exportNames) if (exports.has(name)) matches.add(name);
1361
- } catch {}
1362
- return matches;
1363
- }
1364
- /**
1365
- * Check if a file has a default export.
1366
- * Returns false if the file doesn't exist or can't be parsed.
1367
- */
1368
- function fileHasDefaultExport(filePath) {
1369
- if (!existsSync(filePath)) return false;
1370
- try {
1371
- const program = tryParse(readFileCached(filePath));
1372
- if (!program) return false;
1373
- return hasDefaultExport(program);
1374
- } catch {
1375
- return false;
1376
- }
1377
- }
1378
- /** Node types whose value is unambiguously constructed by this module. */
1379
- var FUNCTION_LIKE = /* @__PURE__ */ new Set([
1380
- "FunctionDeclaration",
1381
- "FunctionExpression",
1382
- "ArrowFunctionExpression",
1383
- "ClassDeclaration",
1384
- "ClassExpression"
1385
- ]);
1386
- /**
1387
- * Expression wrappers that erase at runtime and so cannot change where a value
1388
- * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.
1389
- */
1390
- var TRANSPARENT_WRAPPERS = /* @__PURE__ */ new Set([
1391
- "TSAsExpression",
1392
- "TSSatisfiesExpression",
1393
- "TSTypeAssertion",
1394
- "TSNonNullExpression",
1395
- "TSInstantiationExpression",
1396
- "ParenthesizedExpression"
1397
- ]);
1398
- /**
1399
- * Strip runtime-transparent wrappers so the node underneath can be classified.
1400
- *
1401
- * Without this, `(() => <h1 />) satisfies React.FC` reads as a
1402
- * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a
1403
- * provably-local component is misread as one whose origin cannot be
1404
- * determined — turning a build error into a warning.
1405
- */
1406
- function unwrapTransparent(node) {
1407
- let current = node;
1408
- while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) current = current.expression;
1409
- return current;
1410
- }
1411
- /**
1412
- * Whether `name` is bound at module top level to a function or class written
1413
- * in this file. An imported binding can never match: imports are
1414
- * `ImportDeclaration` specifiers, not function/class/variable declarations,
1415
- * and a module-level name cannot be both.
1416
- */
1417
- function bindsLocalFunction(program, name) {
1418
- for (const stmt of program.body) {
1419
- const decl = stmt.type === "ExportNamedDeclaration" ? stmt.declaration : stmt;
1420
- if (!decl) continue;
1421
- if ((decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") && decl.id?.name === name) return true;
1422
- if (decl.type === "VariableDeclaration") {
1423
- for (const d of decl.declarations ?? []) if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) return true;
1424
- }
1425
- }
1426
- return false;
1427
- }
1428
- /**
1429
- * Whether the default export is *provably* a value constructed by this module:
1430
- * `export default function/class/() => {}`, or a name bound to a function or
1431
- * class declared here — whether it leaves via `export default Name` or
1432
- * `export { Name as default }`. Both spellings are the same fact about where
1433
- * the value was built, so both must answer the same way.
1434
- *
1435
- * This is the sound half of "is this a server component?". A file with no
1436
- * `'use client'` directive whose default export is built here is a server
1437
- * component, full stop. Everything else — `export { default } from
1438
- * './client-thing'`, `export default Imported`, `export default memo(X)`,
1439
- * an unparseable file — returns false, because the exported value may have
1440
- * been minted in a module that *does* carry the directive. Callers must not
1441
- * infer "server component" from a missing directive alone.
1442
- */
1443
- function fileDefaultExportIsLocalValue(filePath) {
1444
- if (!existsSync(filePath)) return false;
1445
- try {
1446
- const program = tryParse(readFileCached(filePath));
1447
- if (!program) return false;
1448
- for (const stmt of program.body) {
1449
- if (stmt.type === "ExportDefaultDeclaration") {
1450
- const decl = stmt.declaration && unwrapTransparent(stmt.declaration);
1451
- if (!decl) return false;
1452
- if (FUNCTION_LIKE.has(decl.type)) return true;
1453
- if (decl.type === "Identifier" && decl.name) return bindsLocalFunction(program, decl.name);
1454
- return false;
1455
- }
1456
- const spec = defaultSpecifier(stmt);
1457
- if (spec) {
1458
- if (stmt.source) return false;
1459
- return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;
1460
- }
1461
- }
1462
- return false;
1463
- } catch {
1464
- return false;
1465
- }
1466
- }
1467
- /**
1468
- * Check if a file has any `export * from '...'` declarations.
1469
- * Returns false if the file doesn't exist or can't be parsed.
1470
- */
1471
- function fileHasStarExport(filePath) {
1472
- if (!existsSync(filePath)) return false;
1473
- try {
1474
- const program = tryParse(readFileCached(filePath));
1475
- if (!program) return false;
1476
- return hasStarExport(program);
1477
- } catch {
1478
- return false;
1479
- }
1480
- }
1481
- function extractLiteralValue(node) {
1482
- if (!node) return void 0;
1483
- const n = node;
1484
- if (n.type === "Literal") return n.value;
1485
- if (n.type === "UnaryExpression" && n.operator === "-" && n.argument?.type === "Literal") return -n.argument.value;
1486
- if (n.type === "ArrayExpression") {
1487
- const elements = n.elements;
1488
- if (!elements) return void 0;
1489
- const result = [];
1490
- for (const el of elements) {
1491
- const v = extractLiteralValue(el);
1492
- if (v === void 0) return void 0;
1493
- result.push(v);
1494
- }
1495
- return result;
1496
- }
1497
- }
1498
- function extractObjectLiteral(node) {
1499
- if (node.type !== "ObjectExpression") return void 0;
1500
- const props = node.properties;
1501
- if (!props) return void 0;
1502
- const result = {};
1503
- for (const prop of props) {
1504
- const p = prop;
1505
- if (p.type === "SpreadElement") return void 0;
1506
- if (p.type !== "Property" || p.computed) return void 0;
1507
- const key = p.key?.type === "Identifier" ? p.key.name : p.key?.type === "Literal" ? String(p.key.value) : void 0;
1508
- if (!key) return void 0;
1509
- const value = extractLiteralValue(p.value);
1510
- if (value === void 0) return void 0;
1511
- result[key] = value;
1512
- }
1513
- return result;
1514
- }
1515
- /**
1516
- * Extract the value of `export const prerender` from a file.
1517
- * Returns undefined if the file doesn't export `prerender` or can't be parsed.
1518
- *
1519
- * Supports:
1520
- * export const prerender = true;
1521
- * export const prerender = false;
1522
- * export const prerender = { ttl: 3600, tags: ['docs'] };
1523
- */
1524
- function getPrerenderExport(filePath) {
1525
- if (!existsSync(filePath)) return void 0;
1526
- try {
1527
- const program = tryParse(readFileCached(filePath));
1528
- if (!program) return void 0;
1529
- for (const stmt of program.body) {
1530
- if (stmt.type !== "ExportNamedDeclaration") continue;
1531
- if (stmt.exportKind === "type") continue;
1532
- if (!stmt.declaration) continue;
1533
- const decl = stmt.declaration;
1534
- if (decl.type !== "VariableDeclaration") continue;
1535
- const declarations = decl.declarations;
1536
- if (!declarations) continue;
1537
- for (const d of declarations) {
1538
- if (d.id?.name !== "prerender" || !d.init) continue;
1539
- const init = d.init;
1540
- if (init.type === "Literal" && typeof init.value === "boolean") return init.value;
1541
- if (init.type === "ObjectExpression") {
1542
- const obj = extractObjectLiteral(init);
1543
- if (!obj) return void 0;
1544
- const result = {};
1545
- if ("ttl" in obj && typeof obj.ttl === "number") result.ttl = obj.ttl;
1546
- if ("tags" in obj && Array.isArray(obj.tags) && obj.tags.every((t) => typeof t === "string")) result.tags = obj.tags;
1547
- return result;
1548
- }
1549
- return;
1550
- }
1551
- }
1552
- return;
1553
- } catch {
1554
- return;
1555
- }
1556
- }
1557
- function getCsrfExport(filePath) {
1558
- if (!existsSync(filePath)) return "absent";
1559
- const program = tryParse(readFileCached(filePath));
1560
- if (!program) return "absent";
1561
- let found = "absent";
1562
- for (const stmt of program.body) {
1563
- if (stmt.type !== "ExportNamedDeclaration" || stmt.exportKind === "type") continue;
1564
- for (const spec of stmt.specifiers ?? []) if (spec.exportKind !== "type" && specifierName(spec.exported) === "csrf") return "invalid";
1565
- const decl = stmt.declaration;
1566
- if (!decl) continue;
1567
- if (decl.id?.name === "csrf") return "invalid";
1568
- if (decl.type !== "VariableDeclaration") continue;
1569
- for (const d of decl.declarations ?? []) {
1570
- const id = d.id;
1571
- if (id?.type === "Identifier") {
1572
- if (id.name !== "csrf") continue;
1573
- const init = d.init && unwrapTransparent(d.init);
1574
- const literalFalse = init?.type === "Literal" && init.value === false;
1575
- if (decl.kind !== "const" || !literalFalse) return "invalid";
1576
- found = "exempt";
1577
- } else if (id && patternBinds(id, "csrf")) return "invalid";
1578
- }
1579
- }
1580
- return found;
1581
- }
1582
- /** An export specifier's name: `csrf` or the string literal `"csrf"`. */
1583
- function specifierName(node) {
1584
- if (!node) return void 0;
1585
- return typeof node.value === "string" ? node.value : node.name;
1586
- }
1587
- /** Whether a destructuring pattern binds `name` anywhere inside it. */
1588
- function patternBinds(node, name) {
1589
- if (!node || typeof node !== "object") return false;
1590
- const n = node;
1591
- switch (n.type) {
1592
- case "Identifier": return n.name === name;
1593
- case "ObjectPattern": return (n.properties ?? []).some((prop) => {
1594
- const p = prop;
1595
- return patternBinds(p.type === "RestElement" ? p.argument : p.value, name);
1596
- });
1597
- case "ArrayPattern": return (n.elements ?? []).some((el) => patternBinds(el, name));
1598
- case "RestElement": return patternBinds(n.argument, name);
1599
- case "AssignmentPattern": return patternBinds(n.left, name);
1600
- default: return false;
1601
- }
1602
- }
1603
- /**
1604
- * Check if a file starts with a specific directive (e.g. "use client").
1605
- * Directives are string literal expression statements at the top of the file.
1606
- */
1607
- function fileHasDirective(filePath, directive) {
1608
- if (!existsSync(filePath)) return false;
1609
- try {
1610
- const program = tryParse(readFileCached(filePath));
1611
- if (!program) return false;
1612
- for (const stmt of program.body) {
1613
- if (stmt.type !== "ExpressionStatement") break;
1614
- const expr = stmt.expression;
1615
- if (expr?.type !== "Literal" || typeof expr.value !== "string") break;
1616
- if (expr.value === directive) return true;
1617
- }
1618
- return false;
1619
- } catch {
1620
- return false;
1621
- }
1622
- }
1623
- // src/routing/scanner.ts
1624
- /**
1625
- * Route discovery scanner.
1626
- *
1627
- * Pure function: (appDir, config) → RouteTree
1628
- *
1629
- * Scans the app/ directory and builds a segment tree recognizing all
1630
- * timber.js file conventions. Does NOT handle request matching — this
1631
- * is discovery only.
1632
- */
1633
- /**
1634
- * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)
1635
- * `error` is excluded — it only accepts script extensions (TIM-1505).
1636
- */
1637
- var PAGE_EXT_CONVENTIONS = /* @__PURE__ */ new Set([
1638
- "page",
1639
- "layout",
1640
- "default",
1641
- "denied"
1642
- ]);
1643
- /**
1644
- * File convention names that are always .ts/.tsx (never .mdx etc.)
1645
- */
1646
- var FIXED_CONVENTIONS = /* @__PURE__ */ new Set([
1647
- "middleware",
1648
- "access",
1649
- "route"
1650
- ]);
1651
- /**
1652
- * Status-code file patterns:
1653
- * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx
1654
- * - Category catch-alls: 4xx.tsx, 5xx.tsx
1655
- */
1656
- var STATUS_CODE_PATTERN = /^(\d{3}|[45]xx)$/;
1657
- /**
1658
- * Whether a basename + extension pair is a route-convention file the
1659
- * framework itself imports: page/layout/default/denied on pageExtensions,
1660
- * error/global-error and status-code files on script extensions only,
1661
- * middleware/access/route/proxy on .ts/.tsx/.js/.jsx only, and
1662
- * status-code .json files — mirroring this scanner's own recognition
1663
- * rules per family.
1664
- *
1665
- * Exported for the analyze classifier so its provisional classification
1666
- * (design/47 §2) derives from the scanner's real conventions instead of
1667
- * a duplicate list that can drift.
1668
- */
1669
- function isRouteConventionFile(base, ext, pageExtensions = DEFAULT_PAGE_EXTENSIONS) {
1670
- const isPageExt = pageExtensions.includes(ext);
1671
- const isScriptExt = /^[jt]sx?$/.test(ext);
1672
- if (PAGE_EXT_CONVENTIONS.has(base) && isPageExt) return true;
1673
- if ((base === "error" || base === "global-error") && isScriptExt) return true;
1674
- if ((FIXED_CONVENTIONS.has(base) || base === "proxy") && isScriptExt) return true;
1675
- if (STATUS_CODE_PATTERN.test(base) && (isScriptExt || ext === "json")) return true;
1676
- return false;
1677
- }
1678
- /**
1679
- * Scan the app/ directory and build the route tree.
1680
- *
1681
- * @param appDir - Absolute path to the app/ directory
1682
- * @param config - Scanner configuration
1683
- * @returns The complete route tree
1684
- */
1685
- function scanRoutes(appDir, config = {}) {
1686
- const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;
1687
- const extSet = new Set(pageExtensions);
1688
- const tree = { root: createSegmentNode("", "static", "/") };
1689
- const proxyFile = findFixedFile(appDir, "proxy");
1690
- if (proxyFile) tree.proxy = proxyFile;
1691
- const globalErrorFile = findScriptExtFile(appDir, "global-error");
1692
- if (globalErrorFile) tree.globalError = globalErrorFile;
1693
- scanSegmentFiles(appDir, tree.root, extSet);
1694
- scanChildren(appDir, tree.root, extSet);
1695
- validateSlotPlacement(tree.root);
1696
- validateRouteGroupCollisions(tree.root);
1697
- validateDuplicateParamNames(tree.root);
1698
- validateUniqueBracketForms(tree.root);
1699
- validateAffixedSiblingConflicts(tree.root);
1700
- validateInterceptionPlacement(tree.root);
1701
- return tree;
1702
- }
1703
- /**
1704
- * Create an empty segment node.
1705
- */
1706
- function createSegmentNode(segmentName, segmentType, urlPath, paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix) {
1707
- return {
1708
- segmentName,
1709
- segmentType,
1710
- urlPath,
1711
- paramName,
1712
- paramPrefix,
1713
- paramSuffix,
1714
- interceptionMarker,
1715
- interceptedSegmentName,
1716
- children: [],
1717
- slots: {}
1718
- };
1719
- }
1720
- /**
1721
- * Compute the URL path for a child segment given its parent's URL path.
1722
- * Route groups, slots, and intercepting routes do NOT add URL depth.
1723
- */
1724
- function computeUrlPath(parentUrlPath, dirName, segmentType) {
1725
- if (segmentType === "group" || segmentType === "slot" || segmentType === "intercepting") return parentUrlPath;
1726
- return `${parentUrlPath === "/" ? "" : parentUrlPath}/${dirName}`;
1727
- }
1728
- /**
1729
- * Scan a directory for file conventions and populate the segment node.
1730
- */
1731
- function scanSegmentFiles(dirPath, node, extSet) {
1732
- let entries;
1733
- try {
1734
- entries = readdirSync(dirPath);
1735
- } catch (err) {
1736
- swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: "warn" });
1737
- return;
1738
- }
1739
- for (const entry of entries) {
1740
- const fullPath = join(dirPath, entry);
1741
- try {
1742
- if (statSync(fullPath).isDirectory()) continue;
1743
- } catch {
1744
- continue;
1745
- }
1746
- const ext = extname(entry).slice(1);
1747
- const name = basename(entry, `.${ext}`);
1748
- if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {
1749
- const key = name;
1750
- const existing = node[key];
1751
- if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1752
- node[key] = {
1753
- filePath: fullPath,
1754
- extension: ext
1755
- };
1756
- continue;
1757
- }
1758
- if (name === "error" && /^[jt]sx?$/.test(ext)) {
1759
- const existing = node.error;
1760
- if (existing) throwDuplicateConvention("error", existing.filePath, fullPath);
1761
- node.error = {
1762
- filePath: fullPath,
1763
- extension: ext
1764
- };
1765
- continue;
1766
- }
1767
- if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {
1768
- const key = name;
1769
- const existing = node[key];
1770
- if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1771
- node[key] = {
1772
- filePath: fullPath,
1773
- extension: ext
1774
- };
1775
- continue;
1776
- }
1777
- if (STATUS_CODE_PATTERN.test(name) && ext === "json") {
1778
- if (!node.jsonStatusFiles) node.jsonStatusFiles = {};
1779
- node.jsonStatusFiles[name] = {
1780
- filePath: fullPath,
1781
- extension: ext
1782
- };
1783
- continue;
1784
- }
1785
- if (STATUS_CODE_PATTERN.test(name) && /^[jt]sx?$/.test(ext)) {
1786
- if (!node.statusFiles) node.statusFiles = {};
1787
- const existing = node.statusFiles[name];
1788
- if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1789
- node.statusFiles[name] = {
1790
- filePath: fullPath,
1791
- extension: ext
1792
- };
1793
- continue;
1794
- }
1795
- const metaInfo = classifyMetadataRoute(entry);
1796
- if (metaInfo) {
1797
- if (!metaInfo.nestable && node.segmentName !== "") throw new Error(`Build error: '${name}' is a root-only metadata convention and must be in the app root directory.\n File: ${fullPath}\n Move this file to the app root (not a route group or nested segment).`);
1798
- if (!node.metadataRoutes) node.metadataRoutes = {};
1799
- const existing = node.metadataRoutes[name];
1800
- if (existing) {
1801
- const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);
1802
- const newIsDynamic = isDynamicMetadataExtension(name, ext);
1803
- if (existingIsDynamic === newIsDynamic) throwDuplicateConvention(name, existing.filePath, fullPath);
1804
- if (newIsDynamic) node.metadataRoutes[name] = {
1805
- filePath: fullPath,
1806
- extension: ext
1807
- };
1808
- } else node.metadataRoutes[name] = {
1809
- filePath: fullPath,
1810
- extension: ext
1811
- };
1812
- }
1813
- }
1814
- if (node.route && node.page) throw new Error(`Build error: route.ts and page.* cannot coexist in the same segment.\n route.ts: ${node.route.filePath}\n page: ${node.page.filePath}\nA URL is either an API endpoint or a rendered page, not both.`);
1815
- if (node.route && getCsrfExport(node.route.filePath) === "exempt") node.csrfExempt = true;
1816
- }
1817
- /**
1818
- * Throw a build error for two files claiming the same convention slot in
1819
- * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first
1820
- * is platform-dependent (APFS sorts entries, ext4 does not) — silently
1821
- * picking one would let macOS dev and Linux CI serve different
1822
- * implementations of the same route.
1823
- */
1824
- function throwDuplicateConvention(convention, firstPath, secondPath) {
1825
- throw new Error(`Build error: duplicate '${convention}' files in the same route segment.\n File 1: ${firstPath}\n File 2: ${secondPath}\nEach segment may define '${convention}' at most once. Remove one of the files.`);
1826
- }
1827
- /**
1828
- * Recursively scan child directories and build the segment tree.
1829
- */
1830
- function scanChildren(dirPath, parentNode, extSet) {
1831
- let entries;
1832
- try {
1833
- entries = readdirSync(dirPath);
1834
- } catch (err) {
1835
- swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: "warn" });
1836
- return;
1837
- }
1838
- for (const entry of entries) {
1839
- const fullPath = join(dirPath, entry);
1840
- try {
1841
- if (!statSync(fullPath).isDirectory()) continue;
1842
- } catch {
1843
- continue;
1844
- }
1845
- if (ENCODED_SEPARATOR_RE.test(entry)) throw new Error(`Build error: directory name contains an encoded path delimiter (%2F or %5C).\n Directory: ${fullPath}\nEncoded separators in directory names cause route collisions when decoded. Rename the directory to remove the encoded delimiter.`);
1846
- if (NULL_BYTE_RE.test(entry)) throw new Error(`Build error: directory name contains an encoded null byte (%00).\n Directory: ${fullPath}\nEncoded null bytes in directory names are not allowed. Rename the directory to remove the null byte encoding.`);
1847
- const { type, paramName, paramPrefix, paramSuffix, interceptionMarker, interceptedSegmentName } = classifySegment(entry);
1848
- if (type === "private") continue;
1849
- const childNode = createSegmentNode(entry, type, computeUrlPath(parentNode.urlPath, entry, type), paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix);
1850
- scanSegmentFiles(fullPath, childNode, extSet);
1851
- scanChildren(fullPath, childNode, extSet);
1852
- if (type === "slot") {
1853
- const slotName = entry.slice(1);
1854
- parentNode.slots[slotName] = childNode;
1855
- } else parentNode.children.push(childNode);
1856
- }
1857
- }
1858
- /**
1859
- * Validate that no route chain contains duplicate dynamic param names.
1860
- *
1861
- * Example violation:
1862
- * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.
1863
- *
1864
- * Route groups are transparent — params accumulate through them.
1865
- * Slots are independent — duplicate detection does NOT cross slot boundaries.
1866
- *
1867
- * See design/07-routing.md §"Duplicate Param Name Detection"
1868
- */
1869
- function validateDuplicateParamNames(root) {
1870
- walkForDuplicateParams(root, /* @__PURE__ */ new Map());
1871
- }
1872
- /**
1873
- * Recursively walk the segment tree, tracking seen param names → segment paths.
1874
- * Throws on the first duplicate found.
1875
- */
1876
- function walkForDuplicateParams(node, seen) {
1877
- const { paramName } = effectiveUrlSegment(node);
1878
- if (paramName) {
1879
- const existing = seen.get(paramName);
1880
- if (existing) throw new Error(`[timber] Duplicate param name '${paramName}' in route chain.\n First defined at: ${existing}\n Duplicate at: ${node.urlPath || "/"}\n Rename one of the segments to avoid ambiguity.`);
1881
- seen = new Map(seen);
1882
- seen.set(paramName, node.urlPath || "/");
1883
- }
1884
- for (const child of node.children) walkForDuplicateParams(child, seen);
1885
- for (const slotNode of Object.values(node.slots)) walkForDuplicateParams(slotNode, new Map(seen));
1886
- }
1887
- /**
1888
- * Validate that each param name uses a single bracket form across the entire route tree.
1889
- *
1890
- * Different bracket forms produce different types:
1891
- * [id] → string
1892
- * [...id] → string[]
1893
- * [[...id]] → string[] | undefined
1894
- *
1895
- * If the same param name appears with multiple forms, the no-argument
1896
- * getSegmentParams() / useSegmentParams() return type becomes ambiguous.
1897
- *
1898
- * Same name + same form across different routes is fine and expected.
1899
- */
1900
- function validateUniqueBracketForms(root) {
1901
- collectBracketForms(root, /* @__PURE__ */ new Map());
1902
- }
1903
- function collectBracketForms(node, forms) {
1904
- const { paramName, segmentType } = effectiveUrlSegment(node);
1905
- if (paramName && segmentType !== "static" && segmentType !== "group") {
1906
- const existing = forms.get(paramName);
1907
- if (existing && existing.segmentType !== segmentType) {
1908
- const bracketExamples = {
1909
- "dynamic": `[${paramName}]`,
1910
- "catch-all": `[...${paramName}]`,
1911
- "optional-catch-all": `[[...${paramName}]]`
1912
- };
1913
- throw new Error(`[timber] Param name '${paramName}' uses multiple bracket forms.\n ${bracketExamples[existing.segmentType] ?? existing.segmentType} at: ${existing.urlPath}\n ${bracketExamples[segmentType] ?? segmentType} at: ${node.urlPath || "/"}\n Each param name must use a single bracket form across all routes.\n Rename one of the segments to fix this (e.g., [${paramName}] → [${paramName}Id]).`);
1914
- }
1915
- if (!existing) forms.set(paramName, {
1916
- segmentType,
1917
- urlPath: node.urlPath || "/"
1918
- });
1919
- }
1920
- for (const child of node.children) collectBracketForms(child, forms);
1921
- for (const slotNode of Object.values(node.slots)) collectBracketForms(slotNode, forms);
1922
- }
1923
- /**
1924
- * Validate that no sibling affixed dynamic segments have equal specificity.
1925
- *
1926
- * Among affixed siblings, longer combined prefix+suffix length wins. When two
1927
- * siblings tie (same total affix length), the router would fall back to
1928
- * filesystem scan order — which is platform-dependent. This is a build error.
1929
- *
1930
- * Route groups are URL-transparent, so affixed segments inside different groups
1931
- * at the same level still conflict with each other.
1932
- *
1933
- * Ambiguity requires the two segments to be candidates for the *same* URL
1934
- * part, which is narrower than "same parent" once interception is involved:
1935
- *
1936
- * - Plain children and intercepting children never compete. They are resolved
1937
- * by different walks — `findSlotMatch` matches the slot subtree (where
1938
- * `tree-match.ts` ignores intercepting nodes outright) and
1939
- * `findInterceptingMatch` builds a synthetic parent holding only
1940
- * interceptors.
1941
- * - Two interceptors compete only at the same anchor. `(.)a-[id]` and
1942
- * `(..)[slug]-b` in one slot are based at different URL depths, so no
1943
- * pathname reaches both, and `anchorIndex` rejects the one whose base does
1944
- * not match the target. Grouping them together would fail the build for a
1945
- * pair that can never be ambiguous.
1946
- *
1947
- * So candidates are keyed by the position they contend for, then by affix
1948
- * length. See design/07-routing.md §"Priority" and §"Intercepting Routes".
1949
- */
1950
- function validateAffixedSiblingConflicts(node) {
1951
- const affixed = collectEffectiveAffixed(node);
1952
- if (affixed.length >= 2) {
1953
- const byLength = /* @__PURE__ */ new Map();
1954
- for (const child of affixed) {
1955
- const key = `${contentionKey(node, child)}\0${affixLengthOf(child)}`;
1956
- const group = byLength.get(key);
1957
- if (group) group.push(child);
1958
- else byLength.set(key, [child]);
1959
- }
1960
- for (const [, group] of byLength) if (group.length >= 2) throw new Error(`Build error: ambiguous affixed dynamic siblings with equal specificity.\n Parent: ${node.urlPath || "/"}\n Segments: ${group.map((s) => s.segmentName).join(", ")}\n Combined prefix+suffix length: ${affixLengthOf(group[0])}\nThe router cannot deterministically choose between these — filesystem scan order is platform-dependent.\nRename one segment to give it a longer or shorter combined affix.`);
1961
- }
1962
- for (const child of node.children) validateAffixedSiblingConflicts(child);
1963
- for (const slotNode of Object.values(node.slots)) validateAffixedSiblingConflicts(slotNode);
1964
- }
1965
- /**
1966
- * The URL position a child contends for, as a comparable key.
1967
- *
1968
- * Plain children contend for the parent's next part. An intercepting child
1969
- * contends for a part determined by its marker's intercepted base, so two
1970
- * markers of different depth are simply different positions — and two markers
1971
- * that compute the *same* base do contend, which is why the key is the base
1972
- * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).
1973
- *
1974
- * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical
1975
- * statement of that grouping — it is what the resolver walks and what the
1976
- * collision validator checks. This computes the same key from the same
1977
- * `computeInterceptedBase` rather than calling it, because affix ambiguity is
1978
- * decided per *child* and `collectEffectiveAffixed` looks through route groups,
1979
- * so the two do not partition the same set of nodes.
1980
- */
1981
- function contentionKey(parent, child) {
1982
- if (child.segmentType !== "intercepting") return "child";
1983
- return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? "(.)")}`;
1984
- }
1985
- /** Combined affix length of a node, read through its effective identity. */
1986
- function affixLengthOf(node) {
1987
- const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);
1988
- return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);
1989
- }
1990
- /**
1991
- * Collect affixed dynamic segments that are effective children of a node.
1992
- * Route groups are URL-transparent, so we look through them recursively.
1993
- *
1994
- * Segments are read through `effectiveUrlSegment`, so an intercepting
1995
- * directory counts as the affixed segment it intercepts: `(.)a-[id]` is
1996
- * `a-[id]`. The proxy the slot resolver builds hands those affixes to
1997
- * `matchUrlParts`, whose equal-length sort is not stable across equal
1998
- * specificity — so two intercepting siblings with the same combined affix
1999
- * length would resolve by filesystem enumeration order, which is precisely
2000
- * what this validator exists to prevent for ordinary siblings (TIM-1288).
2001
- */
2002
- function collectEffectiveAffixed(node) {
2003
- const result = [];
2004
- for (const child of node.children) {
2005
- const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);
2006
- if (segmentType === "dynamic" && (paramPrefix || paramSuffix)) result.push(child);
2007
- else if (segmentType === "group") result.push(...collectEffectiveAffixed(child));
2008
- }
2009
- return result;
2010
- }
2011
- /**
2012
- * Find a fixed-extension file (proxy.ts) in a directory.
2013
- */
2014
- function findFixedFile(dirPath, name) {
2015
- for (const ext of ["ts", "tsx"]) {
2016
- const fullPath = join(dirPath, `${name}.${ext}`);
2017
- try {
2018
- if (statSync(fullPath).isFile()) return {
2019
- filePath: fullPath,
2020
- extension: ext
2021
- };
2022
- } catch {}
2023
- }
2024
- }
2025
- /**
2026
- * Find a file with script extensions (tsx, ts, jsx, js) in a directory.
2027
- * Used for app-root conventions like global-error that only accept script
2028
- * extensions (TIM-1505).
2029
- */
2030
- function findScriptExtFile(dirPath, name) {
2031
- for (const ext of [
2032
- "tsx",
2033
- "ts",
2034
- "jsx",
2035
- "js"
2036
- ]) {
2037
- const fullPath = join(dirPath, `${name}.${ext}`);
2038
- try {
2039
- if (statSync(fullPath).isFile()) return {
2040
- filePath: fullPath,
2041
- extension: ext
2042
- };
2043
- } catch {}
2044
- }
2045
- }
2046
- export { fileHasDefaultExport as a, getCsrfExport as c, collectInterceptionRewrites as d, fileHasAnyExport as i, getPrerenderExport as l, scanRoutes as n, fileHasDirective as o, fileDefaultExportIsLocalValue as r, fileHasStarExport as s, isRouteConventionFile as t, readFileCached as u };
1172
+ export { findOrderDependentCollision as a, validateInterceptionPlacement as i, computeInterceptedBase as n, matchUrlParts as o, computeInterceptedUrlBase as r, collectInterceptionRewrites as t };
2047
1173
 
2048
- //# sourceMappingURL=scanner-CrB_h6FA.js.map
1174
+ //# sourceMappingURL=interception-CtNt9jPt.js.map