@timber-js/app 0.2.0-alpha.184 → 0.2.0-alpha.186

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 (441) hide show
  1. package/dist/_chunks/{actions-O_LsyCE4.js → actions-C-Rw9vPc.js} +3 -3
  2. package/dist/_chunks/{actions-O_LsyCE4.js.map → actions-C-Rw9vPc.js.map} +1 -1
  3. package/dist/_chunks/als-slots-mFweg276.js +27 -0
  4. package/dist/_chunks/als-slots-mFweg276.js.map +1 -0
  5. package/dist/_chunks/base-path-DaQrzbez.js +80 -0
  6. package/dist/_chunks/base-path-DaQrzbez.js.map +1 -0
  7. package/dist/_chunks/build-manifest-DWppEdLB.js +86 -0
  8. package/dist/_chunks/build-manifest-DWppEdLB.js.map +1 -0
  9. package/dist/_chunks/build-output-helper-C3DrfzZR.js +369 -0
  10. package/dist/_chunks/build-output-helper-C3DrfzZR.js.map +1 -0
  11. package/dist/_chunks/{cache-api-B-lhk9p4.js → cache-api-Cd0VZ_Pd.js} +3 -3
  12. package/dist/_chunks/{cache-api-B-lhk9p4.js.map → cache-api-Cd0VZ_Pd.js.map} +1 -1
  13. package/dist/_chunks/cli-schema-sync-CKgHC2MB.js +1857 -0
  14. package/dist/_chunks/cli-schema-sync-CKgHC2MB.js.map +1 -0
  15. package/dist/_chunks/{cloudflare-CnT5Lr7U.js → cloudflare-Cs0uZXea.js} +89 -12
  16. package/dist/_chunks/{cloudflare-CnT5Lr7U.js.map → cloudflare-Cs0uZXea.js.map} +1 -1
  17. package/dist/_chunks/error-boundary-DpYRI_I1.js +330 -0
  18. package/dist/_chunks/error-boundary-DpYRI_I1.js.map +1 -0
  19. package/dist/_chunks/{fast-hash-D6hIVt1Y.js → fast-hash-C-tVYrLb.js} +6 -1
  20. package/dist/_chunks/fast-hash-C-tVYrLb.js.map +1 -0
  21. package/dist/_chunks/fs-identity-D7vb6GdI.js +208 -0
  22. package/dist/_chunks/fs-identity-D7vb6GdI.js.map +1 -0
  23. package/dist/_chunks/{logger-AWfuX-KJ.js → logger-N7e5auP0.js} +9 -13
  24. package/dist/_chunks/logger-N7e5auP0.js.map +1 -0
  25. package/dist/_chunks/navigation-root-B29qg0_T.js +274 -0
  26. package/dist/_chunks/navigation-root-B29qg0_T.js.map +1 -0
  27. package/dist/_chunks/param-value-C8TNYchQ.js +66 -0
  28. package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
  29. package/dist/_chunks/{plugin-context---kTF5v8.js → plugin-context-DEGLSJs3.js} +2 -1
  30. package/dist/_chunks/plugin-context-DEGLSJs3.js.map +1 -0
  31. package/dist/_chunks/{router-ref-CtmF-aPv.js → router-ref-DuYuV_0Q.js} +2 -2
  32. package/dist/_chunks/router-ref-DuYuV_0Q.js.map +1 -0
  33. package/dist/_chunks/rsc-cache-key-DD0fl_-s.js +243 -0
  34. package/dist/_chunks/rsc-cache-key-DD0fl_-s.js.map +1 -0
  35. package/dist/_chunks/rsc-error-envelope-tT5PJs4q.js +40 -0
  36. package/dist/_chunks/rsc-error-envelope-tT5PJs4q.js.map +1 -0
  37. package/dist/_chunks/rsc-payload-path-B_LBodc2.js +48 -0
  38. package/dist/_chunks/rsc-payload-path-B_LBodc2.js.map +1 -0
  39. package/dist/_chunks/{segment-classify-Byy425ng.js → segment-classify-C539Pa2O.js} +23 -2
  40. package/dist/_chunks/segment-classify-C539Pa2O.js.map +1 -0
  41. package/dist/_chunks/{canonicalize-DQHyFClh.js → segment-keys-BawYuNFO.js} +61 -2
  42. package/dist/_chunks/segment-keys-BawYuNFO.js.map +1 -0
  43. package/dist/_chunks/slot-params-BCTmZkQB.js +76 -0
  44. package/dist/_chunks/slot-params-BCTmZkQB.js.map +1 -0
  45. package/dist/_chunks/{ssr-data-BOWsq18U.js → ssr-data-14MXm7Pj.js} +17 -2
  46. package/dist/_chunks/ssr-data-14MXm7Pj.js.map +1 -0
  47. package/dist/_chunks/use-segment-params-ClyUNq4d.js +128 -0
  48. package/dist/_chunks/use-segment-params-ClyUNq4d.js.map +1 -0
  49. package/dist/_chunks/{walkers-BtTlKviE.js → walkers-BhhwI9TD.js} +21 -87
  50. package/dist/_chunks/walkers-BhhwI9TD.js.map +1 -0
  51. package/dist/adapters/build-output-helper.d.ts +37 -0
  52. package/dist/adapters/build-output-helper.d.ts.map +1 -1
  53. package/dist/adapters/cloudflare-dev.js +1 -1
  54. package/dist/adapters/cloudflare-kv-cache.js +1 -1
  55. package/dist/adapters/cloudflare.d.ts.map +1 -1
  56. package/dist/adapters/cloudflare.js +1 -1
  57. package/dist/adapters/fs-identity.d.ts +64 -0
  58. package/dist/adapters/fs-identity.d.ts.map +1 -0
  59. package/dist/adapters/nitro.d.ts.map +1 -1
  60. package/dist/adapters/nitro.js +2 -3
  61. package/dist/adapters/nitro.js.map +1 -1
  62. package/dist/adapters/shared.d.ts +57 -1
  63. package/dist/adapters/shared.d.ts.map +1 -1
  64. package/dist/adapters/types.d.ts +13 -1
  65. package/dist/adapters/types.d.ts.map +1 -1
  66. package/dist/cache/fast-hash.d.ts +5 -0
  67. package/dist/cache/fast-hash.d.ts.map +1 -1
  68. package/dist/cache/index.js +1 -1
  69. package/dist/cli.js +2 -2
  70. package/dist/client/browser-entry/action-dispatch.d.ts.map +1 -1
  71. package/dist/client/browser-entry/hydrate.d.ts +20 -9
  72. package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
  73. package/dist/client/browser-entry/post-hydration.d.ts +4 -1
  74. package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
  75. package/dist/client/browser-entry/router-init.d.ts +3 -0
  76. package/dist/client/browser-entry/router-init.d.ts.map +1 -1
  77. package/dist/client/browser-entry/rsc-stream.d.ts +8 -0
  78. package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -1
  79. package/dist/client/error-boundary.d.ts +1 -0
  80. package/dist/client/error-boundary.d.ts.map +1 -1
  81. package/dist/client/error-boundary.js +1 -162
  82. package/dist/client/history.d.ts +13 -6
  83. package/dist/client/history.d.ts.map +1 -1
  84. package/dist/client/index.js +18 -11
  85. package/dist/client/index.js.map +1 -1
  86. package/dist/client/internal.d.ts +4 -3
  87. package/dist/client/internal.d.ts.map +1 -1
  88. package/dist/client/internal.js +872 -305
  89. package/dist/client/internal.js.map +1 -1
  90. package/dist/client/link.d.ts.map +1 -1
  91. package/dist/client/navigation-api.d.ts +2 -2
  92. package/dist/client/navigation-commit.d.ts +71 -0
  93. package/dist/client/navigation-commit.d.ts.map +1 -0
  94. package/dist/client/navigation-context.d.ts +37 -20
  95. package/dist/client/navigation-context.d.ts.map +1 -1
  96. package/dist/client/navigation-root.d.ts +63 -23
  97. package/dist/client/navigation-root.d.ts.map +1 -1
  98. package/dist/client/params-context.d.ts +81 -0
  99. package/dist/client/params-context.d.ts.map +1 -0
  100. package/dist/client/router-effects.d.ts +129 -0
  101. package/dist/client/router-effects.d.ts.map +1 -0
  102. package/dist/client/router-lifecycle.d.ts +55 -0
  103. package/dist/client/router-lifecycle.d.ts.map +1 -0
  104. package/dist/client/router-pipeline.d.ts +84 -0
  105. package/dist/client/router-pipeline.d.ts.map +1 -0
  106. package/dist/client/router-ref.d.ts +1 -1
  107. package/dist/client/router-ref.d.ts.map +1 -1
  108. package/dist/client/router-skew.d.ts +21 -0
  109. package/dist/client/router-skew.d.ts.map +1 -0
  110. package/dist/client/router-types.d.ts +207 -0
  111. package/dist/client/router-types.d.ts.map +1 -0
  112. package/dist/client/router.d.ts +1 -182
  113. package/dist/client/router.d.ts.map +1 -1
  114. package/dist/client/rsc-fetch.d.ts +39 -16
  115. package/dist/client/rsc-fetch.d.ts.map +1 -1
  116. package/dist/client/segment-cache.d.ts +79 -34
  117. package/dist/client/segment-cache.d.ts.map +1 -1
  118. package/dist/client/ssr-data.d.ts +6 -0
  119. package/dist/client/ssr-data.d.ts.map +1 -1
  120. package/dist/client/stale-client.d.ts +69 -0
  121. package/dist/client/stale-client.d.ts.map +1 -0
  122. package/dist/client/state.d.ts +10 -1
  123. package/dist/client/state.d.ts.map +1 -1
  124. package/dist/client/top-loader.d.ts +2 -1
  125. package/dist/client/top-loader.d.ts.map +1 -1
  126. package/dist/client/unload-guard.d.ts +5 -0
  127. package/dist/client/unload-guard.d.ts.map +1 -1
  128. package/dist/client/use-cookie.d.ts.map +1 -1
  129. package/dist/client/use-router.d.ts +1 -1
  130. package/dist/client/use-segment-params.d.ts +18 -8
  131. package/dist/client/use-segment-params.d.ts.map +1 -1
  132. package/dist/cookies/index.js +3 -3
  133. package/dist/cookies/index.js.map +1 -1
  134. package/dist/index.d.ts.map +1 -1
  135. package/dist/index.js +915 -320
  136. package/dist/index.js.map +1 -1
  137. package/dist/plugin-context.d.ts +33 -1
  138. package/dist/plugin-context.d.ts.map +1 -1
  139. package/dist/plugins/adapter-build.d.ts.map +1 -1
  140. package/dist/plugins/build-manifest.d.ts +1 -1
  141. package/dist/plugins/build-manifest.d.ts.map +1 -1
  142. package/dist/plugins/entries.d.ts.map +1 -1
  143. package/dist/plugins/fonts.d.ts.map +1 -1
  144. package/dist/plugins/request-dep/analysis.d.ts +106 -0
  145. package/dist/plugins/request-dep/analysis.d.ts.map +1 -0
  146. package/dist/plugins/request-dep/index.d.ts +75 -0
  147. package/dist/plugins/request-dep/index.d.ts.map +1 -0
  148. package/dist/plugins/request-dep/origin.d.ts +61 -0
  149. package/dist/plugins/request-dep/origin.d.ts.map +1 -0
  150. package/dist/plugins/routing.d.ts +9 -0
  151. package/dist/plugins/routing.d.ts.map +1 -1
  152. package/dist/plugins/static-build.d.ts +149 -8
  153. package/dist/plugins/static-build.d.ts.map +1 -1
  154. package/dist/routing/codegen-types.d.ts +18 -0
  155. package/dist/routing/codegen-types.d.ts.map +1 -1
  156. package/dist/routing/codegen.d.ts.map +1 -1
  157. package/dist/routing/collision-probe.d.ts +104 -0
  158. package/dist/routing/collision-probe.d.ts.map +1 -0
  159. package/dist/routing/collision-spaces.d.ts +26 -0
  160. package/dist/routing/collision-spaces.d.ts.map +1 -0
  161. package/dist/routing/index.js +3 -3
  162. package/dist/routing/interception.d.ts +235 -6
  163. package/dist/routing/interception.d.ts.map +1 -1
  164. package/dist/routing/manifest-codegen.d.ts.map +1 -1
  165. package/dist/routing/scanner.d.ts.map +1 -1
  166. package/dist/routing/segment-classify.d.ts +33 -0
  167. package/dist/routing/segment-classify.d.ts.map +1 -1
  168. package/dist/routing/segment-keys.d.ts +95 -0
  169. package/dist/routing/segment-keys.d.ts.map +1 -0
  170. package/dist/routing/slot-placement.d.ts +48 -0
  171. package/dist/routing/slot-placement.d.ts.map +1 -0
  172. package/dist/routing/types.d.ts +1 -3
  173. package/dist/routing/types.d.ts.map +1 -1
  174. package/dist/routing/walkers.d.ts +6 -0
  175. package/dist/routing/walkers.d.ts.map +1 -1
  176. package/dist/search-params/define.d.ts +0 -6
  177. package/dist/search-params/define.d.ts.map +1 -1
  178. package/dist/search-params/index.js +176 -2
  179. package/dist/search-params/index.js.map +1 -1
  180. package/dist/segment-params/define.d.ts +0 -6
  181. package/dist/segment-params/define.d.ts.map +1 -1
  182. package/dist/segment-params/index.js +69 -1
  183. package/dist/segment-params/index.js.map +1 -0
  184. package/dist/server/actions.d.ts +6 -3
  185. package/dist/server/actions.d.ts.map +1 -1
  186. package/dist/server/als-registry.d.ts +2 -1
  187. package/dist/server/als-registry.d.ts.map +1 -1
  188. package/dist/server/build-manifest.d.ts +13 -1
  189. package/dist/server/build-manifest.d.ts.map +1 -1
  190. package/dist/server/chain-url-parts.d.ts +82 -0
  191. package/dist/server/chain-url-parts.d.ts.map +1 -0
  192. package/dist/server/children-interception.d.ts +49 -0
  193. package/dist/server/children-interception.d.ts.map +1 -0
  194. package/dist/server/default-status-page.d.ts +45 -0
  195. package/dist/server/default-status-page.d.ts.map +1 -0
  196. package/dist/server/deny-boundary.d.ts +4 -7
  197. package/dist/server/deny-boundary.d.ts.map +1 -1
  198. package/dist/server/deny-renderer.d.ts +14 -3
  199. package/dist/server/deny-renderer.d.ts.map +1 -1
  200. package/dist/server/head-response.d.ts +35 -0
  201. package/dist/server/head-response.d.ts.map +1 -0
  202. package/dist/server/index.js +2 -2
  203. package/dist/server/internal.js +528 -373
  204. package/dist/server/internal.js.map +1 -1
  205. package/dist/server/param-coercion.d.ts +10 -1
  206. package/dist/server/param-coercion.d.ts.map +1 -1
  207. package/dist/server/pipeline-helpers.d.ts +0 -18
  208. package/dist/server/pipeline-helpers.d.ts.map +1 -1
  209. package/dist/server/pipeline-interception.d.ts +59 -9
  210. package/dist/server/pipeline-interception.d.ts.map +1 -1
  211. package/dist/server/pipeline-outcome.d.ts.map +1 -1
  212. package/dist/server/pipeline-phases.d.ts.map +1 -1
  213. package/dist/server/pipeline.d.ts +11 -0
  214. package/dist/server/pipeline.d.ts.map +1 -1
  215. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  216. package/dist/server/primitives.d.ts +0 -12
  217. package/dist/server/primitives.d.ts.map +1 -1
  218. package/dist/server/publish-params.d.ts +33 -0
  219. package/dist/server/publish-params.d.ts.map +1 -0
  220. package/dist/server/request-context.d.ts +48 -0
  221. package/dist/server/request-context.d.ts.map +1 -1
  222. package/dist/server/route-element-builder.d.ts +32 -2
  223. package/dist/server/route-element-builder.d.ts.map +1 -1
  224. package/dist/server/route-handler.d.ts.map +1 -1
  225. package/dist/server/route-matcher.d.ts +13 -0
  226. package/dist/server/route-matcher.d.ts.map +1 -1
  227. package/dist/server/rsc-cache-key-guard.d.ts +78 -0
  228. package/dist/server/rsc-cache-key-guard.d.ts.map +1 -0
  229. package/dist/server/rsc-entry/api-handler.d.ts.map +1 -1
  230. package/dist/server/rsc-entry/error-renderer.d.ts +14 -2
  231. package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
  232. package/dist/server/rsc-entry/helpers.d.ts +2 -10
  233. package/dist/server/rsc-entry/helpers.d.ts.map +1 -1
  234. package/dist/server/rsc-entry/index.d.ts.map +1 -1
  235. package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
  236. package/dist/server/rsc-entry/rsc-payload.d.ts +3 -2
  237. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  238. package/dist/server/rsc-entry/rsc-stream.d.ts +3 -2
  239. package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
  240. package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -0
  241. package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
  242. package/dist/server/sitemap-generator.d.ts.map +1 -1
  243. package/dist/server/skippable-prefix.d.ts +23 -0
  244. package/dist/server/skippable-prefix.d.ts.map +1 -0
  245. package/dist/server/slot-interception.d.ts +80 -0
  246. package/dist/server/slot-interception.d.ts.map +1 -0
  247. package/dist/server/slot-resolver.d.ts +70 -8
  248. package/dist/server/slot-resolver.d.ts.map +1 -1
  249. package/dist/server/ssr-bridge-types.d.ts +6 -0
  250. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  251. package/dist/server/ssr-entry.d.ts.map +1 -1
  252. package/dist/server/ssr-wrappers.d.ts +24 -13
  253. package/dist/server/ssr-wrappers.d.ts.map +1 -1
  254. package/dist/server/state-tree-diff.d.ts +6 -27
  255. package/dist/server/state-tree-diff.d.ts.map +1 -1
  256. package/dist/server/static-generator.d.ts +6 -0
  257. package/dist/server/static-generator.d.ts.map +1 -1
  258. package/dist/server/static-not-found.d.ts +52 -0
  259. package/dist/server/static-not-found.d.ts.map +1 -0
  260. package/dist/server/status-code-resolver.d.ts +3 -10
  261. package/dist/server/status-code-resolver.d.ts.map +1 -1
  262. package/dist/shared/als-slots.d.ts +41 -0
  263. package/dist/shared/als-slots.d.ts.map +1 -0
  264. package/dist/shared/base-path.d.ts +56 -0
  265. package/dist/shared/base-path.d.ts.map +1 -0
  266. package/dist/shared/param-value.d.ts +80 -0
  267. package/dist/shared/param-value.d.ts.map +1 -0
  268. package/dist/shared/payload-root.d.ts +108 -0
  269. package/dist/shared/payload-root.d.ts.map +1 -0
  270. package/dist/shared/rsc-cache-key.d.ts +163 -0
  271. package/dist/shared/rsc-cache-key.d.ts.map +1 -0
  272. package/dist/shared/rsc-error-envelope.d.ts +25 -0
  273. package/dist/shared/rsc-error-envelope.d.ts.map +1 -0
  274. package/dist/shared/rsc-manifest.d.ts +28 -0
  275. package/dist/shared/rsc-manifest.d.ts.map +1 -0
  276. package/dist/shared/rsc-payload-path.d.ts +42 -0
  277. package/dist/shared/rsc-payload-path.d.ts.map +1 -0
  278. package/dist/shared/segment-info.d.ts +59 -0
  279. package/dist/shared/segment-info.d.ts.map +1 -0
  280. package/dist/shared/slot-params.d.ts +51 -0
  281. package/dist/shared/slot-params.d.ts.map +1 -0
  282. package/dist/shared/static-platform-files.d.ts +71 -0
  283. package/dist/shared/static-platform-files.d.ts.map +1 -0
  284. package/dist/shims/navigation-client.d.ts +8 -19
  285. package/dist/shims/navigation-client.d.ts.map +1 -1
  286. package/dist/shims/navigation.d.ts +0 -1
  287. package/dist/shims/navigation.d.ts.map +1 -1
  288. package/docs/api/31-api-client.mdx +4 -2
  289. package/docs/learn/02-pages-and-layouts.mdx +1 -1
  290. package/docs/learn/11-error-handling.mdx +4 -3
  291. package/docs/learn/12-client-navigation.mdx +2 -2
  292. package/docs/learn/14-deploying.mdx +23 -0
  293. package/docs/more/01-advanced-routing.mdx +172 -2
  294. package/docs/more/04-metadata-and-fonts.mdx +1 -1
  295. package/package.json +2 -2
  296. package/src/adapters/build-output-helper.ts +116 -3
  297. package/src/adapters/cloudflare.ts +86 -11
  298. package/src/adapters/fs-identity.ts +156 -0
  299. package/src/adapters/nitro.ts +6 -6
  300. package/src/adapters/shared.ts +196 -21
  301. package/src/adapters/types.ts +13 -1
  302. package/src/cache/fast-hash.ts +5 -0
  303. package/src/client/browser-entry/action-dispatch.ts +9 -4
  304. package/src/client/browser-entry/hydrate.ts +40 -29
  305. package/src/client/browser-entry/index.ts +15 -1
  306. package/src/client/browser-entry/post-hydration.ts +10 -9
  307. package/src/client/browser-entry/router-init.ts +104 -48
  308. package/src/client/browser-entry/rsc-stream.ts +11 -2
  309. package/src/client/error-boundary.tsx +20 -15
  310. package/src/client/history.ts +13 -6
  311. package/src/client/internal.ts +4 -3
  312. package/src/client/link.tsx +55 -8
  313. package/src/client/navigation-api.ts +3 -3
  314. package/src/client/navigation-commit.ts +174 -0
  315. package/src/client/navigation-context.ts +40 -67
  316. package/src/client/navigation-root.tsx +326 -101
  317. package/src/client/params-context.ts +192 -0
  318. package/src/client/router-effects.ts +231 -0
  319. package/src/client/router-lifecycle.ts +288 -0
  320. package/src/client/router-pipeline.ts +389 -0
  321. package/src/client/router-ref.ts +1 -1
  322. package/src/client/router-skew.ts +30 -0
  323. package/src/client/router-types.ts +230 -0
  324. package/src/client/router.ts +242 -690
  325. package/src/client/rsc-fetch.ts +180 -122
  326. package/src/client/segment-cache.ts +121 -44
  327. package/src/client/ssr-data.ts +6 -0
  328. package/src/client/stale-client.ts +191 -0
  329. package/src/client/state.ts +14 -1
  330. package/src/client/top-loader.tsx +2 -1
  331. package/src/client/unload-guard.ts +34 -2
  332. package/src/client/use-cookie.ts +9 -2
  333. package/src/client/use-router.ts +1 -1
  334. package/src/client/use-segment-params.ts +41 -18
  335. package/src/index.ts +5 -1
  336. package/src/plugin-context.ts +34 -1
  337. package/src/plugins/adapter-build.ts +4 -0
  338. package/src/plugins/build-manifest.ts +34 -13
  339. package/src/plugins/entries.ts +4 -0
  340. package/src/plugins/fonts.ts +11 -8
  341. package/src/plugins/request-dep/analysis.ts +447 -0
  342. package/src/plugins/request-dep/index.ts +376 -0
  343. package/src/plugins/request-dep/origin.ts +310 -0
  344. package/src/plugins/routing.ts +60 -3
  345. package/src/plugins/static-build.ts +333 -63
  346. package/src/routing/codegen-types.ts +18 -0
  347. package/src/routing/codegen.ts +50 -10
  348. package/src/routing/collision-probe.ts +438 -0
  349. package/src/routing/collision-spaces.ts +281 -0
  350. package/src/routing/interception.ts +896 -50
  351. package/src/routing/manifest-codegen.ts +6 -9
  352. package/src/routing/scanner.ts +114 -113
  353. package/src/routing/segment-classify.ts +57 -0
  354. package/src/routing/segment-keys.ts +146 -0
  355. package/src/routing/slot-placement.ts +97 -0
  356. package/src/routing/types.ts +1 -3
  357. package/src/routing/walkers.ts +8 -0
  358. package/src/search-params/define.ts +6 -29
  359. package/src/segment-params/define.ts +4 -27
  360. package/src/server/action-handler.ts +3 -1
  361. package/src/server/actions.ts +6 -3
  362. package/src/server/als-registry.ts +2 -1
  363. package/src/server/build-manifest.ts +14 -1
  364. package/src/server/chain-url-parts.ts +163 -0
  365. package/src/server/children-interception.ts +115 -0
  366. package/src/server/default-status-page.ts +127 -0
  367. package/src/server/deny-boundary.ts +5 -31
  368. package/src/server/deny-renderer.ts +83 -22
  369. package/src/server/head-response.ts +54 -0
  370. package/src/server/param-coercion.ts +48 -18
  371. package/src/server/pipeline-helpers.ts +0 -45
  372. package/src/server/pipeline-interception.ts +81 -32
  373. package/src/server/pipeline-outcome.ts +3 -5
  374. package/src/server/pipeline-phases.ts +68 -16
  375. package/src/server/pipeline.ts +57 -10
  376. package/src/server/prebuilt-builder.ts +1 -7
  377. package/src/server/prebuilt-runtime.ts +4 -4
  378. package/src/server/primitives.ts +0 -18
  379. package/src/server/publish-params.ts +42 -0
  380. package/src/server/request-context.ts +97 -18
  381. package/src/server/route-element-builder.ts +89 -98
  382. package/src/server/route-handler.ts +8 -8
  383. package/src/server/route-matcher.ts +21 -9
  384. package/src/server/rsc-cache-key-guard.ts +170 -0
  385. package/src/server/rsc-entry/api-handler.ts +6 -8
  386. package/src/server/rsc-entry/error-renderer.ts +64 -25
  387. package/src/server/rsc-entry/helpers.ts +31 -16
  388. package/src/server/rsc-entry/index.ts +36 -28
  389. package/src/server/rsc-entry/render-route.ts +12 -7
  390. package/src/server/rsc-entry/revalidate-renderer.ts +1 -1
  391. package/src/server/rsc-entry/rsc-payload.ts +14 -25
  392. package/src/server/rsc-entry/rsc-stream.ts +4 -3
  393. package/src/server/rsc-entry/ssr-renderer.ts +13 -9
  394. package/src/server/sitemap-generator.ts +1 -7
  395. package/src/server/skippable-prefix.ts +92 -0
  396. package/src/server/slot-interception.ts +168 -0
  397. package/src/server/slot-resolver.ts +253 -156
  398. package/src/server/ssr-bridge-types.ts +6 -0
  399. package/src/server/ssr-entry.ts +12 -4
  400. package/src/server/ssr-wrappers.tsx +33 -32
  401. package/src/server/state-tree-diff.ts +14 -55
  402. package/src/server/static-generator.ts +67 -45
  403. package/src/server/static-not-found.ts +134 -0
  404. package/src/server/status-code-resolver.ts +4 -47
  405. package/src/shared/als-slots.ts +72 -0
  406. package/src/shared/base-path.ts +80 -0
  407. package/src/shared/param-value.ts +244 -0
  408. package/src/shared/payload-root.ts +151 -0
  409. package/src/shared/rsc-cache-key.ts +269 -0
  410. package/src/shared/rsc-error-envelope.ts +31 -0
  411. package/src/shared/rsc-manifest.ts +29 -0
  412. package/src/shared/rsc-payload-path.ts +45 -0
  413. package/src/shared/segment-info.ts +60 -0
  414. package/src/shared/slot-params.ts +111 -0
  415. package/src/shared/static-platform-files.ts +75 -0
  416. package/src/shims/navigation-client.ts +8 -26
  417. package/src/shims/navigation.ts +0 -4
  418. package/dist/_chunks/build-output-helper-DOGYFb_X.js +0 -196
  419. package/dist/_chunks/build-output-helper-DOGYFb_X.js.map +0 -1
  420. package/dist/_chunks/canonicalize-DQHyFClh.js.map +0 -1
  421. package/dist/_chunks/cli-schema-sync-D3naS3eH.js +0 -688
  422. package/dist/_chunks/cli-schema-sync-D3naS3eH.js.map +0 -1
  423. package/dist/_chunks/define-COtkxMRT.js +0 -191
  424. package/dist/_chunks/define-COtkxMRT.js.map +0 -1
  425. package/dist/_chunks/define-c4au4I9R.js +0 -82
  426. package/dist/_chunks/define-c4au4I9R.js.map +0 -1
  427. package/dist/_chunks/fast-hash-D6hIVt1Y.js.map +0 -1
  428. package/dist/_chunks/logger-AWfuX-KJ.js.map +0 -1
  429. package/dist/_chunks/navigation-root-bUDZLw74.js +0 -124
  430. package/dist/_chunks/navigation-root-bUDZLw74.js.map +0 -1
  431. package/dist/_chunks/plugin-context---kTF5v8.js.map +0 -1
  432. package/dist/_chunks/router-ref-CtmF-aPv.js.map +0 -1
  433. package/dist/_chunks/segment-classify-Byy425ng.js.map +0 -1
  434. package/dist/_chunks/ssr-data-BOWsq18U.js.map +0 -1
  435. package/dist/_chunks/use-segment-params-D1CzlgBo.js +0 -151
  436. package/dist/_chunks/use-segment-params-D1CzlgBo.js.map +0 -1
  437. package/dist/_chunks/walkers-BtTlKviE.js.map +0 -1
  438. package/dist/client/error-boundary.js.map +0 -1
  439. package/dist/plugins/request-dep.d.ts +0 -32
  440. package/dist/plugins/request-dep.d.ts.map +0 -1
  441. package/src/plugins/request-dep.ts +0 -499
@@ -0,0 +1,1857 @@
1
+ import { o as __exportAll } from "./dist-BA3u1z3W.js";
2
+ import { i as NULL_BYTE_RE, n as treePathDepth, r as ENCODED_SEPARATOR_RE, s as classifyMetadataRoute, t as computeSegmentTreePaths, u as isDynamicMetadataExtension } from "./segment-keys-BawYuNFO.js";
3
+ import { i as DEFAULT_PAGE_EXTENSIONS, n as classifyUrlSegment, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-C539Pa2O.js";
4
+ import { h as swallow } from "./logger-N7e5auP0.js";
5
+ import { a as resolveAppDir } from "./plugin-context-DEGLSJs3.js";
6
+ import { basename, extname, join } from "node:path";
7
+ import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
8
+ //#region src/server/tree-match.ts
9
+ /**
10
+ * Match URL path parts against a segment tree.
11
+ *
12
+ * Walks the tree depth-first with backtracking, applying priority
13
+ * ordering globally across group boundaries. Returns the matched
14
+ * segment chain and collected params, or null if no route matches.
15
+ *
16
+ * By default, a match requires a terminal node (one with `page` or
17
+ * `route`) at the leaf. Pass `{ requireTerminal: false }` to match
18
+ * any segment (used by metadata route matching).
19
+ *
20
+ * @param root The root segment node to start matching from.
21
+ * @param parts URL path parts (e.g. ['blog', 'hello-world']).
22
+ * Empty array matches the root itself (if terminal).
23
+ */
24
+ function matchUrlParts(root, parts, options) {
25
+ const chain = [];
26
+ const params = {};
27
+ if (matchNode(root, parts, 0, chain, params, options?.requireTerminal ?? true)) return {
28
+ chain,
29
+ params
30
+ };
31
+ return null;
32
+ }
33
+ /**
34
+ * Flatten children through group segments.
35
+ *
36
+ * Groups are transparent for URL matching — their non-group descendants
37
+ * are returned with the chain of group nodes leading to them. This lets
38
+ * the caller apply priority ordering (static > dynamic > catch-all >
39
+ * optional-catch-all) across all groups uniformly instead of per-group.
40
+ */
41
+ function collectEffectiveChildren(node, groupChain = []) {
42
+ const result = [];
43
+ for (const child of node.children) if (child.segmentType === "group") {
44
+ const nested = collectEffectiveChildren(child, [...groupChain, child]);
45
+ result.push(...nested);
46
+ } else result.push({
47
+ child,
48
+ groupChain
49
+ });
50
+ return result;
51
+ }
52
+ /** A node is terminal if it can serve a response (has a page or route handler). */
53
+ function isTerminal(node) {
54
+ return !!(node.page || node.route);
55
+ }
56
+ /** Combined affix length for specificity ordering. */
57
+ function affixLength(node) {
58
+ return (node.paramPrefix?.length ?? 0) + (node.paramSuffix?.length ?? 0);
59
+ }
60
+ /**
61
+ * Recursive depth-first matcher with backtracking.
62
+ *
63
+ * Mutates `chain` and `params` in place for performance; backtracks
64
+ * (restores previous state) when a candidate doesn't lead to a match.
65
+ */
66
+ function matchNode(node, parts, index, chain, params, requireTerminal) {
67
+ chain.push(node);
68
+ if (index >= parts.length) {
69
+ if (!requireTerminal || isTerminal(node)) return true;
70
+ for (const child of node.children) if (child.segmentType === "group") {
71
+ if (matchNode(child, parts, index, chain, params, requireTerminal)) return true;
72
+ }
73
+ const effective = collectEffectiveChildren(node);
74
+ for (const { child, groupChain } of effective) if (child.segmentType === "optional-catch-all" && (!requireTerminal || isTerminal(child))) {
75
+ chain.push(...groupChain, child);
76
+ return true;
77
+ }
78
+ chain.pop();
79
+ return false;
80
+ }
81
+ const part = parts[index];
82
+ const effective = collectEffectiveChildren(node);
83
+ for (const { child, groupChain } of effective) if (child.segmentType === "static" && child.segmentName === part) {
84
+ chain.push(...groupChain);
85
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
86
+ chain.length -= groupChain.length;
87
+ }
88
+ const affixed = effective.filter(({ child }) => child.segmentType === "dynamic" && child.paramName && (child.paramPrefix || child.paramSuffix));
89
+ affixed.sort((a, b) => affixLength(b.child) - affixLength(a.child));
90
+ for (const { child, groupChain } of affixed) {
91
+ const prefix = child.paramPrefix ?? "";
92
+ const suffix = child.paramSuffix ?? "";
93
+ if (part.length > prefix.length + suffix.length && (!prefix || part.startsWith(prefix)) && (!suffix || part.endsWith(suffix))) {
94
+ const value = part.slice(prefix.length, part.length - (suffix.length || 0));
95
+ chain.push(...groupChain);
96
+ const prev = params[child.paramName];
97
+ params[child.paramName] = value;
98
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
99
+ chain.length -= groupChain.length;
100
+ if (prev !== void 0) params[child.paramName] = prev;
101
+ else delete params[child.paramName];
102
+ }
103
+ }
104
+ for (const { child, groupChain } of effective) if (child.segmentType === "dynamic" && child.paramName && !child.paramPrefix && !child.paramSuffix) {
105
+ chain.push(...groupChain);
106
+ const prev = params[child.paramName];
107
+ params[child.paramName] = part;
108
+ if (matchNode(child, parts, index + 1, chain, params, requireTerminal)) return true;
109
+ chain.length -= groupChain.length;
110
+ if (prev !== void 0) params[child.paramName] = prev;
111
+ else delete params[child.paramName];
112
+ }
113
+ for (const { child, groupChain } of effective) if (child.segmentType === "catch-all" && child.paramName && (!requireTerminal || isTerminal(child))) {
114
+ chain.push(...groupChain, child);
115
+ params[child.paramName] = parts.slice(index);
116
+ return true;
117
+ }
118
+ for (const { child, groupChain } of effective) if (child.segmentType === "optional-catch-all" && child.paramName && (!requireTerminal || isTerminal(child))) {
119
+ chain.push(...groupChain, child);
120
+ params[child.paramName] = parts.slice(index);
121
+ return true;
122
+ }
123
+ chain.pop();
124
+ return false;
125
+ }
126
+ //#endregion
127
+ //#region src/routing/collision-probe.ts
128
+ /**
129
+ * Find a URL in this collision space whose winner depends on `children` order,
130
+ * or null if every probed URL resolves the same way in both orderings.
131
+ *
132
+ * `spaceRoot` is the node `matchUrlParts` starts from — the app root, a slot
133
+ * node, or an intercepting directory. `base` is the URL that root sits at, used
134
+ * only to render the reported URL.
135
+ */
136
+ function findOrderDependentCollision(spaceRoot, leaves, base) {
137
+ const reversed = withReversedChildren(spaceRoot);
138
+ const longTail = longTailLength(spaceRoot) + 1;
139
+ const minLength = longestStaticName(spaceRoot);
140
+ const seen = /* @__PURE__ */ new Set();
141
+ for (const leaf of leaves) for (const { parts, display } of probeUrlsForLeaf(spaceRoot, reversed, leaf, longTail, minLength)) {
142
+ const key = parts.join("/");
143
+ if (seen.has(key)) continue;
144
+ seen.add(key);
145
+ const first = matchedLeafFile(spaceRoot, parts);
146
+ const second = matchedLeafFile(reversed, parts);
147
+ if (!first || !second || first === second) continue;
148
+ return {
149
+ url: describeProbeUrl(base, display),
150
+ first,
151
+ second
152
+ };
153
+ }
154
+ return null;
155
+ }
156
+ /** Join a probe's display parts onto its space's base. */
157
+ function describeProbeUrl(base, display) {
158
+ if (display.length === 0) return base || "/";
159
+ return `${base === "/" ? "" : base}/${display.join("/")}`;
160
+ }
161
+ /**
162
+ * The file `matchUrlParts` resolves for a URL, or null if nothing does.
163
+ *
164
+ * A `route.ts` counts: `isTerminal` accepts either, so a route handler is a
165
+ * legitimate winner of the walk and an ambiguity between a page and a route
166
+ * handler is as real as one between two pages.
167
+ */
168
+ function matchedLeafFile(node, parts) {
169
+ const match = matchUrlParts(node, parts);
170
+ if (!match) return null;
171
+ const leaf = match.chain[match.chain.length - 1];
172
+ return leaf.page?.filePath ?? leaf.route?.filePath ?? null;
173
+ }
174
+ /**
175
+ * The values a probe's dynamic parts are tried with, in order.
176
+ *
177
+ * A probe stands in for "any value" at a dynamic position, so it is only useful
178
+ * if it reaches the leaf it was built for. A *static* sibling's literal name or
179
+ * a more specific *affixed* sibling's pattern can claim it instead, and that
180
+ * higher-priority segment then wins in both orderings — a genuine tie
181
+ * underneath goes unreported, which is safe but is the whole thing these
182
+ * validators are for.
183
+ *
184
+ * Which values are claimable is a question about `matchNode`'s precedence, so
185
+ * `probeUrlsForLeaf` asks `matchUrlParts` rather than deciding it here. This
186
+ * only has to offer enough shapes for the search to find one that works: an
187
+ * affixed sibling constrains the head of the value, its tail, or both, so head
188
+ * and tail are varied over an alphanumeric alphabet. The head varies fastest
189
+ * because a prefix is the more common affix. Exhausting the list is a missed
190
+ * collision like any other inadequate probe, so this is a search and not a
191
+ * proof — nothing downstream may treat it as one.
192
+ *
193
+ * Exported so a test that has to *name* a capturing static sibling can derive
194
+ * the name from this list rather than restate it — a fixture spelling the value
195
+ * out by hand stops being a capture the moment the list changes, and passes.
196
+ *
197
+ * Three revisions of a hand-built value each dodged one more capture and were
198
+ * each followed by another (avoid static names; avoid affix boundary
199
+ * characters; avoid re-affixed forms of static names — then a strictly more
200
+ * specific affixed sibling, TIM-1313). Each rule was modelling affix precedence
201
+ * by hand, which is what the match-shape model was deleted for.
202
+ */
203
+ function* probeCandidates(minLength = 0) {
204
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
205
+ const base = "timber-probe";
206
+ function* wave(core) {
207
+ for (const tail of alphabet) for (const head of alphabet) yield `${head}${core}${tail}`;
208
+ }
209
+ yield* wave(base);
210
+ const padded = base.padEnd(Math.max(12, minLength), "x");
211
+ if (padded !== base) yield* wave(padded);
212
+ }
213
+ /**
214
+ * The longest static segment name anywhere in the space.
215
+ *
216
+ * Read through `effectiveUrlSegment` so an intercepting directory counts as the
217
+ * segment it intercepts, and only static kinds count: a dynamic sibling claims
218
+ * a probe by pattern rather than by equality, which no length can escape.
219
+ */
220
+ function longestStaticName(node) {
221
+ let longest = 0;
222
+ for (const child of node.children) {
223
+ const seg = effectiveUrlSegment(child);
224
+ if (seg.segmentType === "static") longest = Math.max(longest, seg.segmentName.length);
225
+ longest = Math.max(longest, longestStaticName(child));
226
+ }
227
+ return longest;
228
+ }
229
+ /**
230
+ * The probe URLs for one leaf, built from the first candidate value that
231
+ * actually reaches it.
232
+ *
233
+ * "Reaches it" is `matchUrlParts` resolving one of the leaf's own URLs to the
234
+ * leaf's file, in either ordering — either is enough, because a leaf that wins
235
+ * only in the reversed ordering is precisely the contention being looked for.
236
+ * A catch-all leaf may be reached by its long probe and not its short one (at
237
+ * one part it loses to a bare dynamic sibling deterministically), so any one of
238
+ * the generated URLs landing is enough to accept the value.
239
+ *
240
+ * A leaf that no candidate reaches is shadowed at its position for every value
241
+ * tried — most often because it sits below a catch-all, which `matchNode`
242
+ * accepts only as a terminal and never descends past. Its probes are still
243
+ * emitted, from the first candidate: a probe that misses its own leaf is never
244
+ * *wrong* — it is a real URL, and a winner that differs between the two
245
+ * orderings is a real ambiguity whichever leaf it belongs to. Nothing here may
246
+ * report the leaf as unreachable; that is the universal claim these validators
247
+ * do not make.
248
+ */
249
+ function probeUrlsForLeaf(root, reversed, leaf, longTail, minLength) {
250
+ let fallback = null;
251
+ for (const value of probeCandidates(minLength)) {
252
+ const urls = probeUrlsFor(leaf.chain, value, longTail);
253
+ if (urls.some(({ parts }) => matchedLeafFile(root, parts) === leaf.filePath || matchedLeafFile(reversed, parts) === leaf.filePath)) return urls;
254
+ fallback ??= urls;
255
+ if (!urls.some(({ dynamic }) => dynamic)) break;
256
+ }
257
+ return fallback ?? [];
258
+ }
259
+ /**
260
+ * The URL part one segment contributes to a probe.
261
+ *
262
+ * A dynamic segment stands for any single value, so it contributes the
263
+ * candidate value — re-affixed, since an affixed segment only matches parts
264
+ * that carry its prefix and suffix, so a probe without them could not reach it.
265
+ * A catch-all stands for one or more parts, and one is enough to reach the leaf.
266
+ *
267
+ * The re-affixed part is the reason a value cannot be checked once for the
268
+ * whole space: it exposes the value to every affixed sibling that *extends*
269
+ * this segment's affixes, which differs per position. `probeUrlsForLeaf` asks
270
+ * the matcher whether the assembled URL reaches its leaf, and moves to the next
271
+ * candidate when it does not.
272
+ *
273
+ * Segments are read through `effectiveUrlSegment` so an intercepting directory
274
+ * contributes the part the segment it intercepts would.
275
+ */
276
+ function probePartFor(node, value) {
277
+ const seg = effectiveUrlSegment(node);
278
+ switch (seg.segmentType) {
279
+ case "dynamic": {
280
+ const prefix = seg.paramPrefix ?? "";
281
+ const suffix = seg.paramSuffix ?? "";
282
+ return {
283
+ part: `${prefix}${value}${suffix}`,
284
+ shown: `${prefix}<any>${suffix}`,
285
+ dynamic: true
286
+ };
287
+ }
288
+ case "catch-all":
289
+ case "optional-catch-all": return {
290
+ part: value,
291
+ shown: "<any>",
292
+ dynamic: true
293
+ };
294
+ default: return {
295
+ part: seg.segmentName,
296
+ shown: seg.segmentName,
297
+ dynamic: false
298
+ };
299
+ }
300
+ }
301
+ /**
302
+ * The URLs that reach a leaf.
303
+ *
304
+ * An **optional catch-all also matches zero parts**, so it answers the URL its
305
+ * parent sits at as well as longer ones. Both are probed: whether the shorter
306
+ * one is actually *its* to answer is `matchUrlParts`' business, not something
307
+ * to decide here — a page above it, or in a route group beside it, may take
308
+ * that URL deterministically, and the probe will simply report the same winner
309
+ * in both orderings.
310
+ */
311
+ function probeUrlsFor(chain, value, longTail) {
312
+ const probeParts = chain.map((node) => probePartFor(node, value));
313
+ const url = (ps) => ({
314
+ parts: ps.map((p) => p.part),
315
+ display: ps.map((p) => p.shown),
316
+ dynamic: ps.some((p) => p.dynamic)
317
+ });
318
+ const leaf = chain[chain.length - 1];
319
+ const kind = leaf && effectiveUrlSegment(leaf).segmentType;
320
+ if (!(kind === "catch-all" || kind === "optional-catch-all")) return [url(probeParts)];
321
+ const head = probeParts.slice(0, -1);
322
+ const urls = [url(probeParts)];
323
+ if (longTail > 1) {
324
+ const tail = Array.from({ length: longTail }, () => ({
325
+ part: value,
326
+ shown: "<any>",
327
+ dynamic: true
328
+ }));
329
+ urls.push(url([...head, ...tail]));
330
+ }
331
+ if (kind === "optional-catch-all") urls.push(url(head));
332
+ return urls;
333
+ }
334
+ /**
335
+ * One more than the longest fixed-length path in the space.
336
+ *
337
+ * A probe of this length cannot be claimed by any branch that consumes a fixed
338
+ * number of URL parts, so whatever matches it is a catch-all — which is
339
+ * exactly the competition a short probe hides.
340
+ */
341
+ function longTailLength(node) {
342
+ let deepest = 0;
343
+ for (const child of node.children) {
344
+ const own = child.segmentType === "group" ? 0 : 1;
345
+ deepest = Math.max(deepest, own + longTailLength(child));
346
+ }
347
+ return deepest;
348
+ }
349
+ /**
350
+ * The subtree with every `children` array reversed, top to bottom.
351
+ *
352
+ * Nodes are shallow-copied, so files and slots are shared with the original —
353
+ * only the ordering `matchNode` reads is different. Slots are not reversed
354
+ * because `matchNode` never walks them; each slot is validated as its own
355
+ * collision space, with its own reversed clone.
356
+ */
357
+ function withReversedChildren(node) {
358
+ return {
359
+ ...node,
360
+ children: [...node.children].reverse().map(withReversedChildren)
361
+ };
362
+ }
363
+ //#endregion
364
+ //#region src/routing/interception.ts
365
+ /**
366
+ * Group an owner's intercepting children by the URL position they contend for.
367
+ *
368
+ * This is the definition of *which interceptors compete*, and it has exactly
369
+ * one caller shape on each side of the build: `findInterceptingMatch` resolves
370
+ * a group with one `matchUrlParts` walk, and
371
+ * `assertNoInterceptedPatternCollisions` validates the same group as one
372
+ * collision space. Written twice, the two would be free to disagree about what
373
+ * competes — and a resolver that walks a wider set than the validator checked
374
+ * is precisely the order-dependence the validator exists to reject (TIM-1310).
375
+ *
376
+ * Contention is keyed by the computed intercepted **base**, not by the marker:
377
+ * under an owner at `/feed`, `(..)` and `(...)` both base at `/` and are both
378
+ * matched at index 0, so they are one group. Different bases are different
379
+ * positions — a `(.)` interceptor can never claim a target that belongs to a
380
+ * `(..)` one beside it, because the base must also match the target's leading
381
+ * parts.
382
+ *
383
+ * The base is a URL *pattern*, so its length is its part count only because
384
+ * every pattern part stands for exactly one URL part. A catch-all in the base
385
+ * breaks that, and `assertInterceptedBaseIsCountable` rejects the shape at
386
+ * build time.
387
+ *
388
+ * A node missing either marker field is skipped, which `classifySegment` never
389
+ * produces — it sets both whenever it reports `'intercepting'`. Stating the
390
+ * filter here rather than defaulting the marker is what makes the validator and
391
+ * the resolver see the same set: such a node renders nothing either way, and a
392
+ * validator more permissive than the resolver would be checking a candidate
393
+ * that never competes while the resolver walks one nobody checked.
394
+ *
395
+ * `children` is read directly rather than flattened through route groups,
396
+ * matching both resolvers: the slot resolver reads `slotNode.children`, and an
397
+ * interceptor deeper inside a slot subtree is rejected by
398
+ * `validateInterceptionPlacement`. On the children path an interceptor under a
399
+ * route group is legal and the *group* is its owner, so it is grouped with that
400
+ * group's other interceptors — which is again exactly what the resolver walks,
401
+ * since it resolves the owner by tree path.
402
+ */
403
+ function groupByInterceptedAnchor(ownerUrlPath, children) {
404
+ const byBase = /* @__PURE__ */ new Map();
405
+ for (const child of children) {
406
+ if (child.segmentType !== "intercepting") continue;
407
+ if (!child.interceptionMarker || !child.interceptedSegmentName) continue;
408
+ const base = computeInterceptedBase(ownerUrlPath, child.interceptionMarker);
409
+ const group = byBase.get(base);
410
+ if (group) group.interceptors.push(child);
411
+ else byBase.set(base, {
412
+ base,
413
+ anchorIndex: base === "/" ? 0 : base.slice(1).split("/").length,
414
+ interceptors: [child]
415
+ });
416
+ }
417
+ return [...byBase.values()].sort((a, b) => b.anchorIndex - a.anchorIndex);
418
+ }
419
+ /**
420
+ * Collect all interception rewrite rules from the route tree.
421
+ *
422
+ * Walks the tree recursively. For each intercepting segment, computes the
423
+ * intercepted URL based on the marker and the segment's position.
424
+ *
425
+ * The list is returned **deepest scope first**, which is what makes
426
+ * `findInterceptionMatch`'s first-match rule deterministic; see
427
+ * `sortByScopeDepth`.
428
+ */
429
+ function collectInterceptionRewrites(root) {
430
+ const rewrites = [];
431
+ walkForInterceptions(root, [root], false, rewrites);
432
+ return sortByScopeDepth(rewrites);
433
+ }
434
+ /**
435
+ * Order the rewrites deepest scope first, so the request-time first-match rule
436
+ * resolves two applicable rewrites by *nesting* rather than by tree-walk order.
437
+ *
438
+ * `findInterceptionMatch` returns the first rewrite whose pattern matches the
439
+ * target and whose scope the source route reports. More than one can satisfy
440
+ * both, and the case is not exotic — an owner and a directory *beneath* it may
441
+ * each hold an interceptor for one URL:
442
+ *
443
+ * ```
444
+ * app/feed/(.)photo/page.tsx scope /feed
445
+ * app/feed/(a)/(.)photo/page.tsx scope /feed/(a)
446
+ * ```
447
+ *
448
+ * A page inside `(a)` renders both owners' layouts, so the client reports both
449
+ * tree paths and both scopes pass. Unsorted, the winner is whichever the
450
+ * filesystem enumerated first — renaming the group flips which page a click
451
+ * opens, the defect class TIM-1305/TIM-1308/TIM-1310 each rejected in a
452
+ * different space. Here it is an ambiguity between *rewrites* rather than
453
+ * between pages inside one walk, so no collision space sees it.
454
+ *
455
+ * **Deepest wins, and it is specified rather than rejected** because the shape
456
+ * is one a correct app writes on purpose: a nested layout refining the
457
+ * interception its parent declares, exactly as `groupByInterceptedAnchor`
458
+ * already prefers the deepest *anchor* within one owner. The two rules are the
459
+ * same preference — the more local interception is the author's more specific
460
+ * statement — applied at the two levels the mechanism has.
461
+ *
462
+ * Depth is counted on the **tree path**, the identity that never collapses
463
+ * (TIM-1279/TIM-1280); a `urlPath` prefix test would relate `(browse)` and
464
+ * `(landing)`, which render different layouts and share no chain. Two scopes on
465
+ * one rendered chain are strictly nested, so depth orders them totally, and two
466
+ * scopes that are *not* on one chain — sibling groups, `feed/(a)` beside
467
+ * `feed/(b)` — never both pass the scope check, so their relative order is not
468
+ * observable. That is why this sorts on depth alone rather than testing
469
+ * ancestry: it is a total order over the pairs that can compete, and it costs
470
+ * nothing per request.
471
+ *
472
+ * Sorting is stable, so rewrites sharing one scope keep tree-walk order. Equal
473
+ * scopes mean one owner, and of the three pairings that produces only one is an
474
+ * ambiguity — a children-path interceptor beside a slot one, tracked as
475
+ * TIM-1319. The enumeration is in design/07-routing.md §"Selection Between
476
+ * Owners" rather than repeated here, so there is one place to correct if a
477
+ * rewrite ever grows a field that makes two of them distinguishable.
478
+ */
479
+ function sortByScopeDepth(rewrites) {
480
+ return rewrites.sort((a, b) => treePathDepth(b.interceptingScope) - treePathDepth(a.interceptingScope));
481
+ }
482
+ /**
483
+ * Validate that every intercepting segment sits where it can actually render.
484
+ *
485
+ * There are exactly two positions a renderer exists for, and they are the two
486
+ * shapes interception has:
487
+ *
488
+ * 1. **Direct child of a parallel slot** — the modal overlay. The slot
489
+ * resolver scans a slot node's *direct children* for an intercepting
490
+ * segment (`server/slot-interception.ts`). Nothing between the slot and
491
+ * the intercepting directory is allowed, because nothing walks it.
492
+ * 2. **Direct child of an ordinary segment or route group** — the sibling
493
+ * layout swap (TIM-1280). The pipeline resolves the owner by tree path and
494
+ * builds the rendered chain through the intercepting node itself
495
+ * (`server/children-interception.ts`).
496
+ *
497
+ * Everywhere else, rewrite generation still emits a rewrite and nothing
498
+ * renders it: the rewrite matches the soft navigation, and the user is served
499
+ * the page they were already on under a changed URL (TIM-1278). The rejected
500
+ * positions are:
501
+ *
502
+ * - **Inside a slot subtree but not directly under the slot**
503
+ * (`@modal/(inner)/(.)photo`). Neither renderer applies: the slot resolver
504
+ * only reads direct children, and the children-path resolver builds a
505
+ * *chain*, which cannot express a descent through a slot.
506
+ * - **Inside another intercepting subtree** (`(.)a/(.)b`). Left unvalidated
507
+ * `collectLeavesWithRewrites` walks the inner one as an ordinary URL
508
+ * segment and emits a pattern containing a literal "(.)b".
509
+ *
510
+ * Two further shapes are rejected here (TIM-1288). Both are about a catch-all,
511
+ * and both are specific to interception: elsewhere in the tree the same
512
+ * shapes are inert or fail safely, and the general "nothing below a catch-all
513
+ * is reachable" rule is tracked as TIM-1286.
514
+ *
515
+ * And one is specific to the children path: an owner chain that binds params
516
+ * (see `assertOwnerChainBindsNoParams`).
517
+ */
518
+ function validateInterceptionPlacement(root) {
519
+ walkForPlacement(root, "", {
520
+ parentIsSlot: false,
521
+ inSlotSubtree: false,
522
+ inInterceptingSubtree: false,
523
+ ancestorsBindParams: false
524
+ });
525
+ }
526
+ /**
527
+ * Reject a children-path interception whose owner chain binds params.
528
+ *
529
+ * The rendered chain is `[…owner ancestors, interceptingNode, …descendants]`,
530
+ * and the only pathname available to bind params from is the **target** — the
531
+ * URL being navigated to. The intercepting subtree's own params come from it
532
+ * by construction. The owner chain's do not, in general:
533
+ *
534
+ * - With a climbing marker the owner's URL segments are not in the target at
535
+ * all. `app/[team]/(..)photo/[id]` bases at "/", so the target is
536
+ * `/photo/9` — there is no team value anywhere in it, and `[team]`'s layout
537
+ * would render with the param it declares missing.
538
+ * - With `(.)` the base *is* the owner's `urlPath`, so the target's leading
539
+ * parts would bind it. Supporting only that half means one marker behaves
540
+ * differently from its siblings for reasons the author cannot see from the
541
+ * directory names, so the rule is stated once, on the owner chain.
542
+ *
543
+ * A layout that silently renders without the param it declares is the failure
544
+ * this prevents; it is rejected where it can be explained rather than left to
545
+ * surface as `undefined` deep inside user code. Route groups and static
546
+ * segments bind nothing and are unrestricted, which is the whole motivating
547
+ * shape (`app/(browse)/(...)[artistSlug]/…`).
548
+ *
549
+ * The rule stops at a slot boundary: a slot-mode interception re-matches the
550
+ * *source* route, which supplies the owner's params, so a dynamic owner is
551
+ * fine there and always has been.
552
+ */
553
+ /**
554
+ * Require a children-path interception's owner to have a `layout.tsx`.
555
+ *
556
+ * The scope is the owner's tree path, and the client reports which tree paths
557
+ * it has mounted from `X-Timber-Segments` — which carries **one entry per
558
+ * layout-bearing segment**, because those are the segments the client needs an
559
+ * outlet and a cache node for. `buildSegmentInfo` skips the rest.
560
+ *
561
+ * For the modal shape that set is exactly the set of possible scope owners, by
562
+ * construction: a slot is only resolved inside a rendering layout
563
+ * (`route-element-builder.ts`), so a layoutless segment can never own one. A
564
+ * children-path interception broke that equivalence — its owner is an ordinary
565
+ * directory and needs no layout.
566
+ *
567
+ * Left unchecked the result is a swap that works exactly once: the first soft
568
+ * navigation renders, then the client reports no such tree path, and the next
569
+ * navigation fails the scope check and falls back to the canonical page. That
570
+ * is fail-safe but silent, and the address-bar channel cannot recover it —
571
+ * once the swap is on screen the address holds the *intercepted* URL, which
572
+ * re-matches the canonical chain (the TIM-1282 problem, in the one shape the
573
+ * rendered-scope fix does not reach).
574
+ *
575
+ * Requiring the layout restores the invariant the state tree is built on
576
+ * rather than widening the wire format to carry segments that own no outlet
577
+ * and no payload. It also costs the author nothing they were not already
578
+ * doing: the point of this shape is to render inside the owner's own layout,
579
+ * so an owner with no layout has no chrome to preserve.
580
+ */
581
+ function assertOwnerHasLayout(ownerPath, childPath) {
582
+ const owner = ownerPath || "(app root)";
583
+ throw new Error(`Build error: intercepting route whose owner has no layout.\n Directory: app/${childPath}\n Owner: app/${owner}\nAn intercepting directory outside a parallel slot renders inside its owner's layout chain, and the owner must have a layout.tsx: the client reports which directories it has mounted from its layout segments, and a scope it cannot report would let the interception fire once and then silently stop.\nAdd app/${owner}/layout.tsx (a pass-through returning {children} is enough), or move the interception under a directory that has one.\nSee design/07-routing.md §"Intercepting Routes".`);
584
+ }
585
+ function assertOwnerChainBindsNoParams(childPath, marker) {
586
+ throw new Error(`Build error: intercepting route under a dynamic segment.\n Directory: app/${childPath}\nAn intercepting directory outside a parallel slot renders inside its own layout chain, and the only pathname available to bind params from is the intercepted URL — which does not carry the values of the segments above "${marker}".\nMove the interception so every directory above it is a static segment or a route group, or place it inside a parallel slot (@modal/) to render it as an overlay over the source route instead.\nSee design/07-routing.md §"Intercepting Routes".`);
587
+ }
588
+ /**
589
+ * Reject an intercepting route whose intercepted level is not well-defined.
590
+ *
591
+ * "One level up" is counted in URL segments, which works because every
592
+ * pattern part stands for exactly one URL part — except a catch-all, which
593
+ * stands for a number that varies per request. `anchorIndex` fixes the anchor
594
+ * at the base's pattern length, so with an owner at `/docs/[...path]` the
595
+ * interception resolves when the catch-all consumed exactly one segment
596
+ * (`/docs/a/photo/5`) and is dropped when it consumed more
597
+ * (`/docs/a/b/photo/5`), because the base no longer matches the target's
598
+ * leading parts.
599
+ *
600
+ * Dropping is fail-safe — the canonical route renders, as on hard navigation
601
+ * — so this is never a wrong page. But it is a modal that opens at one depth
602
+ * and silently does not at another, with nothing to tell the author why, and
603
+ * no request-time input can fix it: the only available source depth is
604
+ * `X-Timber-URL`, which is the browser's address bar, and once a modal is
605
+ * open that holds the *intercepted* URL rather than the source.
606
+ *
607
+ * So the shape is rejected where it can be explained. A marker that climbs
608
+ * *past* the catch-all is fine — `(..)` from `/docs/[...path]` bases at
609
+ * `/docs` — and so is `(...)`, which always bases at the root. The rule is on
610
+ * the *computed* base, not on having a catch-all anywhere above.
611
+ */
612
+ function assertInterceptedBaseIsCountable(child, ownerUrlPath, childPath) {
613
+ const marker = child.interceptionMarker ?? "(.)";
614
+ const base = computeInterceptedBase(ownerUrlPath, marker);
615
+ const ambiguous = (base === "/" ? [] : base.slice(1).split("/")).find((part) => {
616
+ const kind = classifyUrlSegment(part).kind;
617
+ return kind === "catch-all" || kind === "optional-catch-all";
618
+ });
619
+ if (!ambiguous) return;
620
+ throw new Error(`Build error: intercepting route below a catch-all segment.\n Directory: app/${childPath}\n Intercepted base: ${base}\nA catch-all (${ambiguous}) matches a number of URL segments that varies per request, so "${marker}" cannot identify which segment of a target pathname the interception starts at — the modal would open at one depth and silently not at another.\nMove the interception above the catch-all, or use a marker that climbs past it ((..) or (...)).\nSee design/07-routing.md §"Intercepting Routes".`);
621
+ }
622
+ /**
623
+ * Reject a catch-all inside an intercepting subtree that has directories
624
+ * below it.
625
+ *
626
+ * A catch-all consumes the whole remaining path, so nothing under it is
627
+ * reachable — `matchUrlParts` only accepts a catch-all as a terminal leaf and
628
+ * never descends past one. Rewrite generation is not so strict: it walks the
629
+ * subtree and emits `/feed/[...rest]/child`, and `pathnameMatchesPattern`
630
+ * returns as soon as it reaches the catch-all without ever looking at
631
+ * `child`. So the rewrite matches the navigation and then no renderer exists
632
+ * — the TIM-1278 failure mode reached by a different route, with the user
633
+ * served the page they were already on under a changed URL.
634
+ *
635
+ * The check covers the whole intercepting subtree, not just the intercepted
636
+ * segment: `(.)photo/[...rest]/child` emits `/feed/photo/[...rest]/child` and
637
+ * hijacks `/feed/photo/a/b` by exactly the same mechanism. And it does not
638
+ * exempt a catch-all that carries its own page — that one does render, but
639
+ * the rewrite generated for the unreachable descendant is broader than any
640
+ * route in the tree, so the tail modal fires on navigations no directory
641
+ * describes.
642
+ *
643
+ * Outside a slot the same shape merely 404s, which is why the general rule is
644
+ * tracked separately (TIM-1286); here it is unsafe, and it only became
645
+ * reachable when catch-all intercepted segments started matching at all
646
+ * (TIM-1281).
647
+ *
648
+ * The walk descends `children` and not `slots`, mirroring
649
+ * `collectLeavesWithRewrites` exactly: what this rejects is precisely the set
650
+ * of paths rewrite generation emits, so the two cannot disagree about which
651
+ * shapes exist. A slot nested inside an intercepting subtree produces no
652
+ * rewrite and so cannot hijack anything.
653
+ */
654
+ function assertInterceptedCatchAllsAreTerminal(node, nodePath) {
655
+ const { segmentType, segmentName } = effectiveUrlSegment(node);
656
+ if ((segmentType === "catch-all" || segmentType === "optional-catch-all") && node.children.length > 0) throw new Error(`Build error: catch-all with nested segments inside an intercepting route.\n Directory: app/${nodePath}\n Nested: ${node.children.map((c) => c.segmentName).join(", ")}\nA catch-all (${segmentName}) consumes every remaining URL segment, so nothing below it can ever match — but the interception rewrite would still be generated and would hijack the navigation with no page to render.\nMove the nested routes above the catch-all, or intercept a named segment instead.\nSee design/07-routing.md §"Intercepting Routes".`);
657
+ for (const child of node.children) assertInterceptedCatchAllsAreTerminal(child, `${nodePath}/${child.segmentName}`);
658
+ }
659
+ /**
660
+ * Reject two pages that answer one URL among the interceptors an owner
661
+ * resolves in a single walk.
662
+ *
663
+ * `validateRouteGroupCollisions` in the scanner returns early on an
664
+ * intercepting node, so nothing else validates in here. That exemption exists
665
+ * for a real reason — an interception's computed URL legitimately mirrors the
666
+ * canonical route it replaces, and interceptors at *different* anchors
667
+ * deliberately target one URL, which the resolver then orders (deepest anchor
668
+ * first). But the exemption was broader than its reason. Two shapes slip
669
+ * through it, and they are the same shape seen from two levels:
670
+ *
671
+ * feed/(.)photo/(a)/page.tsx feed/@modal/(.)[a]/page.tsx
672
+ * feed/(.)photo/(b)/page.tsx feed/@modal/(.)[b]/page.tsx
673
+ *
674
+ * Both pairs answer one URL, and in both `matchUrlParts` resolves the tie by
675
+ * whichever `children` array lists first — so the winner is whichever the
676
+ * filesystem enumerated first, and renaming a directory flips it. That is
677
+ * exactly what `validateRouteGroupCollisions` and
678
+ * `validateAffixedSiblingConflicts` exist to reject for ordinary siblings.
679
+ *
680
+ * **The collision space is the anchor group, not the directory.** An earlier
681
+ * revision ran once per intercepting directory, which sees the left-hand pair
682
+ * and not the right-hand one: those leaves live in two different directories.
683
+ * The space is `groupByInterceptedAnchor`'s output — the same grouping
684
+ * `findInterceptingMatch` hands to one `matchUrlParts` call — so what is
685
+ * validated together is exactly what is resolved together. Interceptors at
686
+ * different anchors stay independent, which is the documented case, and two
687
+ * slots on one owner are two owners and so two spaces.
688
+ *
689
+ * **Two checks, and the difference between them matters.** A duplicate
690
+ * intercepted *pattern* is decided by string equality, which is exact: two
691
+ * leaves with one pattern claim one set of URLs, whatever the precedence rules
692
+ * are. Everything else is decided by asking the matcher — `collision-probe.ts`,
693
+ * the same oracle the main tree and every slot use, so the spaces cannot
694
+ * disagree about whether a pair of pages collides.
695
+ *
696
+ * Not covered: two affixed dynamics that tie on specificity (`(x)/a-[id]` vs
697
+ * `(y)/[slug]-b`, ambiguous only for a part shaped `a-…-b`). No single probe
698
+ * URL exercises both, and `validateAffixedSiblingConflicts` already rejects
699
+ * that pair by affix length — including through groups, inside intercepting
700
+ * subtrees, and between two interceptors sharing an anchor.
701
+ *
702
+ * The shape applies to both interception mechanisms — a slot interceptor and a
703
+ * children-path one produce their leaves through the same walk, and both are
704
+ * resolved by `findInterceptingMatch` — so this is called from the one place in
705
+ * `walkForPlacement` that sees every owner regardless of position.
706
+ */
707
+ function assertNoInterceptedPatternCollisions(owner, ownerPath) {
708
+ for (const group of groupByInterceptedAnchor(owner.urlPath, owner.children)) assertAnchorGroupHasNoCollisions(group, ownerPath);
709
+ }
710
+ /**
711
+ * The URL-matching identity of an intercepting node, as a node.
712
+ *
713
+ * `matchUrlParts` reads `segmentType` directly and knows nothing about
714
+ * interception, so a marker'd directory has to be handed to it under the
715
+ * identity of the segment it intercepts — `(.)[id]` as `[id]`. Priority
716
+ * ordering, affix stripping and catch-all handling then come from the shared
717
+ * walker rather than from a second classifier here.
718
+ *
719
+ * Shared with `findInterceptingMatch` for the same reason the grouping is: the
720
+ * collision space is the resolver's synthetic anchor parent, so its children
721
+ * have to carry the identity the resolver gives them or the validator would be
722
+ * probing a tree that does not match the one served. The caller keeps its own
723
+ * map back to the real node — the proxy is a matching identity, not a
724
+ * replacement (tree paths still need the directory name).
725
+ */
726
+ function interceptorProxy(node) {
727
+ return {
728
+ ...node,
729
+ ...effectiveUrlSegment(node)
730
+ };
731
+ }
732
+ function assertAnchorGroupHasNoCollisions(group, ownerPath) {
733
+ const { base } = group;
734
+ const owner = ownerPath || "(app root)";
735
+ const proxies = group.interceptors.map(interceptorProxy);
736
+ const anchorNode = {
737
+ segmentName: "",
738
+ segmentType: "static",
739
+ urlPath: base,
740
+ children: proxies,
741
+ slots: {}
742
+ };
743
+ const patterns = /* @__PURE__ */ new Map();
744
+ const probeLeaves = [];
745
+ for (const proxy of proxies) walkInterceptedLeaves(proxy, joinInterceptedBase(base, proxy.segmentName), [proxy], (page, leaf) => {
746
+ const duplicate = patterns.get(leaf.interceptedPattern);
747
+ if (duplicate) throw new Error(`Build error: route collision between intercepting routes — two pages intercept the same URL.\n Owner: app/${owner}\n Intercepted base: ${base}\n URL: ${leaf.interceptedPattern}\n File 1: ${duplicate}\n File 2: ${page.filePath}\nA route group is transparent for matching, so moving a page into one does not give it a URL of its own — these two claim the same one. Rename or move one of them.\nSee design/07-routing.md §"Collisions Among Intercepting Routes".`);
748
+ patterns.set(leaf.interceptedPattern, page.filePath);
749
+ probeLeaves.push({
750
+ filePath: page.filePath,
751
+ chain: leaf.chain
752
+ });
753
+ });
754
+ const collision = findOrderDependentCollision(anchorNode, probeLeaves, base);
755
+ if (collision) throw new Error(`Build error: route collision between intercepting routes — two pages answer the same URL.\n Owner: app/${owner}\n Intercepted base: ${base}\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.\nPages 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.\nIntercepting directories based at *different* URLs may target one page — the resolver tries the deepest first — so this rejects only an ambiguity among the ones based at ${base}.\nSee design/07-routing.md §"Collisions Among Intercepting Routes".`);
756
+ }
757
+ function walkForPlacement(node, path, ctx) {
758
+ for (const child of node.children) {
759
+ const childPath = path ? `${path}/${child.segmentName}` : child.segmentName;
760
+ if (child.segmentType === "intercepting") {
761
+ const marker = child.interceptionMarker ?? "(.)";
762
+ if (ctx.inInterceptingSubtree) throw new Error(`Build error: intercepting route nested inside another intercepting route.\n Directory: app/${childPath}\nAn intercepting directory (${marker}) resolves against the URL its own parent renders at, and an intercepting subtree has no such URL — nothing walks it, so the rewrite would match the navigation and then have nothing to render.\nSee design/07-routing.md §"Intercepting Routes".`);
763
+ if (ctx.inSlotSubtree && !ctx.parentIsSlot) throw new Error(`Build error: intercepting route inside a parallel slot but not directly under it.\n Directory: app/${childPath}\nAn intercepting directory (${marker}) inside an @slot must be a *direct* child of that slot, e.g. app/feed/@modal/${child.segmentName}/page.tsx. The slot resolver scans the slot's direct children only; elsewhere the rewrite would match the navigation and then have nothing to render.\nSee design/07-routing.md §"Intercepting Routes".`);
764
+ if (!ctx.parentIsSlot && ctx.ancestorsBindParams) assertOwnerChainBindsNoParams(childPath, marker);
765
+ if (!ctx.parentIsSlot && !node.layout) assertOwnerHasLayout(path, childPath);
766
+ assertInterceptedBaseIsCountable(child, node.urlPath, childPath);
767
+ assertInterceptedCatchAllsAreTerminal(child, childPath);
768
+ }
769
+ walkForPlacement(child, childPath, {
770
+ parentIsSlot: false,
771
+ inSlotSubtree: ctx.inSlotSubtree,
772
+ inInterceptingSubtree: ctx.inInterceptingSubtree || child.segmentType === "intercepting",
773
+ ancestorsBindParams: ctx.ancestorsBindParams || !!child.paramName
774
+ });
775
+ }
776
+ assertNoInterceptedPatternCollisions(node, path);
777
+ for (const [slotName, slotNode] of Object.entries(node.slots)) walkForPlacement(slotNode, path ? `${path}/@${slotName}` : `@${slotName}`, {
778
+ parentIsSlot: true,
779
+ inSlotSubtree: true,
780
+ inInterceptingSubtree: ctx.inInterceptingSubtree,
781
+ ancestorsBindParams: false
782
+ });
783
+ }
784
+ /**
785
+ * Recursively walk the segment tree to find intercepting routes.
786
+ *
787
+ * `ancestors` deliberately excludes slot nodes: a slot doesn't appear in a
788
+ * matched route chain, so the last entry is always the nearest chain-visible
789
+ * ancestor — the segment that owns the slot, and therefore the segment whose
790
+ * presence in the source route gates the interception.
791
+ *
792
+ * Intercepting nodes only ever appear as a direct child of a slot or of an
793
+ * ordinary chain segment in a valid tree; `validateInterceptionPlacement`
794
+ * rejects every other placement at scan time, so this walk never has to
795
+ * decide what an unrenderable intercepting node should generate.
796
+ *
797
+ * `parentIsSlot` is what distinguishes the two shapes, and it is the only
798
+ * input that does: the owner, the scope and the intercepted pattern are all
799
+ * computed identically either way.
800
+ */
801
+ function walkForInterceptions(node, ancestors, parentIsSlot, rewrites) {
802
+ for (const child of node.children) if (child.segmentType === "intercepting" && child.interceptionMarker) collectFromInterceptingNode(child, ancestors, parentIsSlot, rewrites);
803
+ else walkForInterceptions(child, [...ancestors, child], false, rewrites);
804
+ for (const slot of Object.values(node.slots)) walkForInterceptions(slot, ancestors, true, rewrites);
805
+ }
806
+ /**
807
+ * For an intercepting segment, find all leaf pages in its sub-tree and
808
+ * generate rewrite rules for each.
809
+ */
810
+ function collectFromInterceptingNode(interceptingNode, ancestors, parentIsSlot, rewrites) {
811
+ const marker = interceptingNode.interceptionMarker;
812
+ const segmentName = interceptingNode.interceptedSegmentName;
813
+ const parentUrlPath = ancestors[ancestors.length - 1].urlPath;
814
+ const interceptedUrlBase = computeInterceptedUrlBase(parentUrlPath, marker, segmentName);
815
+ const ancestorPaths = computeSegmentTreePaths(ancestors);
816
+ const interceptingScope = ancestorPaths[ancestorPaths.length - 1];
817
+ collectLeavesWithRewrites(interceptingNode, interceptedUrlBase, parentIsSlot ? {
818
+ mode: "slot",
819
+ interceptingPrefix: parentUrlPath,
820
+ interceptingScope
821
+ } : {
822
+ mode: "children",
823
+ interceptingScope
824
+ }, rewrites);
825
+ }
826
+ /**
827
+ * Walk an intercepting sub-tree and visit every page-bearing node with the URL
828
+ * pattern it is intercepted at, and URLs that reach it.
829
+ *
830
+ * Route groups are transparent, exactly as they are in the main tree — which
831
+ * is what makes two groups under one interceptor able to claim one URL, and is
832
+ * why the collision validator has to walk the same shape this does.
833
+ *
834
+ * Rewrite generation and that validator are the two callers. They share this
835
+ * walk rather than each having their own so they cannot disagree about which
836
+ * URLs an interceptor claims: a leaf the validator did not see is a rewrite
837
+ * nobody checked, and a leaf only the validator sees is a build error for a
838
+ * route that does not exist. Slots are not descended, here or in either caller
839
+ * — a slot nested inside an intercepting subtree produces no rewrite.
840
+ *
841
+ * That answers the rewrite question only, and the resolution question is
842
+ * answered elsewhere: `validateSlotsInsideInterceptingSubtree`
843
+ * (`collision-spaces.ts`) gives each such slot its own collision space, and
844
+ * `validateSlotPlacement` (`slot-placement.ts`) rejects the ones no renderer
845
+ * reaches. Between them the slots this walk skips are covered; do not conclude
846
+ * from the skip here that they are unvalidated (TIM-1308, TIM-1311).
847
+ *
848
+ * The walk reports the chain of URL-contributing nodes rather than building
849
+ * probe URLs itself: choosing a probe value means running the matcher over the
850
+ * whole subtree, which is the validator's business and not something rewrite
851
+ * generation should be paying for or passing dummy arguments around.
852
+ */
853
+ function walkInterceptedLeaves(node, interceptedUrlPath, chain, visit) {
854
+ if (node.page) visit(node.page, {
855
+ interceptedPattern: interceptedUrlPath,
856
+ chain
857
+ });
858
+ for (const child of node.children) {
859
+ const isGroup = child.segmentType === "group";
860
+ walkInterceptedLeaves(child, isGroup ? interceptedUrlPath : `${interceptedUrlPath}/${child.segmentName}`, isGroup ? chain : [...chain, child], visit);
861
+ }
862
+ }
863
+ /**
864
+ * Recursively find leaf pages in an intercepting sub-tree and generate
865
+ * rewrite rules for each.
866
+ */
867
+ function collectLeavesWithRewrites(node, interceptedUrlPath, shape, rewrites) {
868
+ walkInterceptedLeaves(node, interceptedUrlPath, [], (_page, leaf) => {
869
+ rewrites.push({
870
+ ...shape,
871
+ interceptedPattern: leaf.interceptedPattern
872
+ });
873
+ });
874
+ }
875
+ /**
876
+ * How many URL levels a marker climbs from the slot owner to reach the
877
+ * intercepted segment, or `'root'` for a marker that climbs all the way.
878
+ *
879
+ * Level counting operates on URL path segments, NOT filesystem directories.
880
+ * Route groups and parallel slots are already excluded from urlPath (they
881
+ * don't add URL depth), so (..) correctly climbs visible segments. This
882
+ * avoids the Vinext bug where path.dirname() on filesystem paths would
883
+ * waste climbs on invisible route groups.
884
+ *
885
+ * Used only by `computeInterceptedBase` below — both rewrite generation and
886
+ * the slot resolver go through that, so the arithmetic exists once.
887
+ */
888
+ function interceptionClimb(marker) {
889
+ switch (marker) {
890
+ case "(.)": return 0;
891
+ case "(..)": return 1;
892
+ case "(..)(..)": return 2;
893
+ case "(...)": return "root";
894
+ }
895
+ }
896
+ /**
897
+ * Compute the base URL that an intercepting route intercepts, given the
898
+ * parent's URL path and the interception marker.
899
+ *
900
+ * - (.) — same level: parent's URL path
901
+ * - (..) — one level up: parent's parent URL path
902
+ * - (...) — root level: /
903
+ * - (..)(..) — two levels up: parent's grandparent URL path
904
+ *
905
+ * The result is a URL **pattern**, not a URL — `parentUrlPath` carries the
906
+ * directory names, so a dynamic ancestor appears as `/docs/[...path]`.
907
+ * Rewrite generation wants exactly that. The slot resolver imports this to
908
+ * locate the intercepted segment in a concrete target pathname, and must
909
+ * therefore account for a bracket part standing for a different number of
910
+ * URL parts than itself (TIM-1281).
911
+ *
912
+ * Climbing past the root clamps to `/` rather than erroring, so generation
913
+ * and resolution never disagree about what an over-reaching marker
914
+ * intercepts.
915
+ */
916
+ /**
917
+ * The URL pattern an intercepting directory's own page sits at — its
918
+ * `computeInterceptedBase` joined with the segment it intercepts.
919
+ *
920
+ * The root case is why this is a function rather than a template literal at
921
+ * each caller: a base of `/` must not produce `//photo`. Rewrite generation
922
+ * and the collision validator both start their walk from this value, so the
923
+ * two describe the same URLs by construction.
924
+ */
925
+ function computeInterceptedUrlBase(parentUrlPath, marker, interceptedSegmentName) {
926
+ return joinInterceptedBase(computeInterceptedBase(parentUrlPath, marker), interceptedSegmentName);
927
+ }
928
+ /**
929
+ * An intercepted base joined with one segment beneath it.
930
+ *
931
+ * The whole content of the "function rather than a template literal" rule
932
+ * above: a base of `/` must not produce `//photo`. The collision validator has
933
+ * the base in hand already (it groups by it) and joins through this rather than
934
+ * re-deriving it from an owner path, so both callers spell the root case once.
935
+ */
936
+ function joinInterceptedBase(base, segmentName) {
937
+ return base === "/" ? `/${segmentName}` : `${base}/${segmentName}`;
938
+ }
939
+ function computeInterceptedBase(parentUrlPath, marker) {
940
+ const climb = interceptionClimb(marker);
941
+ if (climb === "root") return "/";
942
+ const parts = parentUrlPath.split("/").filter(Boolean);
943
+ for (let i = 0; i < climb; i++) parts.pop();
944
+ return parts.length === 0 ? "/" : `/${parts.join("/")}`;
945
+ }
946
+ //#endregion
947
+ //#region src/routing/collision-spaces.ts
948
+ /**
949
+ * Validate that no two pages/routes in one collision space answer the same URL.
950
+ *
951
+ * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim
952
+ * /login — the scanner must detect and reject this at build time.
953
+ *
954
+ * Each parallel slot is validated as its OWN collision space: a slot's pages
955
+ * intentionally share URL paths with the parent tree (that's the point of
956
+ * parallel routes), but two route groups INSIDE one slot claiming the same
957
+ * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.
958
+ */
959
+ function validateRouteGroupCollisions(root) {
960
+ validateCollisionSpace(root, "", root.urlPath);
961
+ }
962
+ /**
963
+ * Validate one collision space — the main tree, or one parallel slot.
964
+ *
965
+ * **Two checks, and the difference between them matters.** Two leaves at the
966
+ * same `urlPath` are decided by string equality, which is exact and needs no
967
+ * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs
968
+ * whatever the precedence rules are, and naming the shared path is the clearest
969
+ * thing to tell the author.
970
+ *
971
+ * Everything else is decided by asking the matcher, through the shared oracle
972
+ * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses
973
+ * every pair that matches the same URLs while being *spelled* differently:
974
+ * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority
975
+ * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`
976
+ * because an optional catch-all also matches zero parts. Both built before
977
+ * TIM-1308 with filesystem enumeration order deciding which page renders,
978
+ * which is precisely what this validator and `validateAffixedSiblingConflicts`
979
+ * exist to reject.
980
+ *
981
+ * Segment *kinds* stay distinct without any special-casing here, because the
982
+ * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside
983
+ * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is
984
+ * not reported. So does an affixed sibling against a bare one; the
985
+ * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and
986
+ * duplicating it here would double-report.
987
+ */
988
+ function validateCollisionSpace(spaceRoot, segmentPath, base) {
989
+ const leaves = [];
990
+ collectRoutableLeaves(spaceRoot, /* @__PURE__ */ new Map(), segmentPath, [], leaves, base);
991
+ const collision = findOrderDependentCollision(spaceRoot, leaves, base);
992
+ if (!collision) return;
993
+ 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.`);
994
+ }
995
+ /**
996
+ * Walk one collision space and collect its routable leaves (page or route
997
+ * files), throwing on an exact `urlPath` collision. Each slot recurses as its
998
+ * OWN space — slots are parallel routes that intentionally share URL paths with
999
+ * their parent tree, but collisions within a single slot are real errors.
1000
+ *
1001
+ * The early return at an intercepting node drops that subtree's own pages from
1002
+ * this space, but not its slots: a slot is its own collision space wherever it
1003
+ * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before
1004
+ * returning.
1005
+ *
1006
+ * `chain` accumulates the URL-contributing nodes from the space root down, for
1007
+ * the probe oracle. Route groups are excluded because they are transparent for
1008
+ * matching, and the space root itself is excluded because `matchUrlParts`
1009
+ * matches parts against its *children* — the root consumes nothing.
1010
+ */
1011
+ function collectRoutableLeaves(node, seen, segmentPath, chain, leaves, base) {
1012
+ const currentPath = segmentPath ? `${segmentPath}/${node.segmentName}` : node.segmentName || "(root)";
1013
+ if (node.segmentType === "intercepting") {
1014
+ validateSlotsInsideInterceptingSubtree(node, currentPath, interceptedBaseOf(node, node.urlPath));
1015
+ return;
1016
+ }
1017
+ const routableFile = node.page ?? node.route;
1018
+ if (routableFile) {
1019
+ const existing = seen.get(node.urlPath);
1020
+ 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.`);
1021
+ seen.set(node.urlPath, {
1022
+ filePath: routableFile.filePath,
1023
+ segmentPath: currentPath
1024
+ });
1025
+ leaves.push({
1026
+ filePath: routableFile.filePath,
1027
+ chain
1028
+ });
1029
+ }
1030
+ for (const child of node.children) collectRoutableLeaves(child, seen, currentPath, child.segmentType === "group" ? chain : [...chain, child], leaves, base);
1031
+ for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));
1032
+ }
1033
+ /**
1034
+ * Validate every parallel slot nested anywhere inside an intercepting subtree.
1035
+ *
1036
+ * Two walks each skip these slots for their own good reason, and together they
1037
+ * left them checked by nothing: `collectRoutableLeaves` returns at the
1038
+ * intercepting node before it reaches them, and `walkInterceptedLeaves`
1039
+ * deliberately does not descend slots — correct for rewrite generation, since a
1040
+ * slot inside an intercepting subtree produces no rewrite. But "produces no
1041
+ * rewrite" answers the rewrite question and not the resolution one, so
1042
+ * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor
1043
+ * built with filesystem order picking the page — the ordinary per-slot
1044
+ * collision that fails the build anywhere else in the tree (codex, on PR #1002).
1045
+ *
1046
+ * A slot is its own collision space wherever it sits, so each one is validated
1047
+ * as one.
1048
+ *
1049
+ * **Which interception shape this still applies to.** TIM-1311 answered the
1050
+ * question this was written under — whether such a slot renders at all — and
1051
+ * the answer is per-shape:
1052
+ *
1053
+ * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node
1054
+ * joins the main route chain, so `route-element-builder.ts` resolves slots on
1055
+ * it and below it like any other chain segment. They render, and this is the
1056
+ * space where the check is load-bearing.
1057
+ * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another
1058
+ * slot's subtree, which no renderer descends for slots — so it never renders,
1059
+ * and `validateSlotPlacement` now rejects the placement before this runs.
1060
+ * That rule subsumes this one for the modal shape rather than conflicting
1061
+ * with it, exactly as anticipated.
1062
+ *
1063
+ * So this walk is reached only for children-path interceptors in a valid tree.
1064
+ * It is not narrowed to them: the rule it states — a slot is its own collision
1065
+ * space wherever it sits — is shape-independent, and making it conditional on a
1066
+ * property the placement validator already guarantees would just be a second
1067
+ * place for the two to disagree.
1068
+ *
1069
+ * The walk covers the whole subtree, not just the interceptor's direct slot
1070
+ * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the
1071
+ * same reason as `(...)photo/@side`.
1072
+ */
1073
+ function validateSlotsInsideInterceptingSubtree(node, segmentPath, base) {
1074
+ for (const slotNode of Object.values(node.slots)) validateCollisionSpace(slotNode, segmentPath, base);
1075
+ for (const child of node.children) validateSlotsInsideInterceptingSubtree(child, `${segmentPath}/${child.segmentName}`, childInterceptedBase(child, base));
1076
+ }
1077
+ /**
1078
+ * The URL a leaf answers, built from its space's base and its own chain.
1079
+ *
1080
+ * Read instead of `node.urlPath` because `urlPath` inside an intercepting
1081
+ * subtree is parent-relative and is not an address — the collision URL has to
1082
+ * be one the author can actually find. Outside an intercepting subtree the two
1083
+ * are identical by construction: the base is the space root's `urlPath` and the
1084
+ * chain is every URL-contributing segment below it.
1085
+ */
1086
+ function urlFromChain(base, chain) {
1087
+ if (chain.length === 0) return base || "/";
1088
+ const tail = chain.map((n) => n.segmentName).join("/");
1089
+ return `${base === "/" ? "" : base}/${tail}`;
1090
+ }
1091
+ /**
1092
+ * The intercepted URL an intercepting directory's own page sits at.
1093
+ *
1094
+ * `urlPath` inside an intercepting subtree is deliberately parent-relative and
1095
+ * is **not** an address (see design/07-routing.md §"Why urlPath Stays
1096
+ * Parent-Relative Inside an Intercepting Subtree"), so a collision reported
1097
+ * from one names a URL the author cannot find. The intercepted base is the real
1098
+ * address, and it is what rewrite generation and the interception collision
1099
+ * validator both already use.
1100
+ */
1101
+ function interceptedBaseOf(node, ownerUrlPath) {
1102
+ return computeInterceptedUrlBase(ownerUrlPath, node.interceptionMarker ?? "(.)", node.interceptedSegmentName ?? node.segmentName);
1103
+ }
1104
+ /**
1105
+ * Extend an intercepted base by one child segment.
1106
+ *
1107
+ * Route groups are transparent and contribute nothing. A nested intercepting
1108
+ * node re-bases from its own marker rather than appending — that tree is
1109
+ * rejected by `validateInterceptionPlacement`, but collision validation runs
1110
+ * first, so it still has to produce a sensible URL rather than one containing a
1111
+ * literal "(.)b".
1112
+ */
1113
+ function childInterceptedBase(child, base) {
1114
+ if (child.segmentType === "group") return base;
1115
+ if (child.segmentType === "intercepting") return interceptedBaseOf(child, base);
1116
+ return base === "/" ? `/${child.segmentName}` : `${base}/${child.segmentName}`;
1117
+ }
1118
+ //#endregion
1119
+ //#region src/routing/slot-placement.ts
1120
+ /**
1121
+ * Reject every parallel slot that no renderer reaches.
1122
+ *
1123
+ * **Where slots are resolved.** Two places read `segment.slots`, and both walk
1124
+ * the main route chain: `route-element-builder.ts` (the RSC render) and
1125
+ * `tree-builder.ts`. Neither is reachable from inside a slot. The slot's own
1126
+ * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched
1127
+ * chain to apply that chain's layouts, error boundaries and access gates
1128
+ * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`
1129
+ * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and
1130
+ * everything below it is dead: the file is scanned, typed, code-split and
1131
+ * shipped, and no request can render it.
1132
+ *
1133
+ * That is the TIM-1278 failure — a directory that silently never renders —
1134
+ * and the reason it is a build error rather than a documented limit is that
1135
+ * nothing at request time can report it. A slot that does not match renders
1136
+ * `default.tsx` or `null`, which is exactly what a slot the resolver never
1137
+ * looked at also produces, so the author sees the *designed* behaviour of a
1138
+ * non-matching slot and has no signal to distinguish it from a slot that
1139
+ * cannot match at all.
1140
+ *
1141
+ * **Interception is incidental.** TIM-1311 arrived as
1142
+ * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the
1143
+ * identical `feed/@modal/photo/@side` never renders either, for the same
1144
+ * reason and with no marker anywhere. Rejecting only the intercepting spelling
1145
+ * would have drawn a line the author cannot see from the directory names.
1146
+ *
1147
+ * The children-path interception shape is **not** affected and must not be:
1148
+ * its intercepting node joins the main chain (`server/children-interception.ts`
1149
+ * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary
1150
+ * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below
1151
+ * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`
1152
+ * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot
1153
+ * boundary, which is what this walk tracks — not the marker.
1154
+ */
1155
+ function validateSlotPlacement(root) {
1156
+ walkForSlotPlacement(root, "", null);
1157
+ }
1158
+ /**
1159
+ * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or
1160
+ * above `node`, or null on the main chain. It is carried rather than recomputed
1161
+ * so the error can name the slot that swallows the offender — "this is inside
1162
+ * @modal" is the part of the diagnosis the author cannot see from the offending
1163
+ * path alone.
1164
+ */
1165
+ function walkForSlotPlacement(node, path, enclosingSlotPath) {
1166
+ for (const [slotName, slotNode] of Object.entries(node.slots)) {
1167
+ const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;
1168
+ if (enclosingSlotPath !== null) throwNestedSlot(slotPath, enclosingSlotPath);
1169
+ walkForSlotPlacement(slotNode, slotPath, slotPath);
1170
+ }
1171
+ for (const child of node.children) walkForSlotPlacement(child, path ? `${path}/${child.segmentName}` : child.segmentName, enclosingSlotPath);
1172
+ }
1173
+ function throwNestedSlot(slotPath, enclosingSlotPath) {
1174
+ 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".`);
1175
+ }
1176
+ //#endregion
1177
+ //#region src/routing/scanner.ts
1178
+ /**
1179
+ * Route discovery scanner.
1180
+ *
1181
+ * Pure function: (appDir, config) → RouteTree
1182
+ *
1183
+ * Scans the app/ directory and builds a segment tree recognizing all
1184
+ * timber.js file conventions. Does NOT handle request matching — this
1185
+ * is discovery only.
1186
+ */
1187
+ /**
1188
+ * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)
1189
+ */
1190
+ var PAGE_EXT_CONVENTIONS = /* @__PURE__ */ new Set([
1191
+ "page",
1192
+ "layout",
1193
+ "error",
1194
+ "default",
1195
+ "denied"
1196
+ ]);
1197
+ /**
1198
+ * File convention names that are always .ts/.tsx (never .mdx etc.)
1199
+ */
1200
+ var FIXED_CONVENTIONS = /* @__PURE__ */ new Set([
1201
+ "middleware",
1202
+ "access",
1203
+ "route",
1204
+ "params"
1205
+ ]);
1206
+ /**
1207
+ * Status-code file patterns:
1208
+ * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx
1209
+ * - Category catch-alls: 4xx.tsx, 5xx.tsx
1210
+ */
1211
+ var STATUS_CODE_PATTERN = /^(\d{3}|[45]xx)$/;
1212
+ /**
1213
+ * Scan the app/ directory and build the route tree.
1214
+ *
1215
+ * @param appDir - Absolute path to the app/ directory
1216
+ * @param config - Scanner configuration
1217
+ * @returns The complete route tree
1218
+ */
1219
+ function scanRoutes(appDir, config = {}) {
1220
+ const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;
1221
+ const extSet = new Set(pageExtensions);
1222
+ const tree = { root: createSegmentNode("", "static", "/") };
1223
+ const proxyFile = findFixedFile(appDir, "proxy");
1224
+ if (proxyFile) tree.proxy = proxyFile;
1225
+ const globalErrorFile = findPageExtFile(appDir, "global-error", extSet);
1226
+ if (globalErrorFile) tree.globalError = globalErrorFile;
1227
+ scanSegmentFiles(appDir, tree.root, extSet);
1228
+ scanChildren(appDir, tree.root, extSet);
1229
+ validateSlotPlacement(tree.root);
1230
+ validateRouteGroupCollisions(tree.root);
1231
+ validateDuplicateParamNames(tree.root);
1232
+ validateUniqueBracketForms(tree.root);
1233
+ validateAffixedSiblingConflicts(tree.root);
1234
+ validateInterceptionPlacement(tree.root);
1235
+ return tree;
1236
+ }
1237
+ /**
1238
+ * Create an empty segment node.
1239
+ */
1240
+ function createSegmentNode(segmentName, segmentType, urlPath, paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix) {
1241
+ return {
1242
+ segmentName,
1243
+ segmentType,
1244
+ urlPath,
1245
+ paramName,
1246
+ paramPrefix,
1247
+ paramSuffix,
1248
+ interceptionMarker,
1249
+ interceptedSegmentName,
1250
+ children: [],
1251
+ slots: {}
1252
+ };
1253
+ }
1254
+ /**
1255
+ * Compute the URL path for a child segment given its parent's URL path.
1256
+ * Route groups, slots, and intercepting routes do NOT add URL depth.
1257
+ */
1258
+ function computeUrlPath(parentUrlPath, dirName, segmentType) {
1259
+ if (segmentType === "group" || segmentType === "slot" || segmentType === "intercepting") return parentUrlPath;
1260
+ return `${parentUrlPath === "/" ? "" : parentUrlPath}/${dirName}`;
1261
+ }
1262
+ /**
1263
+ * Scan a directory for file conventions and populate the segment node.
1264
+ */
1265
+ function scanSegmentFiles(dirPath, node, extSet) {
1266
+ let entries;
1267
+ try {
1268
+ entries = readdirSync(dirPath);
1269
+ } catch (err) {
1270
+ swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: "warn" });
1271
+ return;
1272
+ }
1273
+ for (const entry of entries) {
1274
+ const fullPath = join(dirPath, entry);
1275
+ try {
1276
+ if (statSync(fullPath).isDirectory()) continue;
1277
+ } catch {
1278
+ continue;
1279
+ }
1280
+ const ext = extname(entry).slice(1);
1281
+ const name = basename(entry, `.${ext}`);
1282
+ if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {
1283
+ const key = name;
1284
+ const existing = node[key];
1285
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1286
+ node[key] = {
1287
+ filePath: fullPath,
1288
+ extension: ext
1289
+ };
1290
+ continue;
1291
+ }
1292
+ if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {
1293
+ const key = name;
1294
+ const existing = node[key];
1295
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1296
+ node[key] = {
1297
+ filePath: fullPath,
1298
+ extension: ext
1299
+ };
1300
+ continue;
1301
+ }
1302
+ if (STATUS_CODE_PATTERN.test(name) && ext === "json") {
1303
+ if (!node.jsonStatusFiles) node.jsonStatusFiles = {};
1304
+ node.jsonStatusFiles[name] = {
1305
+ filePath: fullPath,
1306
+ extension: ext
1307
+ };
1308
+ continue;
1309
+ }
1310
+ if (STATUS_CODE_PATTERN.test(name) && extSet.has(ext)) {
1311
+ if (!node.statusFiles) node.statusFiles = {};
1312
+ const existing = node.statusFiles[name];
1313
+ if (existing) throwDuplicateConvention(name, existing.filePath, fullPath);
1314
+ node.statusFiles[name] = {
1315
+ filePath: fullPath,
1316
+ extension: ext
1317
+ };
1318
+ continue;
1319
+ }
1320
+ const metaInfo = classifyMetadataRoute(entry);
1321
+ if (metaInfo) {
1322
+ 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).`);
1323
+ if (!node.metadataRoutes) node.metadataRoutes = {};
1324
+ const existing = node.metadataRoutes[name];
1325
+ if (existing) {
1326
+ const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);
1327
+ const newIsDynamic = isDynamicMetadataExtension(name, ext);
1328
+ if (existingIsDynamic === newIsDynamic) throwDuplicateConvention(name, existing.filePath, fullPath);
1329
+ if (newIsDynamic) node.metadataRoutes[name] = {
1330
+ filePath: fullPath,
1331
+ extension: ext
1332
+ };
1333
+ } else node.metadataRoutes[name] = {
1334
+ filePath: fullPath,
1335
+ extension: ext
1336
+ };
1337
+ }
1338
+ }
1339
+ 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.`);
1340
+ }
1341
+ /**
1342
+ * Throw a build error for two files claiming the same convention slot in
1343
+ * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first
1344
+ * is platform-dependent (APFS sorts entries, ext4 does not) — silently
1345
+ * picking one would let macOS dev and Linux CI serve different
1346
+ * implementations of the same route.
1347
+ */
1348
+ function throwDuplicateConvention(convention, firstPath, secondPath) {
1349
+ 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.`);
1350
+ }
1351
+ /**
1352
+ * Recursively scan child directories and build the segment tree.
1353
+ */
1354
+ function scanChildren(dirPath, parentNode, extSet) {
1355
+ let entries;
1356
+ try {
1357
+ entries = readdirSync(dirPath);
1358
+ } catch (err) {
1359
+ swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: "warn" });
1360
+ return;
1361
+ }
1362
+ for (const entry of entries) {
1363
+ const fullPath = join(dirPath, entry);
1364
+ try {
1365
+ if (!statSync(fullPath).isDirectory()) continue;
1366
+ } catch {
1367
+ continue;
1368
+ }
1369
+ 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.`);
1370
+ 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.`);
1371
+ const { type, paramName, paramPrefix, paramSuffix, interceptionMarker, interceptedSegmentName } = classifySegment(entry);
1372
+ if (type === "private") continue;
1373
+ const childNode = createSegmentNode(entry, type, computeUrlPath(parentNode.urlPath, entry, type), paramName, interceptionMarker, interceptedSegmentName, paramPrefix, paramSuffix);
1374
+ scanSegmentFiles(fullPath, childNode, extSet);
1375
+ scanChildren(fullPath, childNode, extSet);
1376
+ if (type === "slot") {
1377
+ const slotName = entry.slice(1);
1378
+ parentNode.slots[slotName] = childNode;
1379
+ } else parentNode.children.push(childNode);
1380
+ }
1381
+ }
1382
+ /**
1383
+ * Validate that no route chain contains duplicate dynamic param names.
1384
+ *
1385
+ * Example violation:
1386
+ * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.
1387
+ *
1388
+ * Route groups are transparent — params accumulate through them.
1389
+ * Slots are independent — duplicate detection does NOT cross slot boundaries.
1390
+ *
1391
+ * See design/07-routing.md §"Duplicate Param Name Detection"
1392
+ */
1393
+ function validateDuplicateParamNames(root) {
1394
+ walkForDuplicateParams(root, /* @__PURE__ */ new Map());
1395
+ }
1396
+ /**
1397
+ * Recursively walk the segment tree, tracking seen param names → segment paths.
1398
+ * Throws on the first duplicate found.
1399
+ */
1400
+ function walkForDuplicateParams(node, seen) {
1401
+ const { paramName } = effectiveUrlSegment(node);
1402
+ if (paramName) {
1403
+ const existing = seen.get(paramName);
1404
+ 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.`);
1405
+ seen = new Map(seen);
1406
+ seen.set(paramName, node.urlPath || "/");
1407
+ }
1408
+ for (const child of node.children) walkForDuplicateParams(child, seen);
1409
+ for (const slotNode of Object.values(node.slots)) walkForDuplicateParams(slotNode, new Map(seen));
1410
+ }
1411
+ /**
1412
+ * Validate that each param name uses a single bracket form across the entire route tree.
1413
+ *
1414
+ * Different bracket forms produce different types:
1415
+ * [id] → string
1416
+ * [...id] → string[]
1417
+ * [[...id]] → string[] | undefined
1418
+ *
1419
+ * If the same param name appears with multiple forms, the no-argument
1420
+ * getSegmentParams() / useSegmentParams() return type becomes ambiguous.
1421
+ *
1422
+ * Same name + same form across different routes is fine and expected.
1423
+ */
1424
+ function validateUniqueBracketForms(root) {
1425
+ collectBracketForms(root, /* @__PURE__ */ new Map());
1426
+ }
1427
+ function collectBracketForms(node, forms) {
1428
+ const { paramName, segmentType } = effectiveUrlSegment(node);
1429
+ if (paramName && segmentType !== "static" && segmentType !== "group") {
1430
+ const existing = forms.get(paramName);
1431
+ if (existing && existing.segmentType !== segmentType) {
1432
+ const bracketExamples = {
1433
+ "dynamic": `[${paramName}]`,
1434
+ "catch-all": `[...${paramName}]`,
1435
+ "optional-catch-all": `[[...${paramName}]]`
1436
+ };
1437
+ 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]).`);
1438
+ }
1439
+ if (!existing) forms.set(paramName, {
1440
+ segmentType,
1441
+ urlPath: node.urlPath || "/"
1442
+ });
1443
+ }
1444
+ for (const child of node.children) collectBracketForms(child, forms);
1445
+ for (const slotNode of Object.values(node.slots)) collectBracketForms(slotNode, forms);
1446
+ }
1447
+ /**
1448
+ * Validate that no sibling affixed dynamic segments have equal specificity.
1449
+ *
1450
+ * Among affixed siblings, longer combined prefix+suffix length wins. When two
1451
+ * siblings tie (same total affix length), the router would fall back to
1452
+ * filesystem scan order — which is platform-dependent. This is a build error.
1453
+ *
1454
+ * Route groups are URL-transparent, so affixed segments inside different groups
1455
+ * at the same level still conflict with each other.
1456
+ *
1457
+ * Ambiguity requires the two segments to be candidates for the *same* URL
1458
+ * part, which is narrower than "same parent" once interception is involved:
1459
+ *
1460
+ * - Plain children and intercepting children never compete. They are resolved
1461
+ * by different walks — `findSlotMatch` matches the slot subtree (where
1462
+ * `tree-match.ts` ignores intercepting nodes outright) and
1463
+ * `findInterceptingMatch` builds a synthetic parent holding only
1464
+ * interceptors.
1465
+ * - Two interceptors compete only at the same anchor. `(.)a-[id]` and
1466
+ * `(..)[slug]-b` in one slot are based at different URL depths, so no
1467
+ * pathname reaches both, and `anchorIndex` rejects the one whose base does
1468
+ * not match the target. Grouping them together would fail the build for a
1469
+ * pair that can never be ambiguous.
1470
+ *
1471
+ * So candidates are keyed by the position they contend for, then by affix
1472
+ * length. See design/07-routing.md §"Priority" and §"Intercepting Routes".
1473
+ */
1474
+ function validateAffixedSiblingConflicts(node) {
1475
+ const affixed = collectEffectiveAffixed(node);
1476
+ if (affixed.length >= 2) {
1477
+ const byLength = /* @__PURE__ */ new Map();
1478
+ for (const child of affixed) {
1479
+ const key = `${contentionKey(node, child)}\0${affixLengthOf(child)}`;
1480
+ const group = byLength.get(key);
1481
+ if (group) group.push(child);
1482
+ else byLength.set(key, [child]);
1483
+ }
1484
+ 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.`);
1485
+ }
1486
+ for (const child of node.children) validateAffixedSiblingConflicts(child);
1487
+ for (const slotNode of Object.values(node.slots)) validateAffixedSiblingConflicts(slotNode);
1488
+ }
1489
+ /**
1490
+ * The URL position a child contends for, as a comparable key.
1491
+ *
1492
+ * Plain children contend for the parent's next part. An intercepting child
1493
+ * contends for a part determined by its marker's intercepted base, so two
1494
+ * markers of different depth are simply different positions — and two markers
1495
+ * that compute the *same* base do contend, which is why the key is the base
1496
+ * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).
1497
+ *
1498
+ * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical
1499
+ * statement of that grouping — it is what the resolver walks and what the
1500
+ * collision validator checks. This computes the same key from the same
1501
+ * `computeInterceptedBase` rather than calling it, because affix ambiguity is
1502
+ * decided per *child* and `collectEffectiveAffixed` looks through route groups,
1503
+ * so the two do not partition the same set of nodes.
1504
+ */
1505
+ function contentionKey(parent, child) {
1506
+ if (child.segmentType !== "intercepting") return "child";
1507
+ return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? "(.)")}`;
1508
+ }
1509
+ /** Combined affix length of a node, read through its effective identity. */
1510
+ function affixLengthOf(node) {
1511
+ const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);
1512
+ return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);
1513
+ }
1514
+ /**
1515
+ * Collect affixed dynamic segments that are effective children of a node.
1516
+ * Route groups are URL-transparent, so we look through them recursively.
1517
+ *
1518
+ * Segments are read through `effectiveUrlSegment`, so an intercepting
1519
+ * directory counts as the affixed segment it intercepts: `(.)a-[id]` is
1520
+ * `a-[id]`. The proxy the slot resolver builds hands those affixes to
1521
+ * `matchUrlParts`, whose equal-length sort is not stable across equal
1522
+ * specificity — so two intercepting siblings with the same combined affix
1523
+ * length would resolve by filesystem enumeration order, which is precisely
1524
+ * what this validator exists to prevent for ordinary siblings (TIM-1288).
1525
+ */
1526
+ function collectEffectiveAffixed(node) {
1527
+ const result = [];
1528
+ for (const child of node.children) {
1529
+ const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);
1530
+ if (segmentType === "dynamic" && (paramPrefix || paramSuffix)) result.push(child);
1531
+ else if (segmentType === "group") result.push(...collectEffectiveAffixed(child));
1532
+ }
1533
+ return result;
1534
+ }
1535
+ /**
1536
+ * Find a fixed-extension file (proxy.ts) in a directory.
1537
+ */
1538
+ function findFixedFile(dirPath, name) {
1539
+ for (const ext of ["ts", "tsx"]) {
1540
+ const fullPath = join(dirPath, `${name}.${ext}`);
1541
+ try {
1542
+ if (statSync(fullPath).isFile()) return {
1543
+ filePath: fullPath,
1544
+ extension: ext
1545
+ };
1546
+ } catch {}
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Find a file using the configured page extensions (tsx, ts, jsx, js, mdx, etc.).
1551
+ * Used for app-root conventions like global-error that aren't per-segment.
1552
+ */
1553
+ function findPageExtFile(dirPath, name, extSet) {
1554
+ for (const ext of extSet) {
1555
+ const fullPath = join(dirPath, `${name}.${ext}`);
1556
+ try {
1557
+ if (statSync(fullPath).isFile()) return {
1558
+ filePath: fullPath,
1559
+ extension: ext
1560
+ };
1561
+ } catch {}
1562
+ }
1563
+ }
1564
+ //#endregion
1565
+ //#region src/cli-schema-sync.ts
1566
+ /**
1567
+ * `timber schema sync` — scan filesystem for dynamic segments, append
1568
+ * missing entries with `codec.string` defaults, and remove stale entries
1569
+ * whose segments no longer exist in the filesystem.
1570
+ *
1571
+ * Design doc: design/41-global-params.md §Auto-Scaffolding
1572
+ */
1573
+ var cli_schema_sync_exports = /* @__PURE__ */ __exportAll({
1574
+ collectDynamicSegments: () => collectDynamicSegments,
1575
+ defaultCodecForSegment: () => defaultCodecForSegment,
1576
+ findSchemaFile: () => findSchemaFile,
1577
+ findSegmentParamsBlock: () => findSegmentParamsBlock,
1578
+ parseExistingSchemaKeys: () => parseExistingSchemaKeys,
1579
+ runSchemaSync: () => runSchemaSync
1580
+ });
1581
+ function toBracketKey(node) {
1582
+ if (node.paramPrefix || node.paramSuffix) return `[${node.paramName}]`;
1583
+ switch (node.segmentType) {
1584
+ case "catch-all": return `[...${node.paramName}]`;
1585
+ case "optional-catch-all": return `[[...${node.paramName}]]`;
1586
+ default: return `[${node.paramName}]`;
1587
+ }
1588
+ }
1589
+ /**
1590
+ * Collect all unique bracket-keyed dynamic segment names from the route tree.
1591
+ * Returns entries like '[artistSlug]', '[...slug]', '[[...topic]]'.
1592
+ */
1593
+ function collectDynamicSegments(appDir) {
1594
+ const tree = scanRoutes(appDir);
1595
+ const segments = /* @__PURE__ */ new Set();
1596
+ walkSegments(tree.root, segments);
1597
+ return [...segments].sort();
1598
+ }
1599
+ function walkSegments(node, segments) {
1600
+ if (node.paramName) segments.add(toBracketKey(node));
1601
+ for (const child of node.children) walkSegments(child, segments);
1602
+ for (const slot of Object.values(node.slots)) walkSegments(slot, segments);
1603
+ }
1604
+ /**
1605
+ * Replace comment bodies (and optionally string contents) with spaces,
1606
+ * preserving length and newlines so every index maps 1:1 to the original.
1607
+ * Lets the structural scanning below ignore `segmentParams` mentions and
1608
+ * braces inside comments/strings without a TS parser (fine pre-alpha,
1609
+ * see TIM-1066).
1610
+ *
1611
+ * With `maskStrings`, string contents are blanked too — except literal
1612
+ * 'segmentParams' strings, kept so a quoted property key stays findable.
1613
+ */
1614
+ function maskSource(content, maskStrings) {
1615
+ const out = content.split("");
1616
+ const n = content.length;
1617
+ let i = 0;
1618
+ const blank = (from, to) => {
1619
+ for (let j = from; j < to; j++) if (content[j] !== "\n") out[j] = " ";
1620
+ };
1621
+ while (i < n) {
1622
+ const ch = content[i];
1623
+ const next = content[i + 1];
1624
+ if (ch === "/" && next === "/") {
1625
+ const start = i;
1626
+ while (i < n && content[i] !== "\n") i++;
1627
+ blank(start, i);
1628
+ } else if (ch === "/" && next === "*") {
1629
+ const start = i;
1630
+ i += 2;
1631
+ while (i < n && !(content[i] === "*" && content[i + 1] === "/")) i++;
1632
+ i = Math.min(i + 2, n);
1633
+ blank(start, i);
1634
+ } else if (ch === "\"" || ch === "'" || ch === "`") {
1635
+ const start = i;
1636
+ i++;
1637
+ while (i < n && content[i] !== ch) {
1638
+ if (content[i] === "\\") i++;
1639
+ i++;
1640
+ }
1641
+ const end = i;
1642
+ if (maskStrings && content.slice(start + 1, end) !== "segmentParams") blank(start + 1, end);
1643
+ i++;
1644
+ } else i++;
1645
+ }
1646
+ return out.join("");
1647
+ }
1648
+ /**
1649
+ * Locate the `segmentParams: { ... }` block in a schema file.
1650
+ * Returns the indices of the opening and matching closing brace, or null
1651
+ * if no segmentParams property is found. Comments and strings are masked
1652
+ * first, so a JSDoc example mentioning `segmentParams: { ... }` above the
1653
+ * real defineSchema call is not mistaken for the block, and braces inside
1654
+ * comments/strings don't skew the depth count. The search is anchored to
1655
+ * the `defineSchema(` call when present, so helper objects with their own
1656
+ * segmentParams property earlier in the file are skipped.
1657
+ */
1658
+ function findSegmentParamsBlock(content) {
1659
+ const masked = maskSource(content, true);
1660
+ const defineCall = /\bdefineSchema\s*\(/.exec(masked);
1661
+ const keyRe = /(['"]?)segmentParams\1\s*:\s*\{/g;
1662
+ keyRe.lastIndex = defineCall ? defineCall.index + defineCall[0].length : 0;
1663
+ const keyMatch = keyRe.exec(masked);
1664
+ if (!keyMatch) return null;
1665
+ const openBrace = keyMatch.index + keyMatch[0].length - 1;
1666
+ let depth = 1;
1667
+ let i = openBrace + 1;
1668
+ while (i < masked.length && depth > 0) {
1669
+ if (masked[i] === "{") depth++;
1670
+ else if (masked[i] === "}") depth--;
1671
+ i++;
1672
+ }
1673
+ if (depth > 0) return null;
1674
+ return {
1675
+ openBrace,
1676
+ closeBrace: i - 1
1677
+ };
1678
+ }
1679
+ /**
1680
+ * Parse existing bracket keys from an app/schema.ts file.
1681
+ * Scoped to the segmentParams: { ... } block — bracket keys elsewhere in
1682
+ * the file (unrelated objects, comments above defineSchema) are ignored.
1683
+ * Comments inside the block are masked, so a commented-out entry does not
1684
+ * count as registered.
1685
+ *
1686
+ * The key charset matches the route classifier (segment-classify.ts):
1687
+ * any character except `]`, so hyphenated params like '[my-param]' parse.
1688
+ */
1689
+ function parseExistingSchemaKeys(content) {
1690
+ const block = findSegmentParamsBlock(content);
1691
+ if (!block) return [];
1692
+ const blockContent = maskSource(content, false).slice(block.openBrace, block.closeBrace);
1693
+ const keys = [];
1694
+ const re = /['"](\[{1,2}(?:\.{3})?[^\]]+\]{1,2})['"]\s*:/g;
1695
+ let m;
1696
+ while ((m = re.exec(blockContent)) !== null) keys.push(m[1]);
1697
+ return keys;
1698
+ }
1699
+ /** Schema file extensions to check. */
1700
+ var SCHEMA_EXTENSIONS = [
1701
+ ".ts",
1702
+ ".tsx",
1703
+ ".js",
1704
+ ".jsx"
1705
+ ];
1706
+ /**
1707
+ * Find the schema file path if it exists.
1708
+ */
1709
+ function findSchemaFile(appDir) {
1710
+ for (const ext of SCHEMA_EXTENSIONS) {
1711
+ const p = join(appDir, `schema${ext}`);
1712
+ if (existsSync(p)) return p;
1713
+ }
1714
+ }
1715
+ function defaultCodecForSegment(seg) {
1716
+ if (seg.startsWith("[[...")) return "codec.optionalCatchAll(codec.string)";
1717
+ if (seg.startsWith("[...")) return "codec.stringArray";
1718
+ return "codec.string";
1719
+ }
1720
+ /**
1721
+ * Generate the content for a new app/schema.ts with the given segment keys.
1722
+ */
1723
+ function generateNewSchema(segments) {
1724
+ const lines = [];
1725
+ lines.push("import { defineSchema } from '@timber-js/app/params';");
1726
+ lines.push("import { codec } from '@timber-js/app/codec';");
1727
+ lines.push("");
1728
+ lines.push("export default defineSchema({");
1729
+ lines.push(" segmentParams: {");
1730
+ for (const seg of segments) lines.push(` '${seg}': ${defaultCodecForSegment(seg)},`);
1731
+ lines.push(" },");
1732
+ lines.push("});");
1733
+ lines.push("");
1734
+ return lines.join("\n");
1735
+ }
1736
+ /**
1737
+ * Append missing segment entries to an existing schema file.
1738
+ * Inserts new entries before the closing `}` of segmentParams.
1739
+ */
1740
+ var CODEC_IMPORT = "import { codec } from '@timber-js/app/codec';";
1741
+ function hasCodecImport(content) {
1742
+ return /import\s+\{[^}]*\bcodec\b[^}]*\}\s+from\s+['"]@timber-js\/app\/codec['"]/.test(content);
1743
+ }
1744
+ function ensureCodecImport(content) {
1745
+ if (hasCodecImport(content)) return content;
1746
+ const lines = content.split("\n");
1747
+ let lastImportIndex = -1;
1748
+ for (let i = 0; i < lines.length; i++) if (/^\s*import\s/.test(lines[i])) lastImportIndex = i;
1749
+ if (lastImportIndex === -1) return "import { codec } from '@timber-js/app/codec';\n" + content;
1750
+ lines.splice(lastImportIndex + 1, 0, CODEC_IMPORT);
1751
+ return lines.join("\n");
1752
+ }
1753
+ function appendToSchema(content, newSegments) {
1754
+ content = ensureCodecImport(content);
1755
+ const block = findSegmentParamsBlock(content);
1756
+ if (!block) throw new Error("[timber] Could not find segmentParams in schema file. Expected a defineSchema({ segmentParams: { ... } }) call.");
1757
+ const { openBrace, closeBrace } = block;
1758
+ const existingLine = content.slice(openBrace, closeBrace).match(/^(\s+)['"]\[/m);
1759
+ const indent = existingLine ? existingLine[1] : " ";
1760
+ const insertion = newSegments.map((seg) => `${indent}'${seg}': ${defaultCodecForSegment(seg)},`).join("\n");
1761
+ const before = content.slice(0, closeBrace);
1762
+ const after = content.slice(closeBrace);
1763
+ return before + (before.trimEnd().endsWith(",") ? "\n" : "\n") + insertion + "\n" + after;
1764
+ }
1765
+ /**
1766
+ * Remove entries from the segmentParams block whose keys match `staleSegments`.
1767
+ * Removes the entire entry including trailing comma/whitespace. Scoped to
1768
+ * the segmentParams block — identical keys in unrelated objects elsewhere
1769
+ * in the file are left untouched.
1770
+ */
1771
+ function removeFromSchema(content, staleSegments) {
1772
+ const block = findSegmentParamsBlock(content);
1773
+ if (!block) return content;
1774
+ let blockContent = content.slice(block.openBrace, block.closeBrace);
1775
+ let blockMasked = maskSource(blockContent, false);
1776
+ for (const seg of staleSegments) {
1777
+ const escaped = seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1778
+ const keyRe = new RegExp(`^[ \t]*['"]${escaped}['"][ \t]*:`, "gm");
1779
+ let m;
1780
+ while ((m = keyRe.exec(blockMasked)) !== null) {
1781
+ const start = m.index;
1782
+ let i = m.index + m[0].length;
1783
+ let depth = 0;
1784
+ let inString = null;
1785
+ while (i < blockMasked.length) {
1786
+ const ch = blockMasked[i];
1787
+ if (inString) {
1788
+ if (ch === "\\") i++;
1789
+ else if (ch === inString) inString = null;
1790
+ } else if (ch === "\"" || ch === "'" || ch === "`") inString = ch;
1791
+ else if (ch === "(" || ch === "{" || ch === "[") depth++;
1792
+ else if (ch === ")" || ch === "}" || ch === "]") depth--;
1793
+ else if (depth === 0 && ch === ",") {
1794
+ i++;
1795
+ break;
1796
+ } else if (depth === 0 && (ch === "\n" || ch === "}")) break;
1797
+ i++;
1798
+ }
1799
+ if (i < blockMasked.length && blockMasked[i] === "\n") i++;
1800
+ blockContent = blockContent.slice(0, start) + blockContent.slice(i);
1801
+ blockMasked = blockMasked.slice(0, start) + blockMasked.slice(i);
1802
+ keyRe.lastIndex = start;
1803
+ }
1804
+ }
1805
+ return content.slice(0, block.openBrace) + blockContent + content.slice(block.closeBrace);
1806
+ }
1807
+ /**
1808
+ * Run the schema sync: scan filesystem, diff against schema, append missing.
1809
+ */
1810
+ function runSchemaSync(projectRoot) {
1811
+ const appDir = resolveAppDir(projectRoot);
1812
+ const filesystemSegments = collectDynamicSegments(appDir);
1813
+ const schemaPath = findSchemaFile(appDir);
1814
+ if (filesystemSegments.length === 0 && !schemaPath) return {
1815
+ filesystemSegments: [],
1816
+ existingSegments: [],
1817
+ addedSegments: [],
1818
+ removedSegments: [],
1819
+ created: false
1820
+ };
1821
+ if (!schemaPath) {
1822
+ writeFileSync(join(appDir, "schema.ts"), generateNewSchema(filesystemSegments), "utf-8");
1823
+ return {
1824
+ filesystemSegments,
1825
+ existingSegments: [],
1826
+ addedSegments: filesystemSegments,
1827
+ removedSegments: [],
1828
+ created: true
1829
+ };
1830
+ }
1831
+ const content = readFileSync(schemaPath, "utf-8");
1832
+ const existingSegments = parseExistingSchemaKeys(content);
1833
+ const missing = filesystemSegments.filter((seg) => !existingSegments.includes(seg));
1834
+ const stale = existingSegments.filter((seg) => !filesystemSegments.includes(seg));
1835
+ if (missing.length === 0 && stale.length === 0) return {
1836
+ filesystemSegments,
1837
+ existingSegments,
1838
+ addedSegments: [],
1839
+ removedSegments: [],
1840
+ created: false
1841
+ };
1842
+ let updated = content;
1843
+ if (stale.length > 0) updated = removeFromSchema(updated, stale);
1844
+ if (missing.length > 0) updated = appendToSchema(updated, missing);
1845
+ writeFileSync(schemaPath, updated, "utf-8");
1846
+ return {
1847
+ filesystemSegments,
1848
+ existingSegments,
1849
+ addedSegments: missing,
1850
+ removedSegments: stale,
1851
+ created: false
1852
+ };
1853
+ }
1854
+ //#endregion
1855
+ export { collectInterceptionRewrites as a, scanRoutes as i, findSchemaFile as n, matchUrlParts as o, parseExistingSchemaKeys as r, cli_schema_sync_exports as t };
1856
+
1857
+ //# sourceMappingURL=cli-schema-sync-CKgHC2MB.js.map