@rangojs/router 0.0.0-experimental.14 → 0.0.0-experimental.140

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 (460) hide show
  1. package/AGENTS.md +17 -0
  2. package/README.md +432 -7
  3. package/dist/bin/rango.js +2073 -213
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +7258 -2714
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +140 -67
  8. package/skills/api-client/SKILL.md +211 -0
  9. package/skills/breadcrumbs/SKILL.md +329 -0
  10. package/skills/bundle-analysis/SKILL.md +159 -0
  11. package/skills/cache-guide/SKILL.md +487 -0
  12. package/skills/caching/SKILL.md +357 -25
  13. package/skills/comparison/SKILL.md +50 -0
  14. package/skills/comparison/agents/openai.yaml +4 -0
  15. package/skills/comparison/references/framework-comparison.md +837 -0
  16. package/skills/composability/SKILL.md +246 -0
  17. package/skills/css/SKILL.md +76 -0
  18. package/skills/debug-manifest/SKILL.md +16 -10
  19. package/skills/document-cache/SKILL.md +87 -62
  20. package/skills/fonts/SKILL.md +6 -4
  21. package/skills/handler-use/SKILL.md +364 -0
  22. package/skills/hooks/SKILL.md +557 -79
  23. package/skills/host-router/SKILL.md +320 -0
  24. package/skills/i18n/SKILL.md +276 -0
  25. package/skills/intercept/SKILL.md +207 -15
  26. package/skills/layout/SKILL.md +146 -6
  27. package/skills/links/SKILL.md +304 -25
  28. package/skills/loader/SKILL.md +616 -54
  29. package/skills/middleware/SKILL.md +217 -37
  30. package/skills/migrate-nextjs/SKILL.md +611 -0
  31. package/skills/migrate-react-router/SKILL.md +927 -0
  32. package/skills/mime-routes/SKILL.md +42 -11
  33. package/skills/observability/SKILL.md +194 -0
  34. package/skills/parallel/SKILL.md +284 -3
  35. package/skills/ppr/SKILL.md +426 -0
  36. package/skills/prerender/SKILL.md +437 -52
  37. package/skills/rango/SKILL.md +369 -22
  38. package/skills/react-compiler/SKILL.md +168 -0
  39. package/skills/response-routes/SKILL.md +263 -121
  40. package/skills/route/SKILL.md +350 -21
  41. package/skills/router-setup/SKILL.md +246 -33
  42. package/skills/scripts/SKILL.md +179 -0
  43. package/skills/server-actions/SKILL.md +775 -0
  44. package/skills/shell-manifest/SKILL.md +185 -0
  45. package/skills/streams-and-websockets/SKILL.md +283 -0
  46. package/skills/tailwind/SKILL.md +27 -3
  47. package/skills/testing/SKILL.md +126 -222
  48. package/skills/testing/bindings.md +103 -0
  49. package/skills/testing/cache-prerender.md +127 -0
  50. package/skills/testing/client-components.md +124 -0
  51. package/skills/testing/e2e-parity.md +125 -0
  52. package/skills/testing/flight.md +91 -0
  53. package/skills/testing/handles.md +131 -0
  54. package/skills/testing/loader.md +128 -0
  55. package/skills/testing/middleware.md +99 -0
  56. package/skills/testing/render-handler.md +122 -0
  57. package/skills/testing/response-routes.md +95 -0
  58. package/skills/testing/reverse-and-types.md +85 -0
  59. package/skills/testing/server-actions.md +107 -0
  60. package/skills/testing/server-tree.md +128 -0
  61. package/skills/testing/setup.md +123 -0
  62. package/skills/theme/SKILL.md +9 -8
  63. package/skills/typesafety/SKILL.md +532 -103
  64. package/skills/use-cache/SKILL.md +367 -0
  65. package/skills/vercel/SKILL.md +128 -0
  66. package/skills/view-transitions/SKILL.md +337 -0
  67. package/src/__augment-tests__/augment.ts +81 -0
  68. package/src/__augment-tests__/augmented.check.ts +116 -0
  69. package/src/__internal.ts +77 -44
  70. package/src/bin/rango.ts +312 -15
  71. package/src/browser/action-coordinator.ts +114 -0
  72. package/src/browser/action-fence.ts +47 -0
  73. package/src/browser/app-shell.ts +39 -0
  74. package/src/browser/app-version.ts +14 -0
  75. package/src/browser/connection-warmup.ts +134 -0
  76. package/src/browser/cookie-name.ts +140 -0
  77. package/src/browser/event-controller.ts +293 -202
  78. package/src/browser/history-state.ts +101 -0
  79. package/src/browser/index.ts +3 -3
  80. package/src/browser/intercept-utils.ts +52 -0
  81. package/src/browser/invalidate-client-cache.ts +52 -0
  82. package/src/browser/link-interceptor.ts +24 -4
  83. package/src/browser/logging.ts +11 -0
  84. package/src/browser/merge-segment-loaders.ts +20 -12
  85. package/src/browser/navigation-bridge.ts +385 -576
  86. package/src/browser/navigation-client.ts +245 -75
  87. package/src/browser/navigation-store-handle.ts +38 -0
  88. package/src/browser/navigation-store.ts +184 -118
  89. package/src/browser/navigation-transaction.ts +247 -0
  90. package/src/browser/network-error-handler.ts +88 -0
  91. package/src/browser/partial-update.ts +412 -364
  92. package/src/browser/prefetch/cache.ts +359 -0
  93. package/src/browser/prefetch/fetch.ts +452 -0
  94. package/src/browser/prefetch/observer.ts +65 -0
  95. package/src/browser/prefetch/policy.ts +48 -0
  96. package/src/browser/prefetch/queue.ts +209 -0
  97. package/src/browser/prefetch/resource-ready.ts +77 -0
  98. package/src/browser/rango-state.ts +194 -0
  99. package/src/browser/react/Link.tsx +275 -68
  100. package/src/browser/react/NavigationProvider.tsx +265 -109
  101. package/src/browser/react/ScrollRestoration.tsx +10 -6
  102. package/src/browser/react/context.ts +11 -0
  103. package/src/browser/react/filter-segment-order.ts +70 -0
  104. package/src/browser/react/index.ts +0 -48
  105. package/src/browser/react/location-state-shared.ts +272 -60
  106. package/src/browser/react/location-state.ts +90 -20
  107. package/src/browser/react/mount-context.ts +6 -1
  108. package/src/browser/react/nonce-context.ts +23 -0
  109. package/src/browser/react/shallow-equal.ts +27 -0
  110. package/src/browser/react/use-action.ts +35 -66
  111. package/src/browser/react/use-handle.ts +39 -126
  112. package/src/browser/react/use-href.tsx +8 -1
  113. package/src/browser/react/use-link-status.ts +39 -13
  114. package/src/browser/react/use-navigation.ts +53 -69
  115. package/src/browser/react/use-params.ts +75 -0
  116. package/src/browser/react/use-pathname.ts +47 -0
  117. package/src/browser/react/use-reverse.ts +106 -0
  118. package/src/browser/react/use-router.ts +98 -0
  119. package/src/browser/react/use-search-params.ts +51 -0
  120. package/src/browser/react/use-segments.ts +72 -99
  121. package/src/browser/response-adapter.ts +164 -0
  122. package/src/browser/rsc-router.tsx +300 -72
  123. package/src/browser/scroll-restoration.ts +138 -50
  124. package/src/browser/segment-reconciler.ts +243 -0
  125. package/src/browser/segment-structure-assert.ts +17 -1
  126. package/src/browser/server-action-bridge.ts +668 -613
  127. package/src/browser/types.ts +223 -51
  128. package/src/browser/validate-redirect-origin.ts +56 -0
  129. package/src/build/collect-fallback-refs.ts +107 -0
  130. package/src/build/generate-manifest.ts +252 -161
  131. package/src/build/generate-route-types.ts +41 -1038
  132. package/src/build/index.ts +12 -7
  133. package/src/build/prefix-tree-utils.ts +123 -0
  134. package/src/build/route-trie.ts +225 -42
  135. package/src/build/route-types/ast-helpers.ts +25 -0
  136. package/src/build/route-types/ast-route-extraction.ts +105 -0
  137. package/src/build/route-types/codegen.ts +113 -0
  138. package/src/build/route-types/include-resolution.ts +812 -0
  139. package/src/build/route-types/param-extraction.ts +51 -0
  140. package/src/build/route-types/per-module-writer.ts +144 -0
  141. package/src/build/route-types/router-processing.ts +695 -0
  142. package/src/build/route-types/scan-filter.ts +85 -0
  143. package/src/build/route-types/source-scan.ts +216 -0
  144. package/src/build/runtime-discovery.ts +223 -0
  145. package/src/cache/background-task.ts +34 -0
  146. package/src/cache/cache-error.ts +104 -0
  147. package/src/cache/cache-key-utils.ts +60 -0
  148. package/src/cache/cache-policy.ts +199 -0
  149. package/src/cache/cache-runtime.ts +525 -0
  150. package/src/cache/cache-scope.ts +298 -332
  151. package/src/cache/cache-tag.ts +103 -0
  152. package/src/cache/cf/cf-base64.ts +33 -0
  153. package/src/cache/cf/cf-cache-constants.ts +127 -0
  154. package/src/cache/cf/cf-cache-store.ts +2500 -158
  155. package/src/cache/cf/cf-cache-types.ts +349 -0
  156. package/src/cache/cf/cf-kv-utils.ts +46 -0
  157. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  158. package/src/cache/cf/index.ts +17 -17
  159. package/src/cache/document-cache.ts +199 -92
  160. package/src/cache/handle-capture.ts +81 -0
  161. package/src/cache/handle-snapshot.ts +111 -0
  162. package/src/cache/index.ts +29 -35
  163. package/src/cache/memory-segment-store.ts +363 -30
  164. package/src/cache/profile-registry.ts +88 -0
  165. package/src/cache/read-through-swr.ts +178 -0
  166. package/src/cache/segment-codec.ts +248 -0
  167. package/src/cache/shell-cache.ts +386 -0
  168. package/src/cache/tag-invalidation.ts +230 -0
  169. package/src/cache/taint.ts +153 -0
  170. package/src/cache/types.ts +156 -211
  171. package/src/cache/vercel/index.ts +11 -0
  172. package/src/cache/vercel/vercel-cache-store.ts +1102 -0
  173. package/src/client.rsc.tsx +43 -21
  174. package/src/client.tsx +131 -347
  175. package/src/cloudflare/index.ts +11 -0
  176. package/src/cloudflare/tracing.ts +109 -0
  177. package/src/component-utils.ts +23 -4
  178. package/src/components/DefaultDocument.tsx +13 -3
  179. package/src/context-var.ts +168 -0
  180. package/src/debug.ts +19 -9
  181. package/src/decode-loader-results.ts +52 -0
  182. package/src/defer.ts +185 -0
  183. package/src/deps/ssr.ts +0 -1
  184. package/src/encode-kv.ts +49 -0
  185. package/src/errors.ts +106 -10
  186. package/src/escape-script.ts +52 -0
  187. package/src/handle.ts +110 -35
  188. package/src/handles/MetaTags.tsx +83 -59
  189. package/src/handles/Scripts.tsx +183 -0
  190. package/src/handles/breadcrumbs.ts +93 -0
  191. package/src/handles/deferred-resolution.ts +127 -0
  192. package/src/handles/is-thenable.ts +18 -0
  193. package/src/handles/meta.ts +44 -53
  194. package/src/handles/script.ts +244 -0
  195. package/src/host/cookie-handler.ts +20 -65
  196. package/src/host/errors.ts +21 -30
  197. package/src/host/index.ts +13 -9
  198. package/src/host/pattern-matcher.ts +50 -79
  199. package/src/host/router.ts +151 -121
  200. package/src/host/testing.ts +45 -32
  201. package/src/host/types.ts +52 -11
  202. package/src/host/utils.ts +2 -2
  203. package/src/href-client.ts +192 -57
  204. package/src/index.rsc.ts +177 -35
  205. package/src/index.ts +255 -71
  206. package/src/internal-debug.ts +9 -2
  207. package/src/loader-store.ts +500 -0
  208. package/src/loader.rsc.ts +31 -99
  209. package/src/loader.ts +30 -12
  210. package/src/missing-id-error.ts +68 -0
  211. package/src/outlet-context.ts +1 -1
  212. package/src/outlet-provider.tsx +41 -0
  213. package/src/prerender/param-hash.ts +16 -14
  214. package/src/prerender/store.ts +121 -21
  215. package/src/prerender.ts +460 -26
  216. package/src/redirect-origin.ts +100 -0
  217. package/src/regex-escape.ts +8 -0
  218. package/src/render-error-thrower.tsx +20 -0
  219. package/src/response-utils.ts +62 -0
  220. package/src/reverse.ts +198 -128
  221. package/src/root-error-boundary.tsx +42 -48
  222. package/src/route-content-wrapper.tsx +22 -77
  223. package/src/route-definition/dsl-helpers.ts +1116 -0
  224. package/src/route-definition/helper-factories.ts +88 -0
  225. package/src/route-definition/helpers-types.ts +505 -0
  226. package/src/route-definition/index.ts +54 -0
  227. package/src/route-definition/redirect.ts +134 -0
  228. package/src/route-definition/resolve-handler-use.ts +160 -0
  229. package/src/route-definition/use-item-types.ts +29 -0
  230. package/src/route-definition.ts +1 -1481
  231. package/src/route-map-builder.ts +82 -144
  232. package/src/route-name.ts +53 -0
  233. package/src/route-types.ts +71 -45
  234. package/src/router/basename.ts +14 -0
  235. package/src/router/content-negotiation.ts +263 -0
  236. package/src/router/debug-manifest.ts +72 -0
  237. package/src/router/error-handling.ts +54 -27
  238. package/src/router/find-match.ts +245 -0
  239. package/src/router/handler-context.ts +377 -125
  240. package/src/router/instrument.ts +350 -0
  241. package/src/router/intercept-resolution.ts +59 -28
  242. package/src/router/lazy-includes.ts +254 -0
  243. package/src/router/loader-resolution.ts +421 -157
  244. package/src/router/logging.ts +106 -6
  245. package/src/router/manifest.ts +131 -57
  246. package/src/router/match-api.ts +167 -246
  247. package/src/router/match-context.ts +4 -24
  248. package/src/router/match-handlers.ts +440 -0
  249. package/src/router/match-middleware/background-revalidation.ts +117 -93
  250. package/src/router/match-middleware/cache-lookup.ts +297 -150
  251. package/src/router/match-middleware/cache-store.ts +123 -51
  252. package/src/router/match-middleware/intercept-resolution.ts +44 -43
  253. package/src/router/match-middleware/segment-resolution.ts +64 -22
  254. package/src/router/match-pipelines.ts +11 -87
  255. package/src/router/match-result.ts +121 -50
  256. package/src/router/metrics.ts +219 -28
  257. package/src/router/middleware-types.ts +93 -0
  258. package/src/router/middleware.ts +505 -441
  259. package/src/router/navigation-snapshot.ts +133 -0
  260. package/src/router/params-util.ts +23 -0
  261. package/src/router/parse-pattern.ts +115 -0
  262. package/src/router/pattern-matching.ts +311 -142
  263. package/src/router/prefetch-cache-ttl.ts +51 -0
  264. package/src/router/prefetch-limits.ts +37 -0
  265. package/src/router/prerender-match.ts +547 -0
  266. package/src/router/preview-match.ts +102 -0
  267. package/src/router/request-classification.ts +278 -0
  268. package/src/router/revalidation.ts +203 -62
  269. package/src/router/route-snapshot.ts +246 -0
  270. package/src/router/router-context.ts +45 -48
  271. package/src/router/router-interfaces.ts +554 -0
  272. package/src/router/router-options.ts +779 -0
  273. package/src/router/router-registry.ts +21 -0
  274. package/src/router/segment-resolution/fresh.ts +772 -0
  275. package/src/router/segment-resolution/helpers.ts +348 -0
  276. package/src/router/segment-resolution/loader-cache.ts +250 -0
  277. package/src/router/segment-resolution/loader-mask.ts +44 -0
  278. package/src/router/segment-resolution/revalidation.ts +1331 -0
  279. package/src/router/segment-resolution/static-store.ts +81 -0
  280. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  281. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  282. package/src/router/segment-resolution.ts +25 -1354
  283. package/src/router/segment-wrappers.ts +292 -0
  284. package/src/router/state-cookie-name.ts +33 -0
  285. package/src/router/substitute-pattern-params.ts +75 -0
  286. package/src/router/telemetry-otel.ts +261 -0
  287. package/src/router/telemetry.ts +377 -0
  288. package/src/router/timeout.ts +128 -0
  289. package/src/router/tracing.ts +206 -0
  290. package/src/router/trie-matching.ts +240 -61
  291. package/src/router/types.ts +23 -70
  292. package/src/router/url-params.ts +57 -0
  293. package/src/router.ts +781 -2378
  294. package/src/rsc/full-payload.ts +70 -0
  295. package/src/rsc/handler-context.ts +46 -0
  296. package/src/rsc/handler.ts +905 -1142
  297. package/src/rsc/helpers.ts +275 -19
  298. package/src/rsc/index.ts +2 -25
  299. package/src/rsc/json-route-result.ts +38 -0
  300. package/src/rsc/loader-fetch.ts +305 -0
  301. package/src/rsc/manifest-init.ts +77 -0
  302. package/src/rsc/nonce.ts +14 -0
  303. package/src/rsc/origin-guard.ts +155 -0
  304. package/src/rsc/progressive-enhancement.ts +502 -0
  305. package/src/rsc/redirect-guard.ts +99 -0
  306. package/src/rsc/response-cache-serve.ts +238 -0
  307. package/src/rsc/response-error.ts +104 -0
  308. package/src/rsc/response-route-handler.ts +257 -0
  309. package/src/rsc/rsc-rendering.ts +337 -0
  310. package/src/rsc/runtime-warnings.ts +55 -0
  311. package/src/rsc/server-action.ts +522 -0
  312. package/src/rsc/shell-capture.ts +439 -0
  313. package/src/rsc/ssr-setup.ts +144 -0
  314. package/src/rsc/transition-gate.ts +89 -0
  315. package/src/rsc/types.ts +95 -12
  316. package/src/runtime-env.ts +18 -0
  317. package/src/search-params.ts +99 -82
  318. package/src/segment-content-promise.ts +67 -0
  319. package/src/segment-loader-promise.ts +149 -0
  320. package/src/segment-system.tsx +349 -134
  321. package/src/serialize.ts +243 -0
  322. package/src/server/context.ts +452 -85
  323. package/src/server/cookie-parse.ts +32 -0
  324. package/src/server/cookie-store.ts +310 -0
  325. package/src/server/fetchable-loader-store.ts +11 -6
  326. package/src/server/handle-store.ts +123 -42
  327. package/src/server/live.ts +130 -0
  328. package/src/server/loader-registry.ts +51 -100
  329. package/src/server/request-context.ts +842 -157
  330. package/src/server.ts +15 -8
  331. package/src/ssr/index.tsx +412 -136
  332. package/src/ssr/ssr-root.tsx +228 -0
  333. package/src/static-handler.ts +45 -18
  334. package/src/testing/cache-status.ts +162 -0
  335. package/src/testing/collect-handle.ts +46 -0
  336. package/src/testing/dispatch.ts +701 -0
  337. package/src/testing/dom.entry.ts +22 -0
  338. package/src/testing/e2e/fixture.ts +188 -0
  339. package/src/testing/e2e/index.ts +128 -0
  340. package/src/testing/e2e/matchers.ts +35 -0
  341. package/src/testing/e2e/page-helpers.ts +272 -0
  342. package/src/testing/e2e/parity.ts +387 -0
  343. package/src/testing/e2e/server.ts +195 -0
  344. package/src/testing/flight-matchers.ts +97 -0
  345. package/src/testing/flight-normalize.ts +11 -0
  346. package/src/testing/flight-runtime.d.ts +57 -0
  347. package/src/testing/flight-tree.ts +682 -0
  348. package/src/testing/flight.entry.ts +52 -0
  349. package/src/testing/flight.ts +257 -0
  350. package/src/testing/generated-routes.ts +199 -0
  351. package/src/testing/index.ts +105 -0
  352. package/src/testing/internal/context.ts +371 -0
  353. package/src/testing/internal/flight-client-globals.ts +30 -0
  354. package/src/testing/internal/seed-vars.ts +54 -0
  355. package/src/testing/render-handler.ts +357 -0
  356. package/src/testing/render-route.tsx +584 -0
  357. package/src/testing/run-loader.ts +385 -0
  358. package/src/testing/run-middleware.ts +205 -0
  359. package/src/testing/run-transition-when.ts +164 -0
  360. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  361. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  362. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  363. package/src/testing/vitest-stubs/version.ts +5 -0
  364. package/src/testing/vitest.ts +305 -0
  365. package/src/theme/ThemeProvider.tsx +40 -72
  366. package/src/theme/ThemeScript.tsx +12 -14
  367. package/src/theme/constants.ts +57 -15
  368. package/src/theme/index.ts +3 -20
  369. package/src/theme/theme-context.ts +5 -35
  370. package/src/theme/theme-script.ts +43 -39
  371. package/src/theme/use-theme.ts +0 -3
  372. package/src/types/boundaries.ts +123 -0
  373. package/src/types/cache-types.ts +207 -0
  374. package/src/types/error-types.ts +132 -0
  375. package/src/types/global-namespace.ts +113 -0
  376. package/src/types/handler-context.ts +839 -0
  377. package/src/types/index.ts +81 -0
  378. package/src/types/loader-types.ts +212 -0
  379. package/src/types/request-scope.ts +112 -0
  380. package/src/types/route-config.ts +138 -0
  381. package/src/types/route-entry.ts +114 -0
  382. package/src/types/segments.ts +271 -0
  383. package/src/types.ts +1 -1795
  384. package/src/urls/include-helper.ts +162 -0
  385. package/src/urls/include-provider.ts +71 -0
  386. package/src/urls/index.ts +43 -0
  387. package/src/urls/path-helper-types.ts +413 -0
  388. package/src/urls/path-helper.ts +275 -0
  389. package/src/urls/pattern-types.ts +124 -0
  390. package/src/urls/response-types.ts +109 -0
  391. package/src/urls/type-extraction.ts +316 -0
  392. package/src/urls/urls-function.ts +80 -0
  393. package/src/urls.ts +1 -1341
  394. package/src/use-loader.tsx +406 -141
  395. package/src/vercel/index.ts +11 -0
  396. package/src/vercel/tracing.ts +88 -0
  397. package/src/vite/debug.ts +185 -0
  398. package/src/vite/discovery/bundle-postprocess.ts +182 -0
  399. package/src/vite/discovery/discover-routers.ts +389 -0
  400. package/src/vite/discovery/discovery-errors.ts +255 -0
  401. package/src/vite/discovery/gate-state.ts +171 -0
  402. package/src/vite/discovery/prerender-collection.ts +467 -0
  403. package/src/vite/discovery/route-types-writer.ts +214 -0
  404. package/src/vite/discovery/self-gen-tracking.ts +73 -0
  405. package/src/vite/discovery/state.ts +161 -0
  406. package/src/vite/discovery/virtual-module-codegen.ts +183 -0
  407. package/src/vite/index.ts +23 -2255
  408. package/src/vite/inject-client-debug.ts +36 -0
  409. package/src/vite/plugin-types.ts +303 -0
  410. package/src/vite/plugins/cjs-to-esm.ts +90 -0
  411. package/src/vite/plugins/client-ref-dedup.ts +120 -0
  412. package/src/vite/plugins/client-ref-hashing.ts +118 -0
  413. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  414. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  415. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  416. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +88 -110
  417. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +89 -79
  418. package/src/vite/plugins/expose-ids/export-analysis.ts +363 -0
  419. package/src/vite/plugins/expose-ids/handler-transform.ts +130 -0
  420. package/src/vite/plugins/expose-ids/loader-transform.ts +64 -0
  421. package/src/vite/plugins/expose-ids/router-transform.ts +199 -0
  422. package/src/vite/plugins/expose-ids/types.ts +45 -0
  423. package/src/vite/plugins/expose-internal-ids.ts +805 -0
  424. package/src/vite/plugins/performance-tracks.ts +89 -0
  425. package/src/vite/plugins/refresh-cmd.ts +127 -0
  426. package/src/vite/plugins/use-cache-transform.ts +313 -0
  427. package/src/vite/plugins/vercel-output.ts +384 -0
  428. package/src/vite/plugins/version-injector.ts +94 -0
  429. package/src/vite/plugins/version-plugin.ts +263 -0
  430. package/src/vite/plugins/virtual-entries.ts +234 -0
  431. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  432. package/src/vite/rango.ts +560 -0
  433. package/src/vite/router-discovery.ts +1638 -0
  434. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +200 -37
  435. package/src/vite/utils/banner.ts +36 -0
  436. package/src/vite/utils/bundle-analysis.ts +132 -0
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +15 -0
  441. package/src/vite/utils/package-resolution.ts +89 -0
  442. package/src/vite/utils/prerender-utils.ts +249 -0
  443. package/src/vite/utils/shared-utils.ts +269 -0
  444. package/CLAUDE.md +0 -43
  445. package/dist/vite/index.named-routes.gen.ts +0 -103
  446. package/src/browser/lru-cache.ts +0 -69
  447. package/src/browser/react/use-client-cache.ts +0 -56
  448. package/src/browser/request-controller.ts +0 -164
  449. package/src/browser/shallow.ts +0 -35
  450. package/src/cache/memory-store.ts +0 -253
  451. package/src/handles/index.ts +0 -6
  452. package/src/href-context.ts +0 -33
  453. package/src/network-error-thrower.tsx +0 -21
  454. package/src/router.gen.ts +0 -6
  455. package/src/static-handler.gen.ts +0 -5
  456. package/src/urls.gen.ts +0 -8
  457. package/src/vite/expose-internal-ids.ts +0 -1167
  458. package/src/vite/package-resolution.ts +0 -125
  459. package/src/vite/virtual-entries.ts +0 -114
  460. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/router.ts CHANGED
@@ -1,70 +1,43 @@
1
- import type { ComponentType } from "react";
2
1
  import { type ReactNode } from "react";
3
2
  import { createCacheScope } from "./cache/cache-scope.js";
4
- import type { SegmentCacheStore } from "./cache/types.js";
3
+ import { resolveCacheProfiles } from "./cache/profile-registry.js";
4
+ import { isCachedFunction } from "./cache/taint.js";
5
5
  import { assertClientComponent } from "./component-utils.js";
6
6
  import { DefaultDocument } from "./components/DefaultDocument.js";
7
- import {
8
- sanitizeError,
9
- } from "./errors";
10
- import { serializeManifest, type SerializedManifest } from "./debug.js";
11
- import {
12
- createReverse,
13
- type ReverseFunction,
14
- type PrefixRoutePatterns,
15
- } from "./reverse.js";
7
+ import type { SerializedManifest } from "./debug.js";
8
+ import { createReverse, type ReverseFunction } from "./reverse.js";
16
9
  import {
17
10
  registerRouteMap,
18
- getGlobalRouteMap,
19
11
  getPrecomputedEntries,
20
- getRouteTrie,
21
12
  getRouterManifest,
22
- getRouterTrie,
23
13
  getRouterPrecomputedEntries,
24
14
  ensureRouterManifest,
25
15
  } from "./route-map-builder.js";
26
- import { tryTrieMatch } from "./router/trie-matching.js";
27
- import {
28
- createRouteHelpers,
29
- type RouteHandlers,
30
- } from "./route-definition.js";
31
16
  import MapRootLayout from "./server/root-layout.js";
32
- import type { AllUseItems, IncludeItem } from "./route-types.js";
17
+ import type { AllUseItems } from "./route-types.js";
33
18
  import type { UrlPatterns } from "./urls.js";
19
+ import type { UrlBuilder } from "./urls/pattern-types.js";
20
+ import { urls } from "./urls.js";
21
+ import { buildPrecomputedByPrefix } from "./build/prefix-tree-utils.js";
34
22
  import {
35
- EntryData,
36
- InterceptEntry,
37
- InterceptSelectorContext,
23
+ type EntryData,
38
24
  getContext,
39
- RSCRouterContext,
40
- runWithPrefixes,
25
+ RangoContext,
41
26
  type MetricsStore,
42
27
  } from "./server/context";
43
28
  import { createHandleStore, type HandleStore } from "./server/handle-store.js";
44
- import { getRequestContext } from "./server/request-context.js";
29
+ import {
30
+ getRequestContext,
31
+ _getRequestContext,
32
+ } from "./server/request-context.js";
45
33
  import type {
46
- ErrorBoundaryHandler,
47
- ErrorInfo,
48
34
  ErrorPhase,
49
35
  HandlerContext,
50
36
  LoaderDataResult,
51
- MatchResult,
52
- NotFoundBoundaryHandler,
53
- OnErrorCallback,
54
37
  ResolvedRouteMap,
55
- RouteDefinition,
56
38
  RouteEntry,
57
39
  TrailingSlashMode,
58
40
  } from "./types";
59
- import type {
60
- NonceProvider,
61
- } from "./rsc/types.js";
62
- import {
63
- runWithRequestContext,
64
- type RequestContext,
65
- type ExecutionContext,
66
- } from "./server/request-context.js";
67
- import type { SerializedSegmentData, SegmentHandleData } from "./cache/types.js";
68
41
 
69
42
  // Extracted router utilities
70
43
  import {
@@ -74,1072 +47,98 @@ import {
74
47
  invokeOnError,
75
48
  } from "./router/error-handling.js";
76
49
 
77
- // Extracted segment resolution functions
78
- import {
79
- resolveAllSegments as _resolveAllSegments,
80
- resolveLoadersOnly as _resolveLoadersOnly,
81
- resolveLoadersOnlyWithRevalidation as _resolveLoadersOnlyWithRevalidation,
82
- buildEntryRevalidateMap as _buildEntryRevalidateMap,
83
- resolveAllSegmentsWithRevalidation as _resolveAllSegmentsWithRevalidation,
84
- } from "./router/segment-resolution.js";
85
-
86
- // Extracted intercept resolution functions
87
- import {
88
- findInterceptForRoute as _findInterceptForRoute,
89
- resolveInterceptEntry as _resolveInterceptEntry,
90
- resolveInterceptLoadersOnly as _resolveInterceptLoadersOnly,
91
- } from "./router/intercept-resolution.js";
92
-
93
- // Extracted match API functions
94
- import {
95
- createMatchContextForFull as _createMatchContextForFull,
96
- createMatchContextForPartial as _createMatchContextForPartial,
97
- matchError as _matchError,
98
- } from "./router/match-api.js";
50
+ // Extracted module factories
51
+ import { createSegmentWrappers } from "./router/segment-wrappers.js";
52
+ import { createMatchHandlers } from "./router/match-handlers.js";
53
+ import { buildDebugManifest } from "./router/debug-manifest.js";
99
54
 
100
55
  import type { SegmentResolutionDeps, MatchApiDeps } from "./router/types.js";
101
- import { createHandlerContext, createBuildContext } from "./router/handler-context.js";
56
+ import { createHandlerContext } from "./router/handler-context.js";
57
+ import { normalizeBasename } from "./router/basename.js";
102
58
  import {
103
59
  setupLoaderAccess,
104
60
  setupLoaderAccessSilent,
105
- setupBuildUse,
106
61
  wrapLoaderWithErrorHandling,
107
62
  } from "./router/loader-resolution.js";
108
63
  import { loadManifest } from "./router/manifest.js";
64
+ import { createMetricsStore } from "./router/metrics.js";
109
65
  import {
110
- createMetricsStore,
111
- } from "./router/metrics.js";
112
- import {
113
- collectRouteMiddleware,
114
- parsePattern,
66
+ compileMiddlewarePattern,
115
67
  type MiddlewareEntry,
116
68
  type MiddlewareFn,
117
69
  } from "./router/middleware.js";
118
70
  import {
119
71
  extractStaticPrefix,
120
- findMatch as findRouteMatch,
121
- isLazyEvaluationNeeded,
72
+ joinPrefix,
122
73
  traverseBack,
123
- type RouteMatchResult,
124
74
  } from "./router/pattern-matching.js";
75
+ import { resolveSink, safeEmit, getRequestId } from "./router/telemetry.js";
76
+ import { resolveTracing } from "./router/tracing.js";
125
77
  import { evaluateRevalidation } from "./router/revalidation.js";
126
78
  import {
127
79
  type RouterContext,
128
80
  runWithRouterContext,
129
81
  } from "./router/router-context.js";
130
- import {
131
- type ActionContext,
132
- type MatchContext,
133
- createPipelineState,
134
- } from "./router/match-context.js";
135
- import { createMatchPartialPipeline } from "./router/match-pipelines.js";
136
- import { collectMatchResult } from "./router/match-result.js";
137
- import {
138
- runWithRouterLogContext,
139
- withRouterLogScope,
140
- } from "./router/logging.js";
141
82
  import { resolveThemeConfig } from "./theme/constants.js";
83
+ import { resolveTimeouts } from "./router/timeout.js";
142
84
 
143
- // Response type -> MIME type used for Accept header matching
144
- const RESPONSE_TYPE_MIME: Record<string, string> = {
145
- json: "application/json",
146
- text: "text/plain",
147
- xml: "application/xml",
148
- html: "text/html",
149
- md: "text/markdown",
150
- };
151
-
152
- // Reverse lookup: MIME type -> response type tag (e.g. "text/html" -> "html")
153
- const MIME_RESPONSE_TYPE: Record<string, string> = Object.fromEntries(
154
- Object.entries(RESPONSE_TYPE_MIME).map(([tag, mime]) => [mime, tag]),
155
- );
156
-
157
- interface AcceptEntry {
158
- mime: string;
159
- q: number;
160
- order: number;
161
- }
162
-
163
- /**
164
- * Parse an Accept header into a sorted array of MIME entries.
165
- * Respects q-values (default 1.0) and uses client order as tiebreaker
166
- * when q-values are equal (matching Express/Hono behavior).
167
- */
168
- function parseAcceptTypes(accept: string): AcceptEntry[] {
169
- const entries: AcceptEntry[] = [];
170
- const parts = accept.split(",");
171
- for (let i = 0; i < parts.length; i++) {
172
- const part = parts[i]!;
173
- const segments = part.split(";");
174
- const mime = segments[0]!.trim();
175
- if (!mime) continue;
176
- let q = 1.0;
177
- for (let j = 1; j < segments.length; j++) {
178
- const param = segments[j]!.trim();
179
- if (param.startsWith("q=")) {
180
- q = Math.max(0, Math.min(1, Number(param.slice(2)) || 0));
181
- }
182
- }
183
- entries.push({ mime, q, order: i });
184
- }
185
- // Sort: highest q first, then lowest client order first (stable)
186
- entries.sort((a, b) => b.q - a.q || a.order - b.order);
187
- return entries;
188
- }
189
-
190
- // Sentinel response type for RSC routes in negotiation candidates
191
- const RSC_RESPONSE_TYPE = "__rsc__";
192
-
193
- /**
194
- * Pick the best negotiate variant by walking the client's sorted Accept list.
195
- * For each accepted MIME type (in q-value/order priority), check if any
196
- * candidate serves that type. Wildcards (*\/*) match the first candidate.
197
- * Falls back to the first candidate if nothing matches.
198
- */
199
- function pickNegotiateVariant(
200
- acceptEntries: AcceptEntry[],
201
- candidates: Array<{ routeKey: string; responseType: string }>,
202
- ): { routeKey: string; responseType: string } {
203
- // Build a MIME -> candidate lookup for O(1) matching
204
- const byCandidateMime = new Map<string, { routeKey: string; responseType: string }>();
205
- for (const c of candidates) {
206
- const mime = c.responseType === RSC_RESPONSE_TYPE ? "text/html" : RESPONSE_TYPE_MIME[c.responseType];
207
- if (mime && !byCandidateMime.has(mime)) {
208
- byCandidateMime.set(mime, c);
209
- }
210
- }
211
-
212
- for (const entry of acceptEntries) {
213
- if (entry.q === 0) continue;
214
- // Wildcard matches first candidate
215
- if (entry.mime === "*/*") return candidates[0]!;
216
- // Type wildcard (e.g. "text/*") — match first candidate with that type
217
- if (entry.mime.endsWith("/*")) {
218
- const typePrefix = entry.mime.slice(0, entry.mime.indexOf("/"));
219
- for (const [mime, candidate] of byCandidateMime) {
220
- if (mime.startsWith(typePrefix + "/")) return candidate;
221
- }
222
- continue;
223
- }
224
- const match = byCandidateMime.get(entry.mime);
225
- if (match) return match;
226
- }
227
- // No match — use first candidate as default
228
- return candidates[0]!;
229
- }
230
-
231
- /**
232
- * Props passed to the root layout component
233
- */
234
- export interface RootLayoutProps {
235
- children: ReactNode;
236
- }
237
-
238
- /**
239
- * Router configuration options
240
- */
241
- /**
242
- * Brand marker for identifying router instances at build time.
243
- * Used by the Vite plugin to auto-discover routers from module exports.
244
- */
245
- export const RSC_ROUTER_BRAND: "__rsc_router__" = "__rsc_router__";
246
-
247
- /**
248
- * Global registry of all router instances created via createRouter().
249
- * Each router is keyed by its id (auto-generated or user-provided).
250
- * Used by the Vite plugin at build time to discover routers and extract
251
- * manifests, prefix trees, and pre-render candidates.
252
- */
253
- export const RouterRegistry: Map<string, RSCRouter<any, any>> = new Map();
254
-
255
- let routerAutoId = 0;
256
-
257
- export interface RSCRouterOptions<TEnv = any> {
258
- /**
259
- * Unique identifier for this router instance.
260
- * Used to namespace static output files and route maps.
261
- * Auto-generated if not provided.
262
- */
263
- id?: string;
264
-
265
- /**
266
- * Injected by the Vite transform at compile time.
267
- * Hash of filename + line number for stable cross-environment ID.
268
- * @internal
269
- */
270
- $$id?: string;
271
-
272
- /**
273
- * Enable performance metrics collection
274
- * When enabled, metrics are output to console and available via Server-Timing header
275
- */
276
- debugPerformance?: boolean;
277
-
278
- /**
279
- * Allow the `?__debug_manifest` query parameter to return route manifest data as JSON.
280
- * In development mode this is always enabled regardless of this setting.
281
- * Defaults to true. Set to false to disable in production.
282
- * @internal
283
- */
284
- allowDebugManifest?: boolean;
285
-
286
- /**
287
- * Document component that wraps the entire application.
288
- *
289
- * This component provides the HTML structure for your app and wraps
290
- * both normal route content AND error states, preventing the app shell
291
- * from unmounting during errors (avoids FOUC).
292
- *
293
- * Must be a client component ("use client") that accepts { children }.
294
- *
295
- * If not provided, a default document with basic HTML structure is used:
296
- * `<html><head><meta charset/viewport></head><body>{children}</body></html>`
297
- *
298
- * @example
299
- * ```typescript
300
- * // components/Document.tsx
301
- * "use client";
302
- * export function Document({ children }: { children: ReactNode }) {
303
- * return (
304
- * <html lang="en">
305
- * <head>
306
- * <link rel="stylesheet" href="/styles.css" />
307
- * </head>
308
- * <body>
309
- * <nav>...</nav>
310
- * {children}
311
- * </body>
312
- * </html>
313
- * );
314
- * }
315
- *
316
- * // router.tsx
317
- * const router = createRouter<AppEnv>({
318
- * document: Document,
319
- * });
320
- * ```
321
- */
322
- document?: ComponentType<RootLayoutProps>;
323
-
324
- /**
325
- * Default error boundary fallback used when no error boundary is defined in the route tree
326
- * If not provided, errors will propagate and crash the request
327
- */
328
- defaultErrorBoundary?: ReactNode | ErrorBoundaryHandler;
329
-
330
- /**
331
- * Default not-found boundary fallback used when no notFoundBoundary is defined in the route tree
332
- * If not provided, DataNotFoundError will be treated as a regular error
333
- */
334
- defaultNotFoundBoundary?: ReactNode | NotFoundBoundaryHandler;
335
-
336
- /**
337
- * Component to render when no route matches the requested URL.
338
- *
339
- * This is rendered within your document/app shell with a 404 status code.
340
- * Use this for a custom 404 page that maintains your app's look and feel.
341
- *
342
- * If not provided, a default "Page not found" component is rendered.
343
- *
344
- * Can be a static ReactNode or a function receiving the pathname.
345
- *
346
- * @example
347
- * ```typescript
348
- * // Simple static component
349
- * const router = createRouter<AppEnv>({
350
- * document: Document,
351
- * notFound: <NotFound404 />,
352
- * });
353
- *
354
- * // Dynamic component with pathname
355
- * const router = createRouter<AppEnv>({
356
- * document: Document,
357
- * notFound: ({ pathname }) => (
358
- * <div>
359
- * <h1>404 - Not Found</h1>
360
- * <p>No page exists at {pathname}</p>
361
- * <a href="/">Go home</a>
362
- * </div>
363
- * ),
364
- * });
365
- * ```
366
- */
367
- notFound?: ReactNode | ((props: { pathname: string }) => ReactNode);
368
-
369
- /**
370
- * Callback invoked when an error occurs during request handling.
371
- *
372
- * This callback is for notification/logging purposes - it cannot modify
373
- * the error handling flow. Use errorBoundary() in route definitions to
374
- * customize error UI.
375
- *
376
- * The callback receives comprehensive context about the error including:
377
- * - The error itself
378
- * - Phase where it occurred (routing, middleware, loader, handler, etc.)
379
- * - Request info (URL, method, params)
380
- * - Route info (routeKey, segmentId)
381
- * - Environment/bindings
382
- * - Duration from request start
383
- *
384
- * @example
385
- * ```typescript
386
- * const router = createRouter<AppEnv>({
387
- * onError: (context) => {
388
- * // Send to error tracking service
389
- * Sentry.captureException(context.error, {
390
- * tags: {
391
- * phase: context.phase,
392
- * route: context.routeKey,
393
- * },
394
- * extra: {
395
- * url: context.url.toString(),
396
- * params: context.params,
397
- * duration: context.duration,
398
- * },
399
- * });
400
- * },
401
- * });
402
- * ```
403
- */
404
- onError?: OnErrorCallback<TEnv>;
405
-
406
- /**
407
- * Cache store for segment caching.
408
- *
409
- * When provided, enables route-level caching via cache() boundaries.
410
- * The store handles persistence (memory, KV, Redis, etc.).
411
- *
412
- * Can be a static config or a function receiving env for runtime bindings.
413
- *
414
- * @example Static config
415
- * ```typescript
416
- * import { MemorySegmentCacheStore } from "rsc-router/rsc";
417
- *
418
- * const router = createRouter({
419
- * cache: {
420
- * store: new MemorySegmentCacheStore({ defaults: { ttl: 60 } }),
421
- * },
422
- * });
423
- * ```
424
- *
425
- * @example Dynamic config with env (e.g., Cloudflare Workers with ExecutionContext)
426
- * ```typescript
427
- * const router = createRouter<AppEnv>({
428
- * cache: (env) => ({
429
- * store: new CFCacheStore({
430
- * defaults: { ttl: 60 },
431
- * ctx: env.ctx, // ExecutionContext for non-blocking writes
432
- * }),
433
- * }),
434
- * });
435
- * ```
436
- */
437
- cache?:
438
- | { store: SegmentCacheStore; enabled?: boolean }
439
- | ((env: TEnv & { ctx?: ExecutionContext }) => {
440
- store: SegmentCacheStore;
441
- enabled?: boolean;
442
- });
443
-
444
- /**
445
- * Theme configuration for automatic theme management.
446
- *
447
- * When provided, enables:
448
- * - ctx.theme and ctx.setTheme() in route handlers
449
- * - useTheme() hook for client components
450
- * - FOUC prevention via inline script in MetaTags
451
- * - Automatic ThemeProvider wrapping in NavigationProvider
452
- *
453
- * @example
454
- * ```typescript
455
- * const router = createRouter<AppEnv>({
456
- * theme: {
457
- * defaultTheme: "system",
458
- * themes: ["light", "dark"],
459
- * }
460
- * });
461
- *
462
- * // In route handler:
463
- * route("settings", (ctx) => {
464
- * const theme = ctx.theme; // "light" | "dark" | "system"
465
- * ctx.setTheme("dark"); // Sets cookie
466
- * return <SettingsPage />;
467
- * });
468
- *
469
- * // In client component:
470
- * import { useTheme } from "@rangojs/router/theme";
471
- *
472
- * function ThemeToggle() {
473
- * const { theme, setTheme, themes } = useTheme();
474
- * return <select value={theme} onChange={e => setTheme(e.target.value)}>
475
- * {themes.map(t => <option key={t}>{t}</option>)}
476
- * </select>;
477
- * }
478
- * ```
479
- *
480
- * Use `theme: true` to enable with all defaults.
481
- */
482
- theme?: import("./theme/types.js").ThemeConfig | true;
483
-
484
- /**
485
- * URL patterns to register with the router.
486
- *
487
- * Alternative to calling `.routes()` method - allows passing patterns
488
- * directly in the config for a more concise setup.
489
- *
490
- * @example
491
- * ```typescript
492
- * import { urls } from "@rangojs/router/server";
493
- *
494
- * const urlpatterns = urls(({ path, layout }) => [
495
- * path("/", HomePage, { name: "home" }),
496
- * path("/about", AboutPage, { name: "about" }),
497
- * ]);
498
- *
499
- * const router = createRouter<AppEnv>({
500
- * document: Document,
501
- * urls: urlpatterns,
502
- * });
503
- * ```
504
- */
505
- urls?: UrlPatterns<TEnv, any>;
506
-
507
- /**
508
- * Injected by the Vite transform at compile time.
509
- * Static import of NamedRoutes from the generated named-routes file.
510
- * Provides O(1) reverse() fallback when lazy includes haven't resolved.
511
- * @internal
512
- */
513
- $$routeNames?: Record<string, string>;
514
-
515
- /**
516
- * Nonce provider for Content Security Policy (CSP).
517
- *
518
- * Can be:
519
- * - A function that returns a nonce string
520
- * - A function that returns `true` to auto-generate a nonce
521
- * - Undefined to disable nonce (default)
522
- *
523
- * The nonce will be applied to inline scripts injected by the RSC payload.
524
- * It's also available to middleware via `ctx.get('nonce')`.
525
- *
526
- * @example Auto-generate nonce
527
- * ```tsx
528
- * createRouter({
529
- * nonce: () => true,
530
- * });
531
- * ```
532
- *
533
- * @example Custom nonce from request context
534
- * ```tsx
535
- * createRouter({
536
- * nonce: (request, env) => env.nonce,
537
- * });
538
- * ```
539
- */
540
- nonce?: NonceProvider<TEnv>;
541
-
542
- /**
543
- * RSC version string included in metadata.
544
- * The browser sends this back on partial requests to detect version mismatches.
545
- *
546
- * Defaults to the auto-generated VERSION from `@rangojs/router:version` virtual module.
547
- * Only set this if you need a custom versioning strategy.
548
- *
549
- * @default VERSION from @rangojs/router:version
550
- */
551
- version?: string;
552
-
553
- /**
554
- * Enable connection warmup to keep TCP+TLS alive after idle periods.
555
- *
556
- * When enabled, the client sends a HEAD request after the user returns
557
- * from an idle period (60s+), prewarming the TLS connection before
558
- * the next navigation.
559
- *
560
- * @default true
561
- */
562
- warmup?: boolean;
563
- }
564
-
565
- /**
566
- * Merge route patterns with response types into a single route map.
567
- * Routes with response types get { path, response } objects; others stay as strings.
568
- * Handles both plain string routes and { path, search } object routes.
569
- */
570
- type MergeRoutesWithResponses<
571
- TRoutes extends Record<string, unknown>,
572
- TResponses,
573
- > = {
574
- [K in keyof TRoutes]: K extends keyof NonNullable<TResponses>
575
- ? unknown extends NonNullable<TResponses>[K]
576
- ? TRoutes[K] // RSC route — TData defaults to unknown, keep as-is
577
- : TRoutes[K] extends { readonly path: infer P extends string }
578
- ? TRoutes[K] & { readonly response: NonNullable<TResponses>[K] }
579
- : { readonly path: TRoutes[K] & string; readonly response: NonNullable<TResponses>[K] }
580
- : TRoutes[K]
581
- };
582
-
583
- /**
584
- * Extract the URL pattern from a route entry (string or { path, response } object)
585
- */
586
- type PatternOfEntry<V> =
587
- V extends string ? V
588
- : V extends { readonly path: infer P extends string } ? P
589
- : never;
590
-
591
- /**
592
- * Type-level detection of conflicting route keys.
593
- * Extracts keys that exist in both TExisting and TNew but with different URL patterns.
594
- * Returns `never` if no conflicts exist.
595
- * Compares patterns (not full entries) to handle both string and { path, response } values.
596
- *
597
- * @example
598
- * ```typescript
599
- * ConflictingKeys<{ a: "/a" }, { a: "/b" }> // "a" (conflict - same key, different URLs)
600
- * ConflictingKeys<{ a: "/a" }, { a: "/a" }> // never (no conflict - same key and URL)
601
- * ConflictingKeys<{ a: "/a" }, { b: "/b" }> // never (no conflict - different keys)
602
- * ```
603
- */
604
- type ConflictingKeys<
605
- TExisting extends Record<string, unknown>,
606
- TNew extends Record<string, unknown>,
607
- > = {
608
- [K in keyof TExisting & keyof TNew]: PatternOfEntry<TExisting[K]> extends PatternOfEntry<TNew[K]>
609
- ? PatternOfEntry<TNew[K]> extends PatternOfEntry<TExisting[K]>
610
- ? never // Same pattern, no conflict
611
- : K // Different patterns, conflict
612
- : K; // Different patterns, conflict
613
- }[keyof TExisting & keyof TNew];
614
-
615
- /**
616
- * Error type returned when route keys conflict.
617
- * Methods require an impossible `never` parameter so TypeScript errors at the call site.
618
- */
619
- type RouteConflictError<TConflicts extends string> = {
620
- __error: `Route key conflict! Key "${TConflicts}" already exists with a different URL pattern.`;
621
- hint: "Route keys must be globally unique. Use prefixed names like 'blog.index' instead of 'index'.";
622
- conflictingKeys: TConflicts;
623
- // These methods require `never` so calling them produces an error at the call site
624
- routes: (
625
- __conflict: `Fix route key conflict: "${TConflicts}" is already defined with a different URL pattern`,
626
- ) => never;
627
- map: (
628
- __conflict: `Fix route key conflict: "${TConflicts}" is already defined with a different URL pattern`,
629
- ) => never;
630
- };
631
-
632
- /**
633
- * Simplified route helpers for inline route definitions.
634
- * Uses TRoutes (Record<string, string>) instead of RouteDefinition.
635
- *
636
- * Note: Some helpers use `any` for context types as a trade-off for simpler usage.
637
- * The main type safety is in the `route` helper which enforces valid route names.
638
- * For full type safety, use the standard map() API with separate handler files.
639
- */
640
- type InlineRouteHelpers<TRoutes extends Record<string, string>, TEnv> = {
641
- /**
642
- * Define a route handler for a specific route pattern
643
- */
644
- route: <K extends keyof TRoutes & string>(
645
- name: K,
646
- handler:
647
- | ((ctx: HandlerContext<{}, TEnv>) => ReactNode | Promise<ReactNode>)
648
- | ReactNode,
649
- ) => AllUseItems;
650
-
651
- /**
652
- * Define a layout that wraps child routes
653
- */
654
- layout: (
655
- component:
656
- | ReactNode
657
- | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>),
658
- use?: () => AllUseItems[],
659
- ) => AllUseItems;
660
-
661
- /**
662
- * Define parallel routes
663
- */
664
- parallel: (
665
- slots: Record<
666
- `@${string}`,
667
- | ReactNode
668
- | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>)
669
- >,
670
- use?: () => AllUseItems[],
671
- ) => AllUseItems;
672
-
673
- /**
674
- * Define route middleware
675
- */
676
- middleware: (
677
- fn: (ctx: any, next: () => Promise<void>) => Promise<void>,
678
- ) => AllUseItems;
679
-
680
- /**
681
- * Define revalidation handlers
682
- */
683
- revalidate: (fn: (ctx: any) => boolean | Promise<boolean>) => AllUseItems;
684
-
685
- /**
686
- * Define data loaders
687
- */
688
- loader: (loader: any, use?: () => AllUseItems[]) => AllUseItems;
689
-
690
- /**
691
- * Define loading states
692
- */
693
- loading: (component: ReactNode) => AllUseItems;
694
-
695
- /**
696
- * Define error boundaries
697
- */
698
- errorBoundary: (
699
- handler: ReactNode | ((props: { error: Error }) => ReactNode),
700
- ) => AllUseItems;
701
-
702
- /**
703
- * Define not found boundaries
704
- */
705
- notFoundBoundary: (
706
- handler: ReactNode | ((props: { pathname: string }) => ReactNode),
707
- ) => AllUseItems;
708
-
709
- /**
710
- * Define intercept routes
711
- */
712
- intercept: (
713
- name: string,
714
- handler:
715
- | ReactNode
716
- | ((ctx: HandlerContext<any, TEnv>) => ReactNode | Promise<ReactNode>),
717
- use?: () => AllUseItems[],
718
- ) => AllUseItems;
719
-
720
- /**
721
- * Define when conditions for intercepts
722
- */
723
- when: (condition: (ctx: any) => boolean | Promise<boolean>) => AllUseItems;
724
-
725
- /**
726
- * Define cache configuration
727
- */
728
- cache: (
729
- config: { ttl?: number; swr?: number } | false,
730
- use?: () => AllUseItems[],
731
- ) => AllUseItems;
732
- };
733
-
734
- /**
735
- * Router builder for chaining .use() and .map()
736
- * TRoutes accumulates all registered route types through the chain
737
- * TLocalRoutes contains the routes for the current .routes() call (for inline handler typing)
738
- */
739
- interface RouteBuilder<
740
- T extends RouteDefinition,
741
- TEnv,
742
- TRoutes extends Record<string, unknown>,
743
- TLocalRoutes extends Record<string, string> = Record<string, string>,
744
- > {
745
- /**
746
- * Add middleware scoped to this mount
747
- * Called between .routes() and .map()
748
- *
749
- * @example
750
- * ```typescript
751
- * .routes("/admin", adminRoutes)
752
- * .use(authMiddleware) // All of /admin/*
753
- * .use("/danger/*", superAuth) // Only /admin/danger/*
754
- * .map(() => import("./admin"))
755
- * ```
756
- */
757
- use(
758
- patternOrMiddleware: string | MiddlewareFn<TEnv>,
759
- middleware?: MiddlewareFn<TEnv>,
760
- ): RouteBuilder<T, TEnv, TRoutes, TLocalRoutes>;
761
-
762
- /**
763
- * Map routes to handlers
764
- *
765
- * Supports two patterns:
766
- *
767
- * 1. Lazy loading (code-split):
768
- * ```typescript
769
- * .routes(homeRoutes)
770
- * .map(() => import("./handlers/home"))
771
- * ```
772
- *
773
- * 2. Inline definition:
774
- * ```typescript
775
- * .routes({ index: "/", about: "/about" })
776
- * .map(({ route }) => [
777
- * route("index", () => <HomePage />),
778
- * route("about", () => <AboutPage />),
779
- * ])
780
- * ```
781
- */
782
- // Inline definition overload - handler receives helpers (must be first for correct inference)
783
- // Uses TLocalRoutes so route names don't need the prefix
784
- map<
785
- H extends (
786
- helpers: InlineRouteHelpers<TLocalRoutes, TEnv>,
787
- ) => Array<AllUseItems>,
788
- >(
789
- handler: H,
790
- ): RSCRouter<TEnv, TRoutes>;
791
- // Lazy loading overload - verifies imported handlers match route definition
792
- map(
793
- handler: () =>
794
- | Array<AllUseItems>
795
- | Promise<{ default: RouteHandlers<TLocalRoutes> }>
796
- | Promise<RouteHandlers<TLocalRoutes>>,
797
- ): RSCRouter<TEnv, TRoutes>;
798
-
799
- /**
800
- * Accumulated route map for typeof extraction
801
- * Used for module augmentation: `type AppRoutes = typeof _router.routeMap`
802
- */
803
- readonly routeMap: TRoutes;
804
- }
805
-
806
- /**
807
- * RSC Router interface
808
- * TRoutes accumulates all registered route types through the builder chain
809
- */
810
- export interface RSCRouter<
811
- TEnv = any,
812
- TRoutes extends Record<string, unknown> = Record<string, string>,
813
- > {
814
- /**
815
- * Brand marker for build-time discovery.
816
- * The Vite plugin uses this to identify router instances in module exports.
817
- */
818
- readonly __brand: typeof RSC_ROUTER_BRAND;
819
-
820
- /**
821
- * Unique identifier for this router instance.
822
- * Used to namespace static output and isolate route maps between routers.
823
- */
824
- readonly id: string;
825
-
826
- /**
827
- * Register routes with a prefix
828
- * Route keys stay unchanged, only URL patterns get the prefix applied.
829
- * This enables composable route modules that work regardless of mount point.
830
- *
831
- * @throws Compile-time error if route keys conflict with previously registered routes
832
- */
833
- routes<const TPrefix extends string, const T extends Record<string, string>>(
834
- prefix: TPrefix,
835
- routes: T,
836
- ): ConflictingKeys<TRoutes, PrefixRoutePatterns<T, TPrefix>> extends never
837
- ? RouteBuilder<
838
- RouteDefinition,
839
- TEnv,
840
- TRoutes & PrefixRoutePatterns<T, TPrefix>,
841
- T
842
- >
843
- : RouteConflictError<
844
- ConflictingKeys<TRoutes, PrefixRoutePatterns<T, TPrefix>> & string
845
- >;
846
-
847
- /**
848
- * Register routes without a prefix
849
- * Route types are accumulated through the chain
850
- *
851
- * @throws Compile-time error if route keys conflict with previously registered routes
852
- */
853
- routes<const T extends Record<string, string>>(
854
- routes: T,
855
- ): ConflictingKeys<TRoutes, T> extends never
856
- ? RouteBuilder<RouteDefinition, TEnv, TRoutes & T, T>
857
- : RouteConflictError<ConflictingKeys<TRoutes, T> & string>;
858
-
859
- /**
860
- * Register routes using Django-style URL patterns
861
- * This is the new API for @rangojs/router - call once with urls() result
862
- *
863
- * @example
864
- * ```typescript
865
- * createRouter({})
866
- * .routes(urlpatterns) // Single call with urls() result
867
- * ```
868
- */
869
- routes<T extends UrlPatterns<TEnv, any>>(
870
- patterns: T,
871
- ): RSCRouter<
872
- TEnv,
873
- TRoutes &
874
- (NonNullable<T["_routes"]> extends Record<string, unknown>
875
- ? MergeRoutesWithResponses<NonNullable<T["_routes"]>, T["_responses"]>
876
- : Record<string, string>)
877
- >;
878
-
879
- /**
880
- * Add global middleware that runs on all routes
881
- * Position matters: middleware before any .routes() is global
882
- *
883
- * @example
884
- * ```typescript
885
- * createRouter({ document: RootLayout })
886
- * .use(loggerMiddleware) // All routes
887
- * .use("/api/*", rateLimiter) // Pattern match
888
- * .routes(homeRoutes)
889
- * .map(() => import("./home"))
890
- * ```
891
- */
892
- use(
893
- patternOrMiddleware: string | MiddlewareFn<TEnv>,
894
- middleware?: MiddlewareFn<TEnv>,
895
- ): RSCRouter<TEnv, TRoutes>;
896
-
897
- /**
898
- * Type-safe URL builder for registered routes
899
- * Types are inferred from the accumulated route registrations
900
- * Route keys stay unchanged regardless of mount prefix.
901
- *
902
- * @example
903
- * ```typescript
904
- * // Given: .routes("/shop", { cart: "/cart", detail: "/product/:slug" })
905
- * router.reverse("cart"); // "/shop/cart"
906
- * router.reverse("detail", { slug: "widget" }); // "/shop/product/widget"
907
- * ```
908
- */
909
- reverse: ReverseFunction<TRoutes>;
910
-
911
- /**
912
- * Accumulated route map for typeof extraction
913
- * Used for module augmentation: `type AppRoutes = typeof _router.routeMap`
914
- *
915
- * @example
916
- * ```typescript
917
- * const _router = createRouter<AppEnv>()
918
- * .routes(homeRoutes).map(() => import('./home'))
919
- * .routes('/shop', shopRoutes).map(() => import('./shop'));
920
- *
921
- * type AppRoutes = typeof _router.routeMap;
922
- *
923
- * declare global {
924
- * namespace RSCRouter {
925
- * interface RegisteredRoutes extends AppRoutes {}
926
- * }
927
- * }
928
- * ```
929
- */
930
- readonly routeMap: TRoutes;
931
-
932
- /**
933
- * Root layout component that wraps the entire application
934
- * Access this to pass to renderSegments
935
- */
936
- readonly rootLayout?: ComponentType<RootLayoutProps>;
937
-
938
- /**
939
- * Error callback for monitoring/alerting
940
- * Called when errors occur in loaders, actions, or routes
941
- */
942
- readonly onError?: RSCRouterOptions<TEnv>["onError"];
943
-
944
- /**
945
- * Cache configuration (for internal use by RSC handler)
946
- */
947
- readonly cache?: RSCRouterOptions<TEnv>["cache"];
948
-
949
- /**
950
- * Not found component to render when no route matches (for internal use by RSC handler)
951
- */
952
- readonly notFound?: RSCRouterOptions<TEnv>["notFound"];
953
-
954
- /**
955
- * Resolved theme configuration (null if theme not enabled)
956
- * Used by NavigationProvider to include ThemeProvider and by MetaTags to render theme script
957
- */
958
- readonly themeConfig: import("./theme/types.js").ResolvedThemeConfig | null;
959
-
960
- /**
961
- * Whether connection warmup is enabled.
962
- * When true, the client sends HEAD /?_rsc_warmup after idle periods
963
- * and the server responds with 204 No Content.
964
- */
965
- readonly warmupEnabled: boolean;
966
-
967
- /**
968
- * Whether ?__debug_manifest is allowed in production.
969
- * Always enabled in development.
970
- * @internal
971
- */
972
- readonly allowDebugManifest: boolean;
973
-
974
- /**
975
- * App-level middleware entries (for internal use by RSC handler)
976
- * These wrap the entire request/response cycle
977
- */
978
- readonly middleware: MiddlewareEntry<TEnv>[];
979
-
980
- /**
981
- * Nonce provider for CSP (for internal use by createHandler)
982
- */
983
- readonly nonce?: NonceProvider<TEnv>;
984
-
985
- /**
986
- * RSC version string (for internal use by createHandler)
987
- */
988
- readonly version?: string;
989
-
990
- /**
991
- * URL patterns reference for build-time manifest generation
992
- * @internal
993
- */
994
- readonly urlpatterns?: UrlPatterns<TEnv, any>;
85
+ // Extracted content negotiation utilities
86
+ import { flattenNamedRoutes } from "./router/content-negotiation.js";
995
87
 
996
- /**
997
- * Source file path where createRouter() was called.
998
- * Set via Error.stack parsing at construction time.
999
- * Used by the Vite plugin to write per-router named-routes.gen.ts files.
1000
- * @internal
1001
- */
1002
- readonly __sourceFile?: string;
1003
-
1004
- match(request: Request, context: TEnv): Promise<MatchResult>;
1005
-
1006
- /**
1007
- * Build-time pre-render match. Resolves segments with a BuildContext
1008
- * (no request/env/headers/cookies), skipping middleware and loaders.
1009
- * Used by the Vite plugin to collect pre-render data at build time.
1010
- * @internal
1011
- */
1012
- matchForPrerender(
1013
- pathname: string,
1014
- params: Record<string, string>,
1015
- ): Promise<{
1016
- segments: SerializedSegmentData[];
1017
- handles: Record<string, SegmentHandleData>;
1018
- routeName: string;
1019
- params: Record<string, string>;
1020
- } | null>;
1021
-
1022
- /**
1023
- * Preview match - returns route middleware without segment resolution.
1024
- * Also returns responseType and handler for response routes (non-RSC short-circuit).
1025
- */
1026
- previewMatch(
1027
- request: Request,
1028
- context: TEnv,
1029
- ): Promise<{
1030
- routeMiddleware?: Array<{
1031
- handler: import("./router/middleware.js").MiddlewareFn;
1032
- params: Record<string, string>;
1033
- }>;
1034
- responseType?: string;
1035
- handler?: Function;
1036
- params?: Record<string, string>;
1037
- negotiated?: boolean;
1038
- } | null>;
1039
-
1040
- matchPartial(
1041
- request: Request,
1042
- context: TEnv,
1043
- actionContext?: {
1044
- actionId?: string;
1045
- actionUrl?: URL;
1046
- actionResult?: any;
1047
- formData?: FormData;
1048
- },
1049
- ): Promise<MatchResult | null>;
1050
-
1051
- /**
1052
- * Match an error to the nearest error boundary and return error segments
1053
- *
1054
- * Used when an action or other operation fails and we need to render
1055
- * the error boundary UI. Finds the nearest errorBoundary in the route tree
1056
- * for the current URL and renders it with the error info.
1057
- *
1058
- * @param request - The current request (used to match the route)
1059
- * @param context - Environment context
1060
- * @param error - The error that occurred
1061
- * @param segmentType - Type of segment where error occurred (default: "route")
1062
- * @returns MatchResult with error segment, or null if no error boundary found
1063
- */
1064
- matchError(
1065
- request: Request,
1066
- context: TEnv,
1067
- error: unknown,
1068
- segmentType?: ErrorInfo["segmentType"],
1069
- ): Promise<MatchResult | null>;
1070
-
1071
- /**
1072
- * @internal
1073
- * Debug utility to serialize the manifest for inspection
1074
- * Returns a JSON-friendly representation of all routes and layouts
1075
- */
1076
- debugManifest(): Promise<SerializedManifest>;
1077
-
1078
- /**
1079
- * Handle an RSC request.
1080
- *
1081
- * Uses the router's configuration (nonce, version, cache) automatically.
1082
- * The handler is lazily created on first call.
1083
- *
1084
- * @example Cloudflare Workers
1085
- * ```tsx
1086
- * import { router } from "./router";
1087
- *
1088
- * export default { fetch: router.fetch };
1089
- * ```
1090
- *
1091
- * @example Direct export
1092
- * ```tsx
1093
- * const router = createRouter({
1094
- * document: Document,
1095
- * urls: urlpatterns,
1096
- * nonce: () => true,
1097
- * });
1098
- *
1099
- * export const fetch = router.fetch;
1100
- * ```
1101
- */
1102
- fetch(
1103
- request: Request,
1104
- env: TEnv & { ctx?: ExecutionContext },
1105
- ): Promise<Response>;
1106
- }
88
+ // Extracted router types and registry
89
+ import {
90
+ RSC_ROUTER_BRAND,
91
+ RouterRegistry,
92
+ nextRouterAutoId,
93
+ } from "./router/router-registry.js";
94
+ import type { RangoOptions, RootLayoutProps } from "./router/router-options.js";
95
+ import type {
96
+ Rango,
97
+ RangoInternal,
98
+ RouterRequestInput,
99
+ } from "./router/router-interfaces.js";
1107
100
 
1108
- /**
1109
- * Create an RSC router with generic context type
1110
- * Route types are accumulated automatically through the builder chain
1111
- *
1112
- * @example
1113
- * ```typescript
1114
- * interface AppContext {
1115
- * db: Database;
1116
- * user?: User;
1117
- * }
1118
- *
1119
- * const router = createRouter<AppContext>({
1120
- * debugPerformance: true // Enable metrics
1121
- * });
1122
- *
1123
- * // Route types accumulate through the chain - no module augmentation needed!
1124
- * // Keys stay unchanged, only URL patterns get the prefix
1125
- * router
1126
- * .routes(homeRoutes) // accumulates homeRoutes
1127
- * .map(() => import('./home'))
1128
- * .routes('/shop', shopRoutes) // accumulates shopRoutes with prefixed URLs
1129
- * .map(() => import('./shop'));
1130
- *
1131
- * // router.reverse now has type-safe autocomplete for all registered routes
1132
- * // Given shopRoutes = { cart: "/cart" }, reverse uses original key:
1133
- * router.reverse("cart"); // "/shop/cart"
1134
- * ```
1135
- */
101
+ // Extracted closure functions
102
+ import {
103
+ findLazyIncludes,
104
+ evaluateLazyEntry as _evaluateLazyEntry,
105
+ type LazyEvalDeps,
106
+ } from "./router/lazy-includes.js";
107
+ import { createFindMatch } from "./router/find-match.js";
108
+ import {
109
+ matchForPrerender as _matchForPrerender,
110
+ renderStaticSegment as _renderStaticSegment,
111
+ } from "./router/prerender-match.js";
112
+ import { resolveStateCookieName } from "./router/state-cookie-name.js";
113
+ import { resolvePrefetchCacheTTL } from "./router/prefetch-cache-ttl.js";
114
+ import {
115
+ resolvePrefetchCacheSize,
116
+ resolvePrefetchConcurrency,
117
+ } from "./router/prefetch-limits.js";
118
+
119
+ // Re-export public types and values from extracted modules
120
+ export { RSC_ROUTER_BRAND, RouterRegistry } from "./router/router-registry.js";
121
+ export type {
122
+ RangoOptions,
123
+ RootLayoutProps,
124
+ SSRStreamMode,
125
+ SSROptions,
126
+ ResolveStreamingContext,
127
+ } from "./router/router-options.js";
128
+ export type {
129
+ Rango,
130
+ RangoInternal,
131
+ RouterRequestInput,
132
+ } from "./router/router-interfaces.js";
133
+ export { toInternal } from "./router/router-interfaces.js";
1136
134
 
1137
135
  export function createRouter<TEnv = any>(
1138
- options: RSCRouterOptions<TEnv> = {},
1139
- ): RSCRouter<TEnv, {}> {
136
+ options: RangoOptions<TEnv> = {},
137
+ ): Rango<TEnv, {}> {
1140
138
  const {
1141
139
  id: userProvidedId,
1142
140
  $$id: injectedId,
141
+ basename: basenameOption,
1143
142
  debugPerformance = false,
1144
143
  document: documentOption,
1145
144
  defaultErrorBoundary,
@@ -1147,62 +146,163 @@ export function createRouter<TEnv = any>(
1147
146
  notFound,
1148
147
  onError,
1149
148
  cache,
149
+ cacheProfiles: cacheProfilesOption,
1150
150
  theme: themeOption,
1151
151
  urls: urlsOption,
1152
152
  $$routeNames: staticRouteNames,
153
+ $$sourceFile: injectedSourceFile,
1153
154
  nonce,
1154
155
  version,
156
+ prefetchCacheTTL: prefetchCacheTTLOption,
157
+ prefetchCacheSize: prefetchCacheSizeOption,
158
+ prefetchConcurrency: prefetchConcurrencyOption,
159
+ stateCookiePrefix: stateCookiePrefixOption,
1155
160
  warmup: warmupOption,
1156
- allowDebugManifest: allowDebugManifestOption = true,
161
+ allowDebugManifest: allowDebugManifestOption = false,
162
+ telemetry: telemetrySink,
163
+ tracing: tracingOption,
164
+ ssr: ssrOption,
165
+ timeout: timeoutShorthand,
166
+ timeouts: timeoutsOption,
167
+ onTimeout,
168
+ originCheck: originCheckOption,
169
+ viewTransition: viewTransitionOption = "auto",
170
+ debugCacheSignal: debugCacheSignalOption = false,
171
+ strictMode: strictModeOption = true,
1157
172
  } = options;
1158
173
 
1159
- // Capture the source file that called createRouter() via stack trace parsing.
1160
- // Used by the Vite plugin to write per-router named-routes.gen.ts files.
1161
- let __sourceFile: string | undefined;
1162
- try {
1163
- const stack = new Error().stack;
1164
- if (stack) {
1165
- const lines = stack.split("\n");
1166
- for (const line of lines) {
1167
- const match = line.match(/\((.+?\.(ts|tsx|js|jsx)):\d+:\d+\)/);
1168
- if (match && !match[1].endsWith("/router.ts") && !match[1].includes("@rangojs/router") && !match[1].includes("node_modules")) {
1169
- // Strip file: URL protocol prefix from Vite module runner stack traces
1170
- __sourceFile = match[1].startsWith("file:") ? match[1].slice(5) : match[1];
1171
- break;
174
+ // Debug cache signal gate (DEVELOPMENT/TEST ONLY). Enabled by the
175
+ // debugCacheSignal option OR the RANGO_TEST_SIGNALS=1 env flag. When off,
176
+ // no X-Rango-Cache header is emitted and output is byte-identical.
177
+ const cacheSignalEnabled =
178
+ debugCacheSignalOption ||
179
+ (typeof process !== "undefined" &&
180
+ (process as { env?: Record<string, string | undefined> }).env
181
+ ?.RANGO_TEST_SIGNALS === "1");
182
+
183
+ // Normalize basename: ensure leading slash, strip trailing slash.
184
+ // A bare "/" is equivalent to no basename. Shared with the testing
185
+ // primitives via normalizeBasename so they can never drift.
186
+ const basename = normalizeBasename(basenameOption);
187
+
188
+ // Resolve telemetry sink (no-op when not configured)
189
+ const telemetry = resolveSink(telemetrySink);
190
+
191
+ // Resolve span tracing (undefined when not configured; every traceSpan() call
192
+ // is then a direct pass-through with zero behavior change).
193
+ const resolvedTracing = resolveTracing(tracingOption);
194
+
195
+ // Resolve cache profiles: merge user config with the guaranteed default
196
+ // profile. This resolved map is threaded onto each request context; the
197
+ // "use cache: <profile>" runtime path reads it request-scoped.
198
+ const resolvedCacheProfiles = resolveCacheProfiles(cacheProfilesOption);
199
+
200
+ // Source file: prefer Vite-injected path (zero cost), fall back to
201
+ // stack trace parsing for non-Vite environments (e.g. tests).
202
+ let __sourceFile: string | undefined = injectedSourceFile;
203
+ if (!__sourceFile) {
204
+ try {
205
+ const stack = new Error().stack;
206
+ if (stack) {
207
+ const lines = stack.split("\n");
208
+ for (const line of lines) {
209
+ const match = line.match(/\((.+?\.(ts|tsx|js|jsx)):\d+:\d+\)/);
210
+ if (
211
+ match &&
212
+ !match[1].endsWith("/router.ts") &&
213
+ !match[1].includes("@rangojs/router") &&
214
+ !match[1].includes("node_modules")
215
+ ) {
216
+ __sourceFile = match[1].startsWith("file:")
217
+ ? match[1].slice(5)
218
+ : match[1];
219
+ break;
220
+ }
1172
221
  }
1173
222
  }
1174
- }
1175
- } catch {}
223
+ } catch {}
224
+ }
1176
225
 
1177
226
  // Router ID priority: explicit id > Vite-injected $$id > counter fallback.
1178
227
  // $$id is a hash of filename+line injected by the Vite transform at compile
1179
228
  // time, so it's stable across build/runtime regardless of module evaluation
1180
229
  // order (unlike the counter which depends on import order).
1181
- const routerId = userProvidedId ?? injectedId ?? `router_${routerAutoId++}`;
230
+ const routerId =
231
+ userProvidedId ?? injectedId ?? `router_${nextRouterAutoId()}`;
232
+
233
+ // Resolve the rango state cookie name once, here, so the two cookie writers
234
+ // (the client document.cookie writer and the server Set-Cookie writer)
235
+ // consume one pre-composed name and cannot drift.
236
+ const resolvedStateCookieName = resolveStateCookieName(
237
+ stateCookiePrefixOption,
238
+ routerId,
239
+ );
240
+
241
+ // Resolve prefetch cache TTL (default: 300 seconds / 5 minutes). Clamps to a
242
+ // non-negative integer and guards non-finite (NaN/Infinity) inputs so a
243
+ // malformed `Cache-Control: max-age=NaN` can never reach the wire.
244
+ const resolvedPrefetchCacheTTL = resolvePrefetchCacheTTL(
245
+ prefetchCacheTTLOption,
246
+ );
247
+ const prefetchCacheTTL = resolvedPrefetchCacheTTL.ms;
248
+ const prefetchCacheControl: string | false =
249
+ resolvedPrefetchCacheTTL.cacheControl;
250
+
251
+ // Resolve client-side prefetch limits (in-memory cache size and queue
252
+ // concurrency). Both are positive-integer counts; sub-1/non-finite inputs
253
+ // fall back to the defaults. Shipped to the client in payload metadata.
254
+ const prefetchCacheSize = resolvePrefetchCacheSize(prefetchCacheSizeOption);
255
+ const prefetchConcurrency = resolvePrefetchConcurrency(
256
+ prefetchConcurrencyOption,
257
+ );
1182
258
 
1183
259
  // Resolve warmup enabled flag (default: true)
1184
260
  const warmupEnabled = warmupOption !== false;
1185
261
 
262
+ // Resolve StrictMode flag (default: true). Shipped to the client in payload
263
+ // metadata; the browser entry reads it once to decide whether to wrap the
264
+ // hydrated tree in React.StrictMode.
265
+ const strictMode = strictModeOption !== false;
266
+
1186
267
  // Resolve theme config (null if theme not enabled)
1187
268
  const resolvedThemeConfig = themeOption
1188
269
  ? resolveThemeConfig(themeOption)
1189
270
  : null;
1190
271
 
272
+ // Resolve timeout config (merge shorthand + structured)
273
+ const resolvedTimeouts = resolveTimeouts(timeoutShorthand, timeoutsOption);
274
+
1191
275
  /**
1192
276
  * Wrapper for invokeOnError that binds the router's onError callback.
1193
277
  * Uses the shared utility from router/error-handling.ts for consistent behavior.
278
+ *
279
+ * Deduplicates via per-request WeakSet stored on the ALS request context.
280
+ * A closure-level WeakSet would silently swallow errors if the same object
281
+ * instance is thrown across separate requests (e.g. a singleton error).
1194
282
  */
1195
283
  function callOnError(
1196
284
  error: unknown,
1197
285
  phase: ErrorPhase,
1198
286
  context: Parameters<typeof invokeOnError<TEnv>>[3],
1199
287
  ): void {
288
+ if (error != null && typeof error === "object") {
289
+ const reportedErrors = _getRequestContext()?._reportedErrors;
290
+ if (reportedErrors) {
291
+ if (reportedErrors.has(error)) return;
292
+ reportedErrors.add(error);
293
+ }
294
+ }
1200
295
  invokeOnError(onError, error, phase, context, "Router");
1201
296
  }
1202
297
 
1203
- // Validate document is a client component
298
+ // Validate document is a client component. Under a test runner the "use
299
+ // client" transform has not run, so a real exported document has no marker;
300
+ // allowServerInTest lets the router construct in a bare unit test (for
301
+ // dispatch / assertGeneratedRoutesMatch) while a real build still throws.
1204
302
  if (documentOption !== undefined) {
1205
- assertClientComponent(documentOption, "document");
303
+ assertClientComponent(documentOption, "document", {
304
+ allowServerInTest: true,
305
+ });
1206
306
  }
1207
307
 
1208
308
  // Use default document if none provided (keeps internal name as rootLayout)
@@ -1239,6 +339,18 @@ export function createRouter<TEnv = any>(
1239
339
  handler = patternOrMiddleware;
1240
340
  }
1241
341
 
342
+ // Prevent "use cache" functions from being used as middleware.
343
+ // They return data/JSX and do not call next() — silently accepting
344
+ // them would be a confusing no-op.
345
+ if (isCachedFunction(handler)) {
346
+ throw new Error(
347
+ `A "use cache" function cannot be used as middleware. ` +
348
+ `Cached functions return data and do not participate in the ` +
349
+ `middleware chain. Remove the "use cache" directive or use a ` +
350
+ `regular middleware function instead.`,
351
+ );
352
+ }
353
+
1242
354
  // If mount-scoped, prepend mount prefix to pattern
1243
355
  let fullPattern = pattern;
1244
356
  if (mountPrefix && pattern) {
@@ -1254,7 +366,7 @@ export function createRouter<TEnv = any>(
1254
366
  let regex: RegExp | null = null;
1255
367
  let paramNames: string[] = [];
1256
368
  if (fullPattern) {
1257
- const parsed = parsePattern(fullPattern);
369
+ const parsed = compileMiddlewarePattern(fullPattern);
1258
370
  regex = parsed.regex;
1259
371
  paramNames = parsed.paramNames;
1260
372
  }
@@ -1264,836 +376,271 @@ export function createRouter<TEnv = any>(
1264
376
  regex,
1265
377
  paramNames,
1266
378
  handler,
1267
- mountPrefix,
1268
379
  });
1269
380
  }
1270
381
 
1271
- // Track all registered routes with their prefixes for reverse()
1272
- const mergedRouteMap: Record<string, string> = {};
1273
-
1274
- // Lazy precomputed entries lookup: rebuilt when per-router data arrives.
1275
- // In production multi-router setups, per-router data is loaded lazily via
1276
- // ensureRouterManifest(). At createRouter() time the data isn't available yet,
1277
- // so we defer building the Map until first use and invalidate when the
1278
- // per-router source changes.
1279
- let precomputedByPrefix: Map<string, Record<string, string>> | null = null;
1280
- let precomputedSource: Array<{ staticPrefix: string; routes: Record<string, string> }> | null | undefined;
1281
-
1282
- function getPrecomputedByPrefix(): Map<string, Record<string, string>> | null {
1283
- const current = getRouterPrecomputedEntries(routerId) ?? getPrecomputedEntries();
1284
- if (current !== precomputedSource) {
1285
- precomputedSource = current;
1286
- precomputedByPrefix = current
1287
- ? new Map(current.map((e) => [e.staticPrefix, e.routes]))
1288
- : null;
1289
- }
1290
- return precomputedByPrefix;
1291
- }
1292
-
1293
-
1294
- // Wrapper to pass debugPerformance to external createMetricsStore
1295
- const getMetricsStore = () => createMetricsStore(debugPerformance);
1296
-
1297
- // Wrapper to pass defaults to error/notFound boundary finders
1298
- const findNearestErrorBoundary = (entry: EntryData | null) =>
1299
- findErrorBoundary(entry, defaultErrorBoundary);
1300
-
1301
- const findNearestNotFoundBoundary = (entry: EntryData | null) =>
1302
- findNotFoundBoundary(entry, defaultNotFoundBoundary);
1303
-
1304
- // Helper to get handleStore from request context
1305
- const getHandleStore = (): HandleStore | undefined => {
1306
- return getRequestContext()?._handleStore;
1307
- };
1308
-
1309
- // Track a pending handler promise (non-blocking)
1310
- const trackHandler = <T>(promise: Promise<T>): Promise<T> => {
1311
- const store = getHandleStore();
1312
- return store ? store.track(promise) : promise;
1313
- };
1314
-
1315
- // Wrapper for wrapLoaderWithErrorHandling that uses router's error boundary finder
1316
- // Includes onError callback for loader error notification
1317
- function wrapLoaderPromise<T>(
1318
- promise: Promise<T>,
1319
- entry: EntryData,
1320
- segmentId: string,
1321
- pathname: string,
1322
- errorContext?: {
1323
- request: Request;
1324
- url: URL;
1325
- routeKey?: string;
1326
- params?: Record<string, string>;
1327
- env?: TEnv;
1328
- isPartial?: boolean;
1329
- requestStartTime?: number;
1330
- },
1331
- ): Promise<LoaderDataResult<T>> {
1332
- return wrapLoaderWithErrorHandling(
1333
- promise,
1334
- entry,
1335
- segmentId,
1336
- pathname,
1337
- findNearestErrorBoundary,
1338
- createErrorInfo,
1339
- // Invoke onError when loader fails
1340
- errorContext
1341
- ? (error, ctx) => {
1342
- callOnError(error, "loader", {
1343
- request: errorContext.request,
1344
- url: errorContext.url,
1345
- routeKey: errorContext.routeKey,
1346
- params: errorContext.params,
1347
- segmentId: ctx.segmentId,
1348
- segmentType: "loader",
1349
- loaderName: ctx.loaderName,
1350
- env: errorContext.env,
1351
- isPartial: errorContext.isPartial,
1352
- handledByBoundary: ctx.handledByBoundary,
1353
- requestStartTime: errorContext.requestStartTime,
1354
- });
1355
- }
1356
- : undefined,
1357
- );
1358
- }
1359
-
1360
- // Dependencies object for extracted segment resolution functions.
1361
- // Captures closure-bound helpers from createRouter.
1362
- const segmentDeps: SegmentResolutionDeps<TEnv> = {
1363
- wrapLoaderPromise,
1364
- trackHandler,
1365
- findNearestErrorBoundary,
1366
- findNearestNotFoundBoundary,
1367
- callOnError,
1368
- };
1369
-
1370
- // Match API dependencies
1371
- const matchApiDeps: MatchApiDeps<TEnv> = {
1372
- findMatch: (pathname: string, ms?: any) => findMatch(pathname, ms),
1373
- getMetricsStore,
1374
- findInterceptForRoute: (routeKey, parentEntry, selectorContext, isAction) =>
1375
- findInterceptForRoute(routeKey, parentEntry, selectorContext, isAction),
1376
- callOnError,
1377
- findNearestErrorBoundary,
1378
- getRouteMap: () => getRouterManifest(routerId) ?? getGlobalRouteMap(),
1379
- };
1380
-
1381
- // Thin wrappers that bind the deps to extracted functions.
1382
- // These maintain the same signatures as the original inline functions
1383
- // so that RouterContext and call sites don't need to change.
1384
-
1385
- function resolveAllSegments(
1386
- entries: EntryData[],
1387
- routeKey: string,
1388
- params: Record<string, string>,
1389
- context: HandlerContext<any, TEnv>,
1390
- loaderPromises: Map<string, Promise<any>>,
1391
- options?: { skipLoaders?: boolean },
1392
- ) {
1393
- return _resolveAllSegments(entries, routeKey, params, context, loaderPromises, segmentDeps, options);
1394
- }
1395
-
1396
- function resolveLoadersOnly(
1397
- entries: EntryData[],
1398
- context: HandlerContext<any, TEnv>,
1399
- ) {
1400
- return _resolveLoadersOnly(entries, context, segmentDeps);
1401
- }
1402
-
1403
- function resolveLoadersOnlyWithRevalidation(
1404
- entries: EntryData[],
1405
- context: HandlerContext<any, TEnv>,
1406
- clientSegmentIds: Set<string>,
1407
- prevParams: Record<string, string>,
1408
- request: Request,
1409
- prevUrl: URL,
1410
- nextUrl: URL,
1411
- routeKey: string,
1412
- actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
1413
- ) {
1414
- return _resolveLoadersOnlyWithRevalidation(
1415
- entries, context, clientSegmentIds, prevParams, request,
1416
- prevUrl, nextUrl, routeKey, segmentDeps, actionContext,
1417
- );
1418
- }
1419
-
1420
- function buildEntryRevalidateMap(entries: EntryData[]) {
1421
- return _buildEntryRevalidateMap(entries);
1422
- }
1423
-
1424
- function resolveAllSegmentsWithRevalidation(
1425
- entries: EntryData[],
1426
- routeKey: string,
1427
- params: Record<string, string>,
1428
- context: HandlerContext<any, TEnv>,
1429
- clientSegmentSet: Set<string>,
1430
- prevParams: Record<string, string>,
1431
- request: Request,
1432
- prevUrl: URL,
1433
- nextUrl: URL,
1434
- loaderPromises: Map<string, Promise<any>>,
1435
- actionContext: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData } | undefined,
1436
- interceptResult: { intercept: InterceptEntry; entry: EntryData } | null,
1437
- localRouteName: string,
1438
- pathname: string,
1439
- ) {
1440
- return _resolveAllSegmentsWithRevalidation(
1441
- entries, routeKey, params, context, clientSegmentSet, prevParams, request,
1442
- prevUrl, nextUrl, loaderPromises, actionContext, interceptResult,
1443
- localRouteName, pathname, segmentDeps,
1444
- );
1445
- }
1446
-
1447
- function findInterceptForRoute(
1448
- targetRouteKey: string,
1449
- fromEntry: EntryData | null,
1450
- selectorContext: InterceptSelectorContext | null = null,
1451
- isAction: boolean = false,
1452
- ) {
1453
- return _findInterceptForRoute(targetRouteKey, fromEntry, selectorContext, isAction);
1454
- }
1455
-
1456
- function resolveInterceptEntry(
1457
- interceptEntry: InterceptEntry,
1458
- parentEntry: EntryData,
1459
- params: Record<string, string>,
1460
- context: HandlerContext<any, TEnv>,
1461
- belongsToRoute: boolean = true,
1462
- revalidationContext?: any,
1463
- ) {
1464
- return _resolveInterceptEntry(
1465
- interceptEntry, parentEntry, params, context, belongsToRoute,
1466
- segmentDeps, revalidationContext,
1467
- );
1468
- }
1469
-
1470
- function resolveInterceptLoadersOnly(
1471
- interceptEntry: InterceptEntry,
1472
- parentEntry: EntryData,
1473
- params: Record<string, string>,
1474
- context: HandlerContext<any, TEnv>,
1475
- belongsToRoute: boolean = true,
1476
- revalidationContext: any,
1477
- ) {
1478
- return _resolveInterceptLoadersOnly(
1479
- interceptEntry, parentEntry, params, context, belongsToRoute,
1480
- segmentDeps, revalidationContext,
1481
- );
1482
- }
1483
-
1484
- // Detect lazy includes in handler result and create placeholder entries
1485
- // Lazy includes are IncludeItem with lazy: true and _lazyContext
1486
- // Moved to outer scope so it can be reused by evaluateLazyEntry for nested includes
1487
- function findLazyIncludes(items: AllUseItems[]): Array<{
1488
- prefix: string;
1489
- patterns: UrlPatterns<TEnv>;
1490
- context: {
1491
- urlPrefix: string;
1492
- namePrefix: string | undefined;
1493
- parent: unknown;
1494
- };
1495
- }> {
1496
- const lazyItems: Array<{
1497
- prefix: string;
1498
- patterns: UrlPatterns<TEnv>;
1499
- context: {
1500
- urlPrefix: string;
1501
- namePrefix: string | undefined;
1502
- parent: unknown;
1503
- };
1504
- }> = [];
1505
-
1506
- for (const item of items) {
1507
- if (!item) continue;
1508
- if (item.type === "include") {
1509
- const includeItem = item as IncludeItem;
1510
- if (includeItem.lazy === true && includeItem._lazyContext) {
1511
- lazyItems.push({
1512
- prefix: includeItem.prefix,
1513
- patterns: includeItem.patterns as UrlPatterns<TEnv>,
1514
- context: includeItem._lazyContext,
1515
- });
1516
- }
1517
- }
1518
- // Recursively check nested items (in layouts, etc.)
1519
- if ((item as any).uses && Array.isArray((item as any).uses)) {
1520
- lazyItems.push(...findLazyIncludes((item as any).uses));
1521
- }
1522
- }
1523
-
1524
- return lazyItems;
1525
- }
1526
-
1527
- /**
1528
- * Evaluate a lazy entry's patterns and populate its routes
1529
- * This runs the lazy patterns handler and updates the entry in-place
1530
- * Also detects nested lazy includes and registers them as new entries
1531
- */
1532
- function evaluateLazyEntry(entry: RouteEntry<TEnv>): void {
1533
- if (!entry.lazy || entry.lazyEvaluated || !entry.lazyPatterns) {
1534
- return;
1535
- }
1536
-
1537
- // Check for pre-computed routes from build-time data.
1538
- // Only leaf nodes (no nested includes) are precomputed, so entries with
1539
- // nested lazy includes fall through to the handler below.
1540
- // When multiple entries share the same staticPrefix (e.g., several
1541
- // include("/", ...) calls), the precomputed data merges all their routes
1542
- // into one entry. Assigning that merged set to the first matching entry
1543
- // causes findMatch to pick the wrong handler for routes belonging to a
1544
- // different include. Skip the shortcut when the prefix is shared.
1545
- const currentPrecomputed = getPrecomputedByPrefix();
1546
- if (currentPrecomputed) {
1547
- const routes = currentPrecomputed.get(entry.staticPrefix);
1548
- if (routes) {
1549
- const prefixIsShared = routesEntries.filter(
1550
- (e) => e.staticPrefix === entry.staticPrefix,
1551
- ).length > 1;
1552
- if (!prefixIsShared) {
1553
- entry.lazyEvaluated = true;
1554
- entry.routes = routes as ResolvedRouteMap<any>;
1555
- for (const [name, pattern] of Object.entries(routes)) {
1556
- mergedRouteMap[name] = pattern;
1557
- }
1558
- registerRouteMap(mergedRouteMap);
1559
- return;
1560
- }
1561
- }
1562
- }
1563
-
1564
- // Mark as evaluated immediately to prevent concurrent evaluation.
1565
- // JS is single-threaded but handlers.handler() could theoretically yield,
1566
- // and the while-loop in findMatch retries after evaluation.
1567
- entry.lazyEvaluated = true;
1568
-
1569
- const lazyPatterns = entry.lazyPatterns as UrlPatterns<TEnv>;
1570
- const lazyContext = entry.lazyContext;
1571
-
1572
- // Create a new context for evaluating the lazy patterns
1573
- const manifest = new Map<string, EntryData>();
1574
- const patterns = new Map<string, string>();
1575
- const patternsByPrefix = new Map<string, Map<string, string>>();
1576
- const trailingSlashMap = new Map<string, TrailingSlashMode>();
1577
-
1578
- // Capture the handler result to detect nested lazy includes
1579
- let handlerResult: AllUseItems[] = [];
1580
-
1581
- // Merge captured counters from include() to maintain consistent
1582
- // shortCode indices with sibling entries from pattern extraction
1583
- const lazyCounters: Record<string, number> = {};
1584
- if (lazyContext && (lazyContext as any).counters) {
1585
- const captured = (lazyContext as any).counters as Record<string, number>;
1586
- for (const [key, value] of Object.entries(captured)) {
1587
- lazyCounters[key] = value;
1588
- }
1589
- }
1590
-
1591
- RSCRouterContext.run(
1592
- {
1593
- manifest,
1594
- patterns,
1595
- patternsByPrefix,
1596
- trailingSlash: trailingSlashMap,
1597
- namespace: "lazy",
1598
- parent: (lazyContext?.parent as EntryData | null) ?? null,
1599
- counters: lazyCounters,
1600
- },
1601
- () => {
1602
- // Run the lazy patterns handler with the original context prefixes
1603
- // The prefix comes from the IncludeItem stored in lazyPatterns
1604
- const includePrefix = (entry as any)._lazyPrefix || "";
1605
- const fullPrefix = (lazyContext?.urlPrefix || "") + includePrefix;
1606
-
1607
- if (fullPrefix || lazyContext?.namePrefix) {
1608
- runWithPrefixes(fullPrefix, lazyContext?.namePrefix, () => {
1609
- handlerResult = lazyPatterns.handler() as AllUseItems[];
1610
- });
1611
- } else {
1612
- handlerResult = lazyPatterns.handler() as AllUseItems[];
1613
- }
1614
- },
1615
- );
1616
-
1617
- // Populate the entry's routes from the patterns
1618
- const routesObject: Record<string, string> = {};
1619
- for (const [name, pattern] of patterns.entries()) {
1620
- routesObject[name] = pattern;
1621
- // Also add to merged route map for reverse() support
1622
- const existingPattern = mergedRouteMap[name];
1623
- if (existingPattern !== undefined && existingPattern !== pattern) {
1624
- console.warn(
1625
- `[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
1626
- `overwriting with "${pattern}" (from lazy include). Use unique route names to avoid this.`,
1627
- );
1628
- }
1629
- mergedRouteMap[name] = pattern;
1630
- }
1631
-
1632
- // Update the entry in-place
1633
- entry.routes = routesObject as ResolvedRouteMap<any>;
1634
-
1635
- // Note: Do NOT clear lazyPatterns/lazyContext here.
1636
- // loadManifest() needs them on every request to re-run the handler
1637
- // in the correct AsyncLocalStorage context (Store.manifest).
1638
-
1639
- // Update trailing slash config if available
1640
- if (trailingSlashMap.size > 0) {
1641
- entry.trailingSlash = Object.fromEntries(trailingSlashMap);
1642
- }
1643
-
1644
- // Detect nested lazy includes and register them as new entries
1645
- const nestedLazyIncludes = findLazyIncludes(handlerResult);
1646
- for (const lazyInclude of nestedLazyIncludes) {
1647
- // Compute the full URL prefix (combining parent prefix if any)
1648
- const fullPrefix = lazyInclude.context.urlPrefix
1649
- ? lazyInclude.context.urlPrefix + lazyInclude.prefix
1650
- : lazyInclude.prefix;
1651
-
1652
- const nestedEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
1653
- prefix: "",
1654
- staticPrefix: extractStaticPrefix(fullPrefix),
1655
- routes: {} as ResolvedRouteMap<any>, // Empty until first match
1656
- trailingSlash: entry.trailingSlash,
1657
- handler: (lazyInclude.patterns as UrlPatterns<TEnv>).handler,
1658
- mountIndex: entry.mountIndex,
1659
- // Lazy evaluation fields
1660
- lazy: true,
1661
- lazyPatterns: lazyInclude.patterns,
1662
- lazyContext: lazyInclude.context,
1663
- lazyEvaluated: false,
1664
- // Store the include prefix for evaluation
1665
- _lazyPrefix: lazyInclude.prefix,
1666
- };
1667
- // Insert nested lazy entry before any entry whose staticPrefix is a
1668
- // prefix of (but shorter than) this lazy entry's staticPrefix.
1669
- // This ensures more specific lazy includes are matched before
1670
- // less specific eager entries (e.g., "/href/nested" before "/href/:id").
1671
- const nestedPrefix = nestedEntry.staticPrefix;
1672
- let insertIndex = routesEntries.length;
1673
- if (nestedPrefix) {
1674
- for (let i = 0; i < routesEntries.length; i++) {
1675
- const existing = routesEntries[i]!;
1676
- if (
1677
- nestedPrefix.startsWith(existing.staticPrefix) &&
1678
- nestedPrefix.length > existing.staticPrefix.length
1679
- ) {
1680
- insertIndex = i;
1681
- break;
1682
- }
1683
- }
1684
- }
1685
- routesEntries.splice(insertIndex, 0, nestedEntry);
1686
- }
1687
-
1688
- // Re-register route map for runtime reverse() usage
1689
- registerRouteMap(mergedRouteMap);
1690
- }
1691
-
1692
- // Single-entry cache for findMatch to avoid redundant matching within the same request.
1693
- // previewMatch and match both call findMatch with the same pathname — this ensures
1694
- // the route matching work (which may check thousands of routes) only happens once.
1695
- let lastFindMatchPathname: string | null = null;
1696
- let lastFindMatchResult: RouteMatchResult<TEnv> | null = null;
1697
-
1698
- // Wrapper for findMatch that uses routesEntries
1699
- // Handles lazy evaluation by evaluating lazy entries on first match.
1700
- // Phase 1: try O(path_length) trie match.
1701
- // Phase 2: fall back to regex iteration.
1702
- function findMatch(
1703
- pathname: string,
1704
- ms?: MetricsStore,
1705
- ): RouteMatchResult<TEnv> | null {
1706
- // Return cached result if same pathname (avoids double-match per request)
1707
- if (lastFindMatchPathname === pathname) {
1708
- return lastFindMatchResult;
1709
- }
1710
-
1711
- // Helper to push sub-metrics
1712
- const pushMetric = ms
1713
- ? (label: string, start: number) => {
1714
- ms.metrics.push({
1715
- label,
1716
- duration: performance.now() - start,
1717
- startTime: start - ms.requestStart,
1718
- });
1719
- }
1720
- : undefined;
1721
-
1722
- // Phase 1: Try trie match (O(path_length))
1723
- // Prefer per-router trie (isolated) over global trie (merged).
1724
- const routeTrie = getRouterTrie(routerId) ?? getRouteTrie();
1725
- if (routeTrie) {
1726
- const trieStart = performance.now();
1727
- const trieResult = tryTrieMatch(routeTrie, pathname);
1728
- pushMetric?.("match:trie", trieStart);
1729
-
1730
- if (trieResult) {
1731
- // Find the RouteEntry that contains this route.
1732
- // Multiple entries can share the same staticPrefix (e.g., several
1733
- // include("/", patterns) calls all produce staticPrefix=""). Evaluate
1734
- // each candidate and pick the one whose routes include the matched key.
1735
- const entryStart = performance.now();
1736
- let entry: RouteEntry<TEnv> | undefined;
1737
- let fallbackEntry: RouteEntry<TEnv> | undefined;
1738
-
1739
- for (const e of routesEntries) {
1740
- if (e.staticPrefix !== trieResult.sp) continue;
1741
- if (!fallbackEntry) fallbackEntry = e;
1742
- evaluateLazyEntry(e);
1743
- if (
1744
- e.routes &&
1745
- trieResult.routeKey in (e.routes as Record<string, unknown>)
1746
- ) {
1747
- entry = e;
1748
- break;
1749
- }
1750
- }
1751
-
1752
- // If no entry had the route in its routes map, use the first matching
1753
- // entry as fallback (handles main entry with inline routes not yet
1754
- // reflected in its routes object).
1755
- if (!entry) entry = fallbackEntry;
1756
-
1757
- // If entry not found (nested include not yet discovered), evaluate parent
1758
- if (!entry) {
1759
- const parent = routesEntries.find(
1760
- (e) =>
1761
- trieResult.sp.startsWith(e.staticPrefix) &&
1762
- e.staticPrefix !== trieResult.sp,
1763
- );
1764
- if (parent) {
1765
- const lazyStart = performance.now();
1766
- evaluateLazyEntry(parent);
1767
- pushMetric?.("match:lazy-eval", lazyStart);
1768
- }
1769
- entry = routesEntries.find((e) => e.staticPrefix === trieResult.sp);
1770
- }
1771
- pushMetric?.("match:entry-resolve", entryStart);
1772
-
1773
- if (entry) {
1774
- lastFindMatchPathname = pathname;
1775
- lastFindMatchResult = {
1776
- entry,
1777
- routeKey: trieResult.routeKey,
1778
- params: trieResult.params,
1779
- optionalParams: new Set(trieResult.optionalParams || []),
1780
- redirectTo: trieResult.redirectTo,
1781
- ancestry: trieResult.ancestry,
1782
- ...(trieResult.pr ? { pr: true } : {}),
1783
- ...(trieResult.pt ? { pt: true } : {}),
1784
- ...(trieResult.responseType ? { responseType: trieResult.responseType } : {}),
1785
- ...(trieResult.negotiateVariants ? { negotiateVariants: trieResult.negotiateVariants } : {}),
1786
- ...(trieResult.rscFirst ? { rscFirst: true } : {}),
1787
- };
1788
- return lastFindMatchResult;
1789
- }
1790
- }
1791
- }
1792
-
1793
- // Phase 2: Fall back to existing matching (regex iteration)
1794
- const regexStart = performance.now();
1795
- let result = findRouteMatch(pathname, routesEntries);
1796
-
1797
- // If we hit a lazy entry that needs evaluation, evaluate and retry.
1798
- // Cap iterations to prevent infinite loops from pathological nesting.
1799
- const MAX_LAZY_ITERATIONS = 100;
1800
- let iterations = 0;
1801
- while (isLazyEvaluationNeeded(result)) {
1802
- if (++iterations > MAX_LAZY_ITERATIONS) {
1803
- console.error(
1804
- `[@rangojs/router] Exceeded ${MAX_LAZY_ITERATIONS} lazy evaluation iterations ` +
1805
- `for pathname "${pathname}". This likely indicates circular lazy includes.`,
1806
- );
1807
- lastFindMatchPathname = pathname;
1808
- lastFindMatchResult = null;
1809
- return null;
1810
- }
1811
- evaluateLazyEntry(result.lazyEntry);
1812
- result = findRouteMatch(pathname, routesEntries);
1813
- }
1814
- pushMetric?.("match:regex-fallback", regexStart);
1815
-
1816
- lastFindMatchPathname = pathname;
1817
- lastFindMatchResult = result;
1818
- return result;
1819
- }
1820
-
1821
-
1822
- /**
1823
- * Build-time pre-render match. Resolves segments with a BuildContext
1824
- * (no request/env/headers/cookies), skipping middleware and loaders.
1825
- */
1826
- async function matchForPrerender(
1827
- pathname: string,
1828
- params: Record<string, string>,
1829
- ): Promise<{
1830
- segments: SerializedSegmentData[];
1831
- handles: Record<string, SegmentHandleData>;
1832
- routeName: string;
1833
- params: Record<string, string>;
1834
- } | null> {
1835
- // 1. Find the matching route entry
1836
- const matched = findMatch(pathname);
1837
- if (!matched) return null;
1838
-
1839
- // Use params from trie match if available, fall back to provided params
1840
- const matchedParams = matched.params ?? params;
1841
-
1842
- // Build a minimal RouterContext for loadManifest/traverseBack
1843
- const routerCtx: RouterContext<TEnv> = {
1844
- findMatch,
1845
- loadManifest,
1846
- traverseBack,
1847
- createHandlerContext,
1848
- setupLoaderAccess,
1849
- setupLoaderAccessSilent,
1850
- getContext,
1851
- getMetricsStore,
1852
- createCacheScope,
1853
- findInterceptForRoute,
1854
- resolveAllSegmentsWithRevalidation,
1855
- resolveInterceptEntry,
1856
- evaluateRevalidation,
1857
- getRequestContext,
1858
- resolveAllSegments,
1859
- createHandleStore,
1860
- buildEntryRevalidateMap,
1861
- resolveLoadersOnlyWithRevalidation,
1862
- resolveInterceptLoadersOnly,
1863
- resolveLoadersOnly,
1864
- };
1865
-
1866
- return runWithRouterContext(routerCtx, async () => {
1867
- // 2. Load the manifest entry tree
1868
- const manifestEntry = await loadManifest(
1869
- matched.entry,
1870
- matched.routeKey,
1871
- pathname,
1872
- undefined,
1873
- false,
1874
- );
1875
-
1876
- // 3. Build ancestor chain [root, ..., route]
1877
- const entries: EntryData[] = [];
1878
- for (const entry of traverseBack(manifestEntry)) {
1879
- entries.push(entry);
1880
- }
1881
-
1882
- // 4. Create handle store for collecting handle data
1883
- const handleStore = createHandleStore();
382
+ // Track all registered routes with their prefixes for reverse().
383
+ // Seed from injected NamedRoutes so reverse() works at module load time
384
+ // for routes that come from lazy includes.
385
+ const mergedRouteMap: Record<string, string> =
386
+ flattenNamedRoutes(staticRouteNames);
1884
387
 
1885
- // 5. Create a minimal request context with the handle store
1886
- const stubRes = new Response(null, { status: 200 });
1887
- const minimalRequestContext: RequestContext<TEnv> = {
1888
- env: {} as TEnv,
1889
- request: new Request("http://prerender" + pathname),
1890
- url: new URL("http://prerender" + pathname),
1891
- pathname,
1892
- searchParams: new URLSearchParams(),
1893
- var: {},
1894
- get: () => undefined as any,
1895
- set: () => {},
1896
- params: matchedParams,
1897
- res: stubRes,
1898
- cookie: () => undefined,
1899
- cookies: () => ({}),
1900
- setCookie: () => {},
1901
- deleteCookie: () => {},
1902
- header: () => {},
1903
- use: (() => {
1904
- throw new Error("use() not available during pre-rendering");
1905
- }) as any,
1906
- method: "GET",
1907
- _handleStore: handleStore,
1908
- waitUntil: () => {},
1909
- onResponse: () => {},
1910
- _onResponseCallbacks: [],
1911
- };
1912
-
1913
- return runWithRequestContext(minimalRequestContext, async () => {
1914
- // 6. Create BuildContext (no request/env/headers/cookies)
1915
- const buildCtx = createBuildContext<TEnv>(
1916
- matchedParams,
1917
- pathname,
1918
- handleStore,
1919
- );
1920
-
1921
- // 7. Wire use() for handles only (loaders throw)
1922
- setupBuildUse(buildCtx);
1923
-
1924
- // 8. Resolve all segments with skipLoaders
1925
- const loaderPromises = new Map<string, Promise<any>>();
1926
- const allSegments = await resolveAllSegments(
1927
- entries,
1928
- matched.routeKey,
1929
- matchedParams,
1930
- buildCtx,
1931
- loaderPromises,
1932
- { skipLoaders: true },
1933
- );
388
+ // Track names that came from the static seed so we can silently overwrite
389
+ // them during routes() registration. The gen file may be stale during HMR,
390
+ // so conflicts between seeded and runtime-registered values are expected.
391
+ const seededNames = new Set(Object.keys(mergedRouteMap));
1934
392
 
1935
- // 9. Filter out any loader segments (belt-and-suspenders)
1936
- const nonLoaderSegments = allSegments.filter((s) => s.type !== "loader");
393
+ // Lazy precomputed entries lookup: rebuilt when per-router data arrives.
394
+ // In production multi-router setups, per-router data is loaded lazily via
395
+ // ensureRouterManifest(). At createRouter() time the data isn't available yet,
396
+ // so we defer building the Map until first use and invalidate when the
397
+ // per-router source changes.
398
+ let precomputedByPrefix: Map<string, Record<string, string>> | null = null;
399
+ let precomputedSource:
400
+ | Array<{ staticPrefix: string; routes: Record<string, string> }>
401
+ | null
402
+ | undefined;
403
+
404
+ function getPrecomputedByPrefix(): Map<
405
+ string,
406
+ Record<string, string>
407
+ > | null {
408
+ const current =
409
+ getRouterPrecomputedEntries(routerId) ?? getPrecomputedEntries();
410
+ if (current !== precomputedSource) {
411
+ precomputedSource = current;
412
+ // buildPrecomputedByPrefix drops any staticPrefix owned by more than one
413
+ // leaf include instead of collapsing it last-wins (which would mis-assign
414
+ // one include's routes to another's entry and 500 a valid sibling route).
415
+ // Such shared-prefix includes resolve via the handler path instead.
416
+ precomputedByPrefix = current ? buildPrecomputedByPrefix(current) : null;
417
+ }
418
+ return precomputedByPrefix;
419
+ }
1937
420
 
1938
- // 10. Wait for handles to settle
1939
- await handleStore.settled;
421
+ // Wrapper to pass debugPerformance to external createMetricsStore.
422
+ // Also checks per-request flag set by ctx.debugPerformance() in middleware.
423
+ const getMetricsStore = () => {
424
+ const reqCtx = _getRequestContext();
425
+ const enabled = debugPerformance || !!reqCtx?._debugPerformance;
426
+ if (!enabled) return undefined;
427
+ if (!reqCtx) {
428
+ return createMetricsStore(true);
429
+ }
430
+ reqCtx._metricsStore ??= createMetricsStore(true);
431
+ return reqCtx._metricsStore;
432
+ };
1940
433
 
1941
- // 11. Serialize segments using the cache serializer
1942
- const { serializeSegments } = await import("./cache/cache-scope.js");
1943
- const serializedSegments = await serializeSegments(nonLoaderSegments);
434
+ // Wrapper to pass defaults to error/notFound boundary finders
435
+ const findNearestErrorBoundary = (entry: EntryData | null) =>
436
+ findErrorBoundary(entry, defaultErrorBoundary);
1944
437
 
1945
- // 12. Collect handle data per segment (skip segments with no handle data)
1946
- const handles: Record<string, SegmentHandleData> = {};
1947
- for (const seg of nonLoaderSegments) {
1948
- const segHandles = handleStore.getDataForSegment(seg.id);
1949
- if (Object.keys(segHandles).length > 0) {
1950
- handles[seg.id] = segHandles;
1951
- }
1952
- }
438
+ const findNearestNotFoundBoundary = (entry: EntryData | null) =>
439
+ findNotFoundBoundary(entry, defaultNotFoundBoundary);
1953
440
 
1954
- // Use the trie-level route key (e.g., "docs", "docs.article")
1955
- const routeName = matched.routeKey;
441
+ // Helper to get handleStore from request context
442
+ const getHandleStore = (): HandleStore | undefined => {
443
+ return _getRequestContext()?._handleStore;
444
+ };
1956
445
 
1957
- return {
1958
- segments: serializedSegments,
1959
- handles,
1960
- routeName,
1961
- params: matchedParams,
1962
- };
446
+ // Track a pending handler promise (non-blocking).
447
+ // Attaches a side-effect .catch() to report streaming handler errors to onError
448
+ // without altering the rejection chain (React's streaming error boundary still handles it).
449
+ const trackHandler = <T>(
450
+ promise: Promise<T>,
451
+ errorContext?: {
452
+ segmentId?: string;
453
+ segmentType?: string;
454
+ },
455
+ ): Promise<T> => {
456
+ const store = getHandleStore();
457
+ const tracked = store ? store.track(promise) : promise;
458
+
459
+ // Report streaming handler errors to onError as a side-effect.
460
+ // The rejection still propagates to the RSC stream for client error boundaries.
461
+ // Captures request context eagerly (closure) so the catch handler has full context.
462
+ const reqCtx = _getRequestContext();
463
+ if (reqCtx && onError) {
464
+ tracked.catch((error) => {
465
+ callOnError(error, "handler", {
466
+ request: reqCtx.request,
467
+ url: reqCtx.url,
468
+ routeKey: reqCtx._routeName,
469
+ params: reqCtx.params as Record<string, string>,
470
+ env: reqCtx.env as TEnv,
471
+ segmentId: errorContext?.segmentId,
472
+ segmentType: errorContext?.segmentType as any,
473
+ handledByBoundary: true,
474
+ });
1963
475
  });
1964
- });
1965
- }
476
+ }
1966
477
 
1967
- /**
1968
- * Match request and return segments (document/SSR requests)
1969
- *
1970
- * Uses generator middleware pipeline for clean separation of concerns:
1971
- * - cache-lookup: Check cache first
1972
- * - segment-resolution: Resolve segments on cache miss
1973
- * - cache-store: Store results in cache
1974
- * - background-revalidation: SWR revalidation
1975
- */
1976
- async function match(request: Request, env: TEnv): Promise<MatchResult> {
1977
- // Build RouterContext with all closure functions needed by middleware
1978
- const routerCtx: RouterContext<TEnv> = {
1979
- findMatch,
1980
- loadManifest,
1981
- traverseBack,
1982
- createHandlerContext,
1983
- setupLoaderAccess,
1984
- setupLoaderAccessSilent,
1985
- getContext,
1986
- getMetricsStore,
1987
- createCacheScope,
1988
- findInterceptForRoute,
1989
- resolveAllSegmentsWithRevalidation,
1990
- resolveInterceptEntry,
1991
- evaluateRevalidation,
1992
- getRequestContext,
1993
- resolveAllSegments,
1994
- createHandleStore,
1995
- buildEntryRevalidateMap,
1996
- resolveLoadersOnlyWithRevalidation,
1997
- resolveInterceptLoadersOnly,
1998
- resolveLoadersOnly,
1999
- };
478
+ return tracked;
479
+ };
2000
480
 
2001
- return runWithRouterLogContext(
2002
- { request, transaction: "match" },
2003
- () =>
2004
- runWithRouterContext(routerCtx, async () =>
2005
- withRouterLogScope("match", async () => {
2006
- const result = await createMatchContextForFull(request, env);
2007
-
2008
- // Handle redirect case
2009
- if ("type" in result && result.type === "redirect") {
2010
- return {
2011
- segments: [],
2012
- matched: [],
2013
- diff: [],
2014
- params: {},
2015
- redirect: result.redirectUrl,
2016
- };
2017
- }
481
+ // Wrapper for wrapLoaderWithErrorHandling that uses router's error boundary finder
482
+ // Includes onError callback for loader error notification and telemetry emission.
483
+ function wrapLoaderPromise<T>(
484
+ promise: Promise<T>,
485
+ entry: EntryData,
486
+ segmentId: string,
487
+ pathname: string,
488
+ errorContext?: {
489
+ request: Request;
490
+ url: URL;
491
+ routeKey?: string;
492
+ params?: Record<string, string>;
493
+ env?: TEnv;
494
+ isPartial?: boolean;
495
+ requestStartTime?: number;
496
+ },
497
+ ): Promise<LoaderDataResult<T>> {
498
+ const loaderStart = telemetrySink ? performance.now() : 0;
499
+ const loaderRequestId = telemetrySink
500
+ ? errorContext?.request
501
+ ? getRequestId(errorContext.request)
502
+ : undefined
503
+ : undefined;
504
+ if (telemetrySink) {
505
+ const loaderName = segmentId.split(".").pop() || "unknown";
506
+ safeEmit(telemetry, {
507
+ type: "loader.start",
508
+ timestamp: loaderStart,
509
+ requestId: loaderRequestId,
510
+ segmentId,
511
+ loaderName,
512
+ pathname,
513
+ });
514
+ }
2018
515
 
2019
- const ctx = result as MatchContext<TEnv>;
2020
-
2021
- try {
2022
- const state = createPipelineState();
2023
- const pipeline = createMatchPartialPipeline(ctx, state);
2024
- return await collectMatchResult(pipeline, ctx, state);
2025
- } catch (error) {
2026
- if (error instanceof Response) throw error;
2027
- // Report unhandled errors during full match pipeline
2028
- callOnError(error, "routing", {
2029
- request,
2030
- url: ctx.url,
2031
- env,
2032
- isPartial: false,
2033
- handledByBoundary: false,
516
+ const result = wrapLoaderWithErrorHandling(
517
+ promise,
518
+ entry,
519
+ segmentId,
520
+ pathname,
521
+ findNearestErrorBoundary,
522
+ createErrorInfo,
523
+ // Invoke onError when loader fails
524
+ errorContext
525
+ ? (error, ctx) => {
526
+ callOnError(error, "loader", {
527
+ request: errorContext.request,
528
+ url: errorContext.url,
529
+ routeKey: errorContext.routeKey,
530
+ params: errorContext.params,
531
+ segmentId: ctx.segmentId,
532
+ segmentType: "loader",
533
+ loaderName: ctx.loaderName,
534
+ env: errorContext.env,
535
+ isPartial: errorContext.isPartial,
536
+ handledByBoundary: ctx.handledByBoundary,
537
+ requestStartTime: errorContext.requestStartTime,
538
+ });
539
+ if (telemetrySink) {
540
+ const errorObj =
541
+ error instanceof Error ? error : new Error(String(error));
542
+ safeEmit(telemetry, {
543
+ type: "loader.error",
544
+ timestamp: performance.now(),
545
+ requestId: loaderRequestId,
546
+ segmentId: ctx.segmentId,
547
+ loaderName: ctx.loaderName,
548
+ pathname,
549
+ error: errorObj,
550
+ handledByBoundary: ctx.handledByBoundary,
2034
551
  });
2035
- throw sanitizeError(error);
2036
552
  }
2037
- }),
2038
- ),
553
+ }
554
+ : undefined,
2039
555
  );
2040
- }
2041
556
 
2042
- async function matchError(
2043
- request: Request,
2044
- _context: TEnv,
2045
- error: unknown,
2046
- segmentType: ErrorInfo["segmentType"] = "route",
2047
- ): Promise<MatchResult | null> {
2048
- return runWithRouterLogContext(
2049
- { request, transaction: "matchError" },
2050
- () =>
2051
- withRouterLogScope("matchError", () =>
2052
- _matchError(
2053
- request,
2054
- _context,
2055
- error,
2056
- matchApiDeps,
2057
- defaultErrorBoundary,
2058
- segmentType,
2059
- ),
2060
- ),
2061
- );
557
+ // Emit loader.end after the promise settles (fire-and-forget)
558
+ if (telemetrySink) {
559
+ const loaderName = segmentId.split(".").pop() || "unknown";
560
+ result.then((r) => {
561
+ safeEmit(telemetry, {
562
+ type: "loader.end",
563
+ timestamp: performance.now(),
564
+ requestId: loaderRequestId,
565
+ segmentId,
566
+ loaderName,
567
+ pathname,
568
+ durationMs: performance.now() - loaderStart,
569
+ ok: r.ok,
570
+ });
571
+ });
572
+ }
573
+
574
+ return result;
2062
575
  }
2063
576
 
577
+ // Dependencies object for extracted segment resolution functions.
578
+ // Captures closure-bound helpers from createRouter.
579
+ const segmentDeps: SegmentResolutionDeps<TEnv> = {
580
+ wrapLoaderPromise,
581
+ trackHandler,
582
+ findNearestErrorBoundary,
583
+ findNearestNotFoundBoundary,
584
+ notFoundComponent: notFound,
585
+ callOnError,
586
+ viewTransitionDefault: viewTransitionOption,
587
+ };
2064
588
 
2065
- async function createMatchContextForFull(
2066
- request: Request,
2067
- env: TEnv,
2068
- ) {
2069
- return _createMatchContextForFull(request, env, matchApiDeps, findInterceptForRoute);
2070
- }
589
+ // Match API dependencies
590
+ const matchApiDeps: MatchApiDeps<TEnv> = {
591
+ findMatch: (pathname: string, ms?: any) => findMatch(pathname, ms),
592
+ getMetricsStore,
593
+ findInterceptForRoute: (routeKey, parentEntry, selectorContext, isAction) =>
594
+ findInterceptForRoute(routeKey, parentEntry, selectorContext, isAction),
595
+ callOnError,
596
+ findNearestErrorBoundary,
597
+ // Use per-router manifest when available, otherwise the static named map
598
+ // seeded into mergedRouteMap at router creation.
599
+ getRouteMap: () => getRouterManifest(routerId) ?? mergedRouteMap,
600
+ };
2071
601
 
2072
- async function createMatchContextForPartial(
2073
- request: Request,
2074
- env: TEnv,
2075
- actionContext?: { actionId?: string; actionUrl?: URL; actionResult?: any; formData?: FormData },
2076
- ) {
2077
- return _createMatchContextForPartial(request, env, matchApiDeps, findInterceptForRoute, actionContext);
602
+ // Create segment resolution wrappers bound to segmentDeps
603
+ const {
604
+ resolveAllSegments,
605
+ resolveLoadersOnly,
606
+ resolveLoadersOnlyWithRevalidation,
607
+ buildEntryRevalidateMap,
608
+ resolveAllSegmentsWithRevalidation,
609
+ findInterceptForRoute,
610
+ resolveInterceptEntry,
611
+ resolveInterceptLoadersOnly,
612
+ } = createSegmentWrappers<TEnv>(segmentDeps);
613
+
614
+ // Lazy evaluation deps — captures closure state for extracted evaluateLazyEntry
615
+ const lazyEvalDeps: LazyEvalDeps<TEnv> = {
616
+ routesEntries,
617
+ mergedRouteMap,
618
+ nextMountIndex: () => mountIndex++,
619
+ getPrecomputedByPrefix,
620
+ routerId,
621
+ };
622
+
623
+ // Must return the Promise from _evaluateLazyEntry: an async include provider
624
+ // (`() => import("./routes")`) resolves off the startup path, and createFindMatch
625
+ // awaits this to know when the import + expansion have completed. Dropping it
626
+ // (typing this `void`) makes the import fire-and-forget, so findMatch spins the
627
+ // lazy-eval retry loop to its cap and returns null on the first request to any
628
+ // async include whose prefix isn't already covered by a unique precomputed entry
629
+ // (nested includes, shared prefixes, regex fallback).
630
+ function evaluateLazyEntry(entry: RouteEntry<TEnv>): void | Promise<void> {
631
+ return _evaluateLazyEntry(entry, lazyEvalDeps);
2078
632
  }
2079
633
 
2080
- /**
2081
- * Match partial request with revalidation
2082
- *
2083
- * Uses generator middleware pipeline for clean separation of concerns:
2084
- * - cache-lookup: Check cache first
2085
- * - segment-resolution: Resolve segments on cache miss
2086
- * - intercept-resolution: Handle intercept routes
2087
- * - cache-store: Store results in cache
2088
- * - background-revalidation: SWR revalidation
2089
- */
2090
- async function matchPartial(
2091
- request: Request,
2092
- context: TEnv,
2093
- actionContext?: ActionContext,
2094
- ): Promise<MatchResult | null> {
2095
- // Build RouterContext with all closure functions needed by middleware
2096
- const routerCtx: RouterContext<TEnv> = {
634
+ // Create findMatch with single-entry cache, bound to router state
635
+ const findMatch = createFindMatch<TEnv>({
636
+ routesEntries,
637
+ evaluateLazyEntry,
638
+ routerId,
639
+ });
640
+
641
+ // Build a RouterContext once — shared by match, matchPartial, matchForPrerender
642
+ function buildRouterContext(): RouterContext<TEnv> {
643
+ return {
2097
644
  findMatch,
2098
645
  loadManifest,
2099
646
  traverseBack,
@@ -2113,479 +660,307 @@ export function createRouter<TEnv = any>(
2113
660
  buildEntryRevalidateMap,
2114
661
  resolveLoadersOnlyWithRevalidation,
2115
662
  resolveInterceptLoadersOnly,
663
+ resolveLoadersOnly,
664
+ telemetry: telemetrySink,
2116
665
  };
2117
-
2118
- return runWithRouterLogContext(
2119
- { request, transaction: "matchPartial" },
2120
- () =>
2121
- runWithRouterContext(routerCtx, async () =>
2122
- withRouterLogScope("matchPartial", async () => {
2123
- const ctx = await createMatchContextForPartial(
2124
- request,
2125
- context,
2126
- actionContext,
2127
- );
2128
- if (!ctx) return null;
2129
-
2130
- try {
2131
- const state = createPipelineState();
2132
- const pipeline = createMatchPartialPipeline(ctx, state);
2133
- return await collectMatchResult(pipeline, ctx, state);
2134
- } catch (error) {
2135
- if (error instanceof Response) throw error;
2136
- // Report unhandled errors during partial match pipeline
2137
- callOnError(error, actionContext ? "action" : "revalidation", {
2138
- request,
2139
- url: ctx.url,
2140
- env: context,
2141
- actionId: actionContext?.actionId,
2142
- isPartial: true,
2143
- handledByBoundary: false,
2144
- });
2145
- throw sanitizeError(error);
2146
- }
2147
- }),
2148
- ),
2149
- );
2150
666
  }
2151
667
 
2152
- /**
2153
- * Preview match - returns route middleware without segment resolution.
2154
- * Also returns responseType and handler for response routes (non-RSC short-circuit).
2155
- */
2156
- async function previewMatch(
2157
- request: Request,
2158
- _context: TEnv,
2159
- ): Promise<{
2160
- routeMiddleware?: Array<{
2161
- handler: import("./router/middleware.js").MiddlewareFn;
2162
- params: Record<string, string>;
2163
- }>;
2164
- responseType?: string;
2165
- handler?: Function;
2166
- params?: Record<string, string>;
2167
- negotiated?: boolean;
2168
- } | null> {
2169
- return runWithRouterLogContext(
2170
- { request, transaction: "previewMatch" },
2171
- async () =>
2172
- withRouterLogScope("previewMatch", async () => {
2173
- const url = new URL(request.url);
2174
- const pathname = url.pathname;
2175
-
2176
- // Quick route matching
2177
- const matched = findMatch(pathname);
2178
- if (!matched) {
2179
- return null;
2180
- }
2181
-
2182
- // Skip redirect check - will be handled in full match
2183
- if (matched.redirectTo) {
2184
- return { routeMiddleware: undefined };
2185
- }
668
+ // Prerender/static match deps (bind closure state for extracted functions)
669
+ const prerenderDeps = {
670
+ findMatch,
671
+ buildRouterContext,
672
+ mergedRouteMap,
673
+ resolveAllSegments,
674
+ };
2186
675
 
2187
- // Load manifest (without segment resolution)
2188
- const manifestEntry = await loadManifest(
2189
- matched.entry,
2190
- matched.routeKey,
676
+ async function matchForPrerender(
677
+ pathname: string,
678
+ params: Record<string, string>,
679
+ buildVars?: Record<string, any>,
680
+ isPassthroughRoute?: boolean,
681
+ buildEnv?: TEnv,
682
+ devMode?: boolean,
683
+ ) {
684
+ return _matchForPrerender(
2191
685
  pathname,
2192
- undefined, // No metrics store for preview
2193
- false, // isSSR - doesn't matter for preview
2194
- );
2195
-
2196
- // Collect route-level middleware from entry tree
2197
- // Includes middleware from orphan layouts (inline layouts within routes)
2198
- const routeMiddleware = collectRouteMiddleware(
2199
- traverseBack(manifestEntry),
2200
- matched.params,
686
+ params,
687
+ prerenderDeps,
688
+ buildVars,
689
+ isPassthroughRoute,
690
+ buildEnv,
691
+ devMode,
2201
692
  );
693
+ }
2202
694
 
2203
- // Check for response type (from trie match or manifest entry)
2204
- const responseType = matched.responseType ||
2205
- (manifestEntry.type === "route" ? manifestEntry.responseType : undefined);
2206
-
2207
- // Content negotiation: when negotiate variants exist, pick the best
2208
- // handler based on the Accept header. Uses q-values and client order
2209
- // as tiebreaker (matching Express/Hono behavior). RSC routes participate
2210
- // as text/html candidates so browsers naturally get HTML without
2211
- // special-casing.
2212
- if (matched.negotiateVariants && matched.negotiateVariants.length > 0) {
2213
- const acceptEntries = parseAcceptTypes(request.headers.get("accept") || "");
2214
-
2215
- // Build candidate list preserving definition order.
2216
- // For wildcard (*/*) and no-Accept fallback, the first candidate wins.
2217
- const variants = matched.negotiateVariants;
2218
- let candidates: Array<{ routeKey: string; responseType: string }>;
2219
- if (responseType) {
2220
- // Primary is response-type — include it as a candidate
2221
- candidates = [...variants, { routeKey: matched.routeKey, responseType }];
2222
- } else {
2223
- // Primary is RSC — insert as text/html candidate in definition order
2224
- const rscCandidate = { routeKey: matched.routeKey, responseType: RSC_RESPONSE_TYPE };
2225
- candidates = matched.rscFirst
2226
- ? [rscCandidate, ...variants]
2227
- : [...variants, rscCandidate];
2228
- }
2229
-
2230
- const variant = pickNegotiateVariant(acceptEntries, candidates);
2231
-
2232
- // If the winner is RSC, fall through to default RSC handling
2233
- if (variant.responseType === RSC_RESPONSE_TYPE) {
2234
- // Fall through — RSC won negotiation
2235
- } else if (responseType && variant.routeKey === matched.routeKey) {
2236
- // Fall through — response-type primary won, already set
2237
- } else {
2238
- const negotiateEntry = await loadManifest(
2239
- matched.entry,
2240
- variant.routeKey,
2241
- pathname,
2242
- undefined,
2243
- false,
2244
- );
2245
- return {
2246
- routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
2247
- responseType: variant.responseType,
2248
- handler: negotiateEntry.type === "route" ? negotiateEntry.handler : undefined,
2249
- params: matched.params,
2250
- negotiated: true,
2251
- };
2252
- }
2253
- }
2254
-
2255
- // If we passed through the negotiation block (variants exist), mark as
2256
- // negotiated so the handler sets Vary: Accept on the response.
2257
- const hasVariants = matched.negotiateVariants && matched.negotiateVariants.length > 0;
2258
- return {
2259
- routeMiddleware: routeMiddleware.length > 0 ? routeMiddleware : undefined,
2260
- ...(responseType ? {
2261
- responseType,
2262
- handler: manifestEntry.type === "route" ? manifestEntry.handler : undefined,
2263
- params: matched.params,
2264
- } : {}),
2265
- ...(hasVariants ? { negotiated: true } : {}),
2266
- };
2267
- }),
695
+ async function renderStaticSegment(
696
+ handler: Function,
697
+ handlerId: string,
698
+ routeName?: string,
699
+ buildEnv?: TEnv,
700
+ devMode?: boolean,
701
+ ) {
702
+ return _renderStaticSegment<TEnv>(
703
+ handler,
704
+ handlerId,
705
+ mergedRouteMap,
706
+ routeName,
707
+ buildEnv,
708
+ devMode,
2268
709
  );
2269
710
  }
2270
711
 
2271
- /**
2272
- * Create route builder with accumulated route types
2273
- * The TNewRoutes type parameter captures the new routes being added
2274
- */
2275
- function createRouteBuilder<TNewRoutes extends Record<string, string>>(
2276
- prefix: string,
2277
- routes: TNewRoutes,
2278
- ): RouteBuilder<RouteDefinition, TEnv, any, TNewRoutes> {
2279
- const currentMountIndex = mountIndex++;
2280
-
2281
- // Merge routes into the reverse map
2282
- // Keys stay unchanged for composability - only URL patterns get prefixed
2283
- const routeEntries = routes as Record<string, string>;
2284
- for (const [key, pattern] of Object.entries(routeEntries)) {
2285
- // Build prefixed pattern: "/shop" + "/cart" -> "/shop/cart"
2286
- // Root prefix "/" is a no-op — don't double the leading slash.
2287
- const effectivePrefix = prefix === "/" ? "" : prefix;
2288
- const prefixedPattern =
2289
- effectivePrefix && pattern !== "/"
2290
- ? `${effectivePrefix}${pattern}`
2291
- : effectivePrefix && pattern === "/"
2292
- ? effectivePrefix
2293
- : pattern;
2294
-
2295
- // Runtime validation: warn if key already exists with different pattern
2296
- const existingPattern = mergedRouteMap[key];
2297
- if (
2298
- existingPattern !== undefined &&
2299
- existingPattern !== prefixedPattern
2300
- ) {
2301
- console.warn(
2302
- `[rsc-router] Route key conflict: "${key}" already maps to "${existingPattern}", ` +
2303
- `overwriting with "${prefixedPattern}". Use unique key names to avoid this.`,
2304
- );
2305
- }
2306
-
2307
- // Use original key - enables reusable route modules
2308
- mergedRouteMap[key] = prefixedPattern;
2309
- }
2310
-
2311
- // Auto-register route map for runtime reverse() usage
2312
- registerRouteMap(mergedRouteMap);
2313
-
2314
- // Extract trailing slash config if present (attached by route())
2315
- const trailingSlashConfig = (routes as any).__trailingSlash as
2316
- | Record<string, TrailingSlashMode>
2317
- | undefined;
2318
-
2319
- // Create builder object so .use() can return it
2320
- const builder: RouteBuilder<RouteDefinition, TEnv, any, TNewRoutes> = {
2321
- use(
2322
- patternOrMiddleware: string | MiddlewareFn<TEnv>,
2323
- middleware?: MiddlewareFn<TEnv>,
2324
- ) {
2325
- // Mount-scoped middleware - prefix is the mount prefix
2326
- addMiddleware(patternOrMiddleware, middleware, prefix || null);
2327
- return builder;
2328
- },
2329
-
2330
- map(
2331
- handler:
2332
- | ((
2333
- helpers: InlineRouteHelpers<TNewRoutes, TEnv>,
2334
- ) => Array<AllUseItems>)
2335
- | (() =>
2336
- | Array<AllUseItems>
2337
- | Promise<{ default: () => Array<AllUseItems> }>
2338
- | Promise<() => Array<AllUseItems>>),
2339
- ) {
2340
- // Store handler as-is - detection happens at call time based on return type
2341
- // Both patterns use the same signature:
2342
- // - Inline: ({ route }) => [...] - receives helpers, returns Array
2343
- // - Lazy: () => import(...) - ignores helpers, returns Promise
2344
- routesEntries.push({
2345
- prefix,
2346
- staticPrefix: extractStaticPrefix(prefix),
2347
- routes: routes as ResolvedRouteMap<any>,
2348
- trailingSlash: trailingSlashConfig,
2349
- handler: handler as any,
2350
- mountIndex: currentMountIndex,
2351
- });
2352
- // Return router with accumulated types
2353
- // At runtime this is the same object, but TypeScript tracks the accumulated route types
2354
- return router as any;
2355
- },
2356
-
2357
- // Expose accumulated route map for typeof extraction
2358
- get routeMap() {
2359
- return mergedRouteMap as TNewRoutes;
2360
- },
2361
- };
712
+ // Create match handler functions bound to router state
713
+ const matchHandlers = createMatchHandlers<TEnv>({
714
+ buildRouterContext,
715
+ callOnError,
716
+ matchApiDeps,
717
+ defaultErrorBoundary,
718
+ findMatch,
719
+ findInterceptForRoute,
720
+ telemetry: telemetrySink,
721
+ cacheSignalEnabled,
722
+ });
2362
723
 
2363
- return builder;
2364
- }
724
+ const { match, matchPartial, matchError, previewMatch } = matchHandlers;
2365
725
 
2366
726
  /**
2367
727
  * Router instance
2368
728
  * The type system tracks accumulated routes through the builder chain
2369
729
  * Initial TRoutes is {} (empty) to avoid poisoning accumulated types with Record<string, string>
2370
730
  */
2371
- const router: RSCRouter<TEnv, {}> = {
731
+ const router: RangoInternal<TEnv, {}> = {
2372
732
  __brand: RSC_ROUTER_BRAND,
2373
733
  id: routerId,
734
+ basename,
2374
735
 
2375
- routes(
2376
- prefixOrRoutes: string | Record<string, string> | UrlPatterns<TEnv>,
2377
- maybeRoutes?: Record<string, string>,
2378
- ): any {
2379
- // Note: Multiple .routes() calls are allowed for backwards compatibility
2380
- // with the old map() pattern. For new code, prefer urls() with include().
2381
-
2382
- // Check if argument is UrlPatterns (new Django-style API)
2383
- // Detect by checking for handler and definitions properties
2384
- if (
2385
- typeof prefixOrRoutes === "object" &&
2386
- prefixOrRoutes !== null &&
2387
- "handler" in prefixOrRoutes &&
2388
- "definitions" in prefixOrRoutes &&
2389
- typeof (prefixOrRoutes as UrlPatterns<TEnv>).handler === "function"
2390
- ) {
2391
- const urlPatterns = prefixOrRoutes as UrlPatterns<TEnv>;
2392
- // Store reference for runtime manifest generation
2393
- storedUrlPatterns = urlPatterns;
2394
- const currentMountIndex = mountIndex++;
2395
-
2396
- // Create manifest and patterns maps for route registration
2397
- const manifest = new Map<string, EntryData>();
2398
- const patterns = new Map<string, string>();
2399
- const patternsByPrefix = new Map<string, Map<string, string>>();
2400
- const trailingSlashMap = new Map<string, TrailingSlashMode>();
2401
-
2402
- // Run the handler once to extract patterns for route matching.
2403
- // Note: loadManifest will re-run the handler to register entries in its context.
2404
- // Lazy includes are detected in the return value and handled separately.
2405
- //
2406
- // Pattern extraction must use the same mountIndex and MapRootLayout root
2407
- // parent as loadManifest so that shortCodes produced here match those at
2408
- // runtime. include() captures the current parent and counters; if those
2409
- // shortCodes diverge from the runtime tree the segment reconciliation on
2410
- // the client will see a full mismatch and remount the entire page.
2411
- const syntheticMapRoot: EntryData = {
2412
- type: "layout",
2413
- id: `#synthetic-maproot-M${currentMountIndex}`,
2414
- shortCode: `M${currentMountIndex}L0`,
2415
- parent: null,
2416
- handler: MapRootLayout,
2417
- middleware: [],
2418
- revalidate: [],
2419
- errorBoundary: [],
2420
- notFoundBoundary: [],
2421
- layout: [],
2422
- parallel: [],
2423
- intercept: [],
2424
- loader: [],
2425
- };
736
+ routes(patternsOrBuilder: UrlPatterns<TEnv> | UrlBuilder<TEnv>): any {
737
+ // Wrap builder functions in urls() automatically
738
+ const urlPatterns: UrlPatterns<TEnv> =
739
+ typeof patternsOrBuilder === "function"
740
+ ? (urls(patternsOrBuilder) as UrlPatterns<TEnv>)
741
+ : patternsOrBuilder;
2426
742
 
2427
- let handlerResult: AllUseItems[] = [];
2428
- RSCRouterContext.run(
2429
- {
2430
- manifest,
2431
- patterns,
2432
- patternsByPrefix,
2433
- trailingSlash: trailingSlashMap,
2434
- namespace: "root",
2435
- parent: syntheticMapRoot,
2436
- counters: {},
2437
- mountIndex: currentMountIndex,
2438
- },
2439
- () => {
2440
- handlerResult = urlPatterns.handler() as AllUseItems[];
2441
- },
2442
- );
743
+ // Store reference for runtime manifest generation
744
+ storedUrlPatterns = urlPatterns;
745
+ const currentMountIndex = mountIndex++;
2443
746
 
2444
- // Store the ORIGINAL handler - loadManifest will re-run it to register manifest entries
2445
- // Convert trailingSlash map to object for the router
2446
- const trailingSlashConfig =
2447
- trailingSlashMap.size > 0
2448
- ? Object.fromEntries(trailingSlashMap)
2449
- : undefined;
2450
-
2451
- // Collect route keys that have prerender handlers (for non-trie match path)
2452
- let prerenderRouteKeys: Set<string> | undefined;
2453
- for (const [name, entry] of manifest.entries()) {
2454
- if (entry.type === "route" && entry.isPrerender) {
2455
- if (!prerenderRouteKeys) prerenderRouteKeys = new Set();
2456
- prerenderRouteKeys.add(name);
2457
- }
2458
- }
747
+ // Create manifest and patterns maps for route registration
748
+ const manifest = new Map<string, EntryData>();
749
+ const routePatterns = new Map<string, string>();
750
+ const patternsByPrefix = new Map<string, Map<string, string>>();
751
+ const trailingSlashMap = new Map<string, TrailingSlashMode>();
752
+
753
+ // Run the handler once to extract patterns for route matching.
754
+ // Note: loadManifest will re-run the handler to register entries in its context.
755
+ // Lazy includes are detected in the return value and handled separately.
756
+ //
757
+ // Pattern extraction must use the same mountIndex and MapRootLayout root
758
+ // parent as loadManifest so that shortCodes produced here match those at
759
+ // runtime. include() captures the current parent and counters; if those
760
+ // shortCodes diverge from the runtime tree the segment reconciliation on
761
+ // the client will see a full mismatch and remount the entire page.
762
+ const syntheticMapRoot: EntryData = {
763
+ type: "layout",
764
+ id: `#synthetic-maproot-M${currentMountIndex}`,
765
+ shortCode: `M${currentMountIndex}L0`,
766
+ parent: null,
767
+ handler: MapRootLayout,
768
+ middleware: [],
769
+ revalidate: [],
770
+ errorBoundary: [],
771
+ notFoundBoundary: [],
772
+ layout: [],
773
+ parallel: {},
774
+ intercept: [],
775
+ loader: [],
776
+ };
2459
777
 
2460
- // Create separate RouteEntry for each URL prefix group
2461
- // This enables prefix-based short-circuit optimization
2462
- if (patternsByPrefix.size > 0) {
2463
- for (const [prefix, prefixPatterns] of patternsByPrefix.entries()) {
2464
- const routesObject: Record<string, string> = {};
2465
- for (const [name, pattern] of prefixPatterns.entries()) {
2466
- routesObject[name] = pattern;
2467
- }
778
+ let handlerResult: AllUseItems[] = [];
779
+ RangoContext.run(
780
+ {
781
+ manifest,
782
+ patterns: routePatterns,
783
+ patternsByPrefix,
784
+ trailingSlash: trailingSlashMap,
785
+ namespace: "root",
786
+ parent: syntheticMapRoot,
787
+ counters: {},
788
+ mountIndex: currentMountIndex,
789
+ cacheProfiles: resolvedCacheProfiles,
790
+ // basename sets the initial URL prefix so all path() patterns
791
+ // are registered with the prefix (e.g. "/admin" + "/users" = "/admin/users").
792
+ // No namePrefix — route names stay unprefixed.
793
+ ...(basename ? { urlPrefix: basename } : {}),
794
+ },
795
+ () => {
796
+ handlerResult = urlPatterns.handler() as AllUseItems[];
797
+ },
798
+ );
2468
799
 
2469
- routesEntries.push({
2470
- // prefix is "" because patterns already include the URL prefix
2471
- // (e.g., "/site/:locale/user1/:id" not just "/user1/:id")
2472
- prefix: "",
2473
- // staticPrefix is the actual prefix for short-circuit optimization
2474
- staticPrefix: extractStaticPrefix(prefix),
2475
- routes: routesObject as ResolvedRouteMap<any>,
2476
- trailingSlash: trailingSlashConfig,
2477
- handler: urlPatterns.handler,
2478
- mountIndex: currentMountIndex,
2479
- ...(prerenderRouteKeys ? { prerenderRouteKeys } : {}),
2480
- });
800
+ // Convert trailingSlash map to object for the router
801
+ const trailingSlashConfig =
802
+ trailingSlashMap.size > 0
803
+ ? Object.fromEntries(trailingSlashMap)
804
+ : undefined;
805
+
806
+ // Collect route keys that have prerender handlers (for non-trie match path)
807
+ let prerenderRouteKeys: Set<string> | undefined;
808
+ let passthroughRouteKeys: Set<string> | undefined;
809
+ for (const [name, entry] of manifest.entries()) {
810
+ if (entry.type === "route" && entry.isPrerender) {
811
+ if (!prerenderRouteKeys) prerenderRouteKeys = new Set();
812
+ prerenderRouteKeys.add(name);
813
+ if (entry.isPassthrough === true) {
814
+ if (!passthroughRouteKeys) passthroughRouteKeys = new Set();
815
+ passthroughRouteKeys.add(name);
2481
816
  }
2482
- } else {
2483
- // Fallback: no prefix grouping, use flat patterns map
817
+ }
818
+ }
819
+
820
+ // Create separate RouteEntry for each URL prefix group
821
+ // This enables prefix-based short-circuit optimization
822
+ if (patternsByPrefix.size > 0) {
823
+ for (const [prefix, prefixPatterns] of patternsByPrefix.entries()) {
2484
824
  const routesObject: Record<string, string> = {};
2485
- for (const [name, pattern] of patterns.entries()) {
825
+ for (const [name, pattern] of prefixPatterns.entries()) {
2486
826
  routesObject[name] = pattern;
2487
827
  }
2488
828
 
2489
829
  routesEntries.push({
830
+ // prefix is "" because patterns already include the URL prefix
831
+ // (e.g., "/site/:locale/user1/:id" not just "/user1/:id")
2490
832
  prefix: "",
2491
- staticPrefix: "",
833
+ // staticPrefix is the actual prefix for short-circuit optimization
834
+ staticPrefix: extractStaticPrefix(prefix),
2492
835
  routes: routesObject as ResolvedRouteMap<any>,
2493
836
  trailingSlash: trailingSlashConfig,
2494
837
  handler: urlPatterns.handler,
2495
838
  mountIndex: currentMountIndex,
839
+ routerId,
840
+ cacheProfiles: resolvedCacheProfiles,
2496
841
  ...(prerenderRouteKeys ? { prerenderRouteKeys } : {}),
842
+ ...(passthroughRouteKeys ? { passthroughRouteKeys } : {}),
2497
843
  });
2498
844
  }
2499
-
2500
- // Build route map from registered patterns
2501
- for (const [name, pattern] of patterns.entries()) {
2502
- // Runtime validation: warn if key already exists with different pattern
2503
- const existingPattern = mergedRouteMap[name];
2504
- if (existingPattern !== undefined && existingPattern !== pattern) {
2505
- console.warn(
2506
- `[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
2507
- `overwriting with "${pattern}". Use unique route names to avoid this.`,
2508
- );
2509
- }
2510
- mergedRouteMap[name] = pattern;
845
+ } else {
846
+ // Fallback: no prefix grouping, use flat patterns map
847
+ const routesObject: Record<string, string> = {};
848
+ for (const [name, pattern] of routePatterns.entries()) {
849
+ routesObject[name] = pattern;
2511
850
  }
2512
851
 
2513
- // Detect lazy includes in handler result and create placeholder entries
2514
- // Uses findLazyIncludes from outer scope (shared with evaluateLazyEntry)
2515
- const lazyIncludes = findLazyIncludes(handlerResult);
852
+ routesEntries.push({
853
+ prefix: "",
854
+ staticPrefix: "",
855
+ routes: routesObject as ResolvedRouteMap<any>,
856
+ trailingSlash: trailingSlashConfig,
857
+ handler: urlPatterns.handler,
858
+ mountIndex: currentMountIndex,
859
+ routerId,
860
+ cacheProfiles: resolvedCacheProfiles,
861
+ ...(prerenderRouteKeys ? { prerenderRouteKeys } : {}),
862
+ ...(passthroughRouteKeys ? { passthroughRouteKeys } : {}),
863
+ });
864
+ }
865
+
866
+ // Build route map from registered patterns
867
+ for (const [name, pattern] of routePatterns.entries()) {
868
+ // Runtime validation: warn if key already exists with different pattern.
869
+ // Skip warning for entries that came from the static seed — the gen file
870
+ // can be stale during HMR, so runtime registration is authoritative.
871
+ const existingPattern = mergedRouteMap[name];
872
+ if (
873
+ existingPattern !== undefined &&
874
+ existingPattern !== pattern &&
875
+ !seededNames.has(name)
876
+ ) {
877
+ console.warn(
878
+ `[@rangojs/router] Route name conflict: "${name}" already maps to "${existingPattern}", ` +
879
+ `overwriting with "${pattern}". Use unique route names to avoid this.`,
880
+ );
881
+ }
882
+ mergedRouteMap[name] = pattern;
883
+ seededNames.delete(name);
884
+ }
2516
885
 
2517
- // Create placeholder RouteEntry for each lazy include
2518
- for (const lazyInclude of lazyIncludes) {
2519
- // Compute the full URL prefix (combining parent prefix if any)
2520
- const fullPrefix = lazyInclude.context.urlPrefix
2521
- ? lazyInclude.context.urlPrefix + lazyInclude.prefix
2522
- : lazyInclude.prefix;
886
+ // Detect lazy includes in handler result and create placeholder entries
887
+ const lazyIncludes = findLazyIncludes(handlerResult);
888
+
889
+ // Create placeholder RouteEntry for each lazy include
890
+ for (const lazyInclude of lazyIncludes) {
891
+ // Compute the full URL prefix (combining parent prefix if any). Use the
892
+ // slash-collapsing join so a trailing-slash parent prefix does not
893
+ // produce a double-slash staticPrefix the trie's sp can never match.
894
+ const fullPrefix = joinPrefix(
895
+ lazyInclude.context.urlPrefix,
896
+ lazyInclude.prefix,
897
+ );
2523
898
 
2524
- const lazyEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
2525
- prefix: "",
2526
- staticPrefix: extractStaticPrefix(fullPrefix),
2527
- routes: {} as ResolvedRouteMap<any>, // Empty until first match
2528
- trailingSlash: trailingSlashConfig,
2529
- handler: urlPatterns.handler,
2530
- mountIndex: currentMountIndex,
2531
- // Lazy evaluation fields
2532
- lazy: true,
2533
- lazyPatterns: lazyInclude.patterns,
2534
- lazyContext: lazyInclude.context,
2535
- lazyEvaluated: false,
2536
- // Store the include prefix for evaluation
2537
- _lazyPrefix: lazyInclude.prefix,
2538
- };
2539
- // Insert lazy entry before any entry whose staticPrefix is a
2540
- // prefix of (but shorter than) this lazy entry's staticPrefix.
2541
- // This ensures more specific lazy includes are matched before
2542
- // less specific eager entries (e.g., "/href/nested" before "/href/:id").
2543
- const lazyPrefix = lazyEntry.staticPrefix;
2544
- let insertIndex = routesEntries.length;
2545
- if (lazyPrefix) {
2546
- for (let i = 0; i < routesEntries.length; i++) {
2547
- const existing = routesEntries[i]!;
2548
- if (
2549
- lazyPrefix.startsWith(existing.staticPrefix) &&
2550
- lazyPrefix.length > existing.staticPrefix.length
2551
- ) {
2552
- insertIndex = i;
2553
- break;
2554
- }
899
+ const lazyEntry: RouteEntry<TEnv> & { _lazyPrefix?: string } = {
900
+ prefix: "",
901
+ staticPrefix: extractStaticPrefix(fullPrefix),
902
+ routes: {} as ResolvedRouteMap<any>, // Empty until first match
903
+ trailingSlash: trailingSlashConfig,
904
+ handler: urlPatterns.handler,
905
+ mountIndex: mountIndex++,
906
+ routerId,
907
+ // Lazy evaluation fields
908
+ lazy: true,
909
+ lazyPatterns: lazyInclude.patterns,
910
+ lazyContext: lazyInclude.context,
911
+ lazyEvaluated: false,
912
+ _lazyPrefix: lazyInclude.prefix,
913
+ };
914
+ // Insert lazy entry before any entry whose staticPrefix is a
915
+ // prefix of (but shorter than) this lazy entry's staticPrefix.
916
+ // This ensures more specific lazy includes are matched before
917
+ // less specific eager entries (e.g., "/href/nested" before "/href/:id").
918
+ const lazyPrefix = lazyEntry.staticPrefix;
919
+ let insertIndex = routesEntries.length;
920
+ if (lazyPrefix) {
921
+ for (let i = 0; i < routesEntries.length; i++) {
922
+ const existing = routesEntries[i]!;
923
+ if (
924
+ lazyPrefix.startsWith(existing.staticPrefix) &&
925
+ lazyPrefix.length > existing.staticPrefix.length
926
+ ) {
927
+ insertIndex = i;
928
+ break;
2555
929
  }
2556
930
  }
2557
- routesEntries.splice(insertIndex, 0, lazyEntry);
2558
931
  }
2559
-
2560
- // Auto-register route map for runtime reverse() usage
2561
- registerRouteMap(mergedRouteMap);
2562
-
2563
- // Return the router (no .map() needed for UrlPatterns)
2564
- return router;
932
+ routesEntries.splice(insertIndex, 0, lazyEntry);
2565
933
  }
2566
934
 
2567
- // Legacy API: route() + map() pattern
2568
- // If second argument exists, first is prefix
2569
- if (maybeRoutes !== undefined) {
2570
- return createRouteBuilder(prefixOrRoutes as string, maybeRoutes);
2571
- }
2572
- // Otherwise, first argument is routes with empty prefix
2573
- return createRouteBuilder("", prefixOrRoutes as Record<string, string>);
935
+ // Auto-register route map for runtime reverse() usage
936
+ registerRouteMap(mergedRouteMap);
937
+
938
+ return router;
2574
939
  },
2575
940
 
2576
941
  use(
2577
942
  patternOrMiddleware: string | MiddlewareFn<TEnv>,
2578
943
  middleware?: MiddlewareFn<TEnv>,
2579
944
  ): any {
2580
- // Global middleware - no mount prefix
2581
- addMiddleware(patternOrMiddleware, middleware, null);
945
+ // Auto-prefix pattern with basename so router-level middleware
946
+ // patterns are router-relative (e.g. "/users/*" matches "/app/users/*").
947
+ if (basename && typeof patternOrMiddleware === "string") {
948
+ const pattern = patternOrMiddleware;
949
+ const prefixed =
950
+ pattern === "/*" || pattern === "*"
951
+ ? `${basename}/*`
952
+ : `${basename}${pattern}`;
953
+ addMiddleware(prefixed, middleware, null);
954
+ } else {
955
+ addMiddleware(patternOrMiddleware, middleware, null);
956
+ }
2582
957
  return router;
2583
958
  },
2584
959
 
2585
960
  // Type-safe URL builder using merged route map
2586
961
  // Types are tracked through the builder chain via TRoutes parameter
2587
- // Falls back to static route names from the generated file (injected by Vite)
2588
- reverse: createReverse(mergedRouteMap, () => staticRouteNames),
962
+ // Seeded with static route names from the generated file (injected by Vite)
963
+ reverse: createReverse(mergedRouteMap),
2589
964
 
2590
965
  // Expose accumulated route map for typeof extraction
2591
966
  // Returns {} initially, but builder chain accumulates specific route types
@@ -2608,20 +983,74 @@ export function createRouter<TEnv = any>(
2608
983
  // Expose resolved theme configuration for NavigationProvider and MetaTags
2609
984
  themeConfig: resolvedThemeConfig,
2610
985
 
986
+ // Expose resolved cache profiles for per-request resolution
987
+ cacheProfiles: resolvedCacheProfiles,
988
+
989
+ // Expose prefetch cache settings
990
+ prefetchCacheControl,
991
+ prefetchCacheTTL,
992
+ prefetchCacheSize,
993
+ prefetchConcurrency,
994
+
995
+ // Expose the resolved rango state cookie name for the server-side writer
996
+ // (invalidateClientCache) and for shipping to the client in metadata.
997
+ resolvedStateCookieName,
998
+
2611
999
  // Expose warmup enabled flag for handler and client
2612
1000
  warmupEnabled,
2613
1001
 
1002
+ // Expose StrictMode flag for the initial-render payload metadata
1003
+ strictMode,
1004
+
1005
+ // Expose router-wide performance debugging for request-level metrics setup
1006
+ debugPerformance,
1007
+
1008
+ // Expose resolved span tracing for the handler (Cloudflare custom spans)
1009
+ tracing: resolvedTracing,
1010
+
2614
1011
  // Expose debug manifest flag for handler
2615
1012
  allowDebugManifest: allowDebugManifestOption,
2616
1013
 
1014
+ // Expose origin check configuration for handler (default: enabled)
1015
+ originCheck: originCheckOption ?? true,
1016
+
1017
+ // Expose SSR configuration for handler
1018
+ ssr: ssrOption,
1019
+
1020
+ // Expose resolved timeouts for RSC handler
1021
+ timeouts: resolvedTimeouts,
1022
+ onTimeout,
1023
+
2617
1024
  // Expose global middleware for RSC handler
2618
1025
  middleware: globalMiddleware,
2619
1026
 
2620
- match,
1027
+ match: (request: Request, input: RouterRequestInput<TEnv> = {}) => {
1028
+ const env = input.env ?? ({} as TEnv);
1029
+ return match(request, env);
1030
+ },
2621
1031
  matchForPrerender,
2622
- matchPartial,
2623
- matchError,
2624
- previewMatch,
1032
+ renderStaticSegment,
1033
+ matchPartial: (
1034
+ request: Request,
1035
+ input: RouterRequestInput<TEnv> = {},
1036
+ actionContext?: Parameters<typeof matchPartial>[2],
1037
+ ) => {
1038
+ const env = input.env ?? ({} as TEnv);
1039
+ return matchPartial(request, env, actionContext);
1040
+ },
1041
+ matchError: (
1042
+ request: Request,
1043
+ input: RouterRequestInput<TEnv> | undefined,
1044
+ error: unknown,
1045
+ segmentType?: Parameters<typeof matchError>[3],
1046
+ ) => {
1047
+ const env = input?.env ?? ({} as TEnv);
1048
+ return matchError(request, env, error, segmentType);
1049
+ },
1050
+ previewMatch: (request: Request, input: RouterRequestInput<TEnv> = {}) => {
1051
+ const env = input.env ?? ({} as TEnv);
1052
+ return previewMatch(request, env);
1053
+ },
2625
1054
 
2626
1055
  // Expose nonce provider for fetch
2627
1056
  nonce,
@@ -2637,93 +1066,67 @@ export function createRouter<TEnv = any>(
2637
1066
  // Expose source file for per-router type generation
2638
1067
  __sourceFile,
2639
1068
 
1069
+ // Expose basename for runtime manifest generation
1070
+ __basename: basename,
1071
+
1072
+ // Expose router-level boundary defaults for build-time clientChunks
1073
+ // discovery (so a "use client" default boundary lands in app-fallback).
1074
+ // These are createRouter options, never pushed onto EntryData.
1075
+ __defaultErrorBoundary: defaultErrorBoundary,
1076
+ __defaultNotFoundBoundary: defaultNotFoundBoundary,
1077
+ __notFound: notFound,
1078
+
2640
1079
  // RSC request handler (lazily created on first call)
2641
1080
  fetch: (() => {
2642
1081
  // Handler is created on first call and reused
2643
1082
  let handler:
2644
1083
  | ((
2645
1084
  request: Request,
2646
- env: TEnv & { ctx?: ExecutionContext },
1085
+ input: RouterRequestInput<TEnv>,
2647
1086
  ) => Promise<Response>)
2648
1087
  | null = null;
2649
1088
 
2650
- return async (
2651
- request: Request,
2652
- env: TEnv & { ctx?: ExecutionContext },
2653
- ) => {
1089
+ return async (request: Request, input: RouterRequestInput<TEnv> = {}) => {
2654
1090
  // Trigger lazy import of per-router manifest data before route matching.
2655
1091
  // No-op if data is already loaded or no loader is registered.
2656
1092
  await ensureRouterManifest(routerId);
2657
1093
  if (!handler) {
2658
1094
  // Lazy import deferred to first request to avoid dev mode issues
2659
1095
  const { createRSCHandler } = await import("./rsc/handler.js");
1096
+ // Cast: createRSCHandler receives `router as any`, which erases TEnv
1097
+ // and infers its handler as RouterRequestInput<unknown>. Re-narrow the
1098
+ // returned handler to RouterRequestInput<TEnv> so the call below stays
1099
+ // typed. (The handler already accepts (request, RouterRequestInput).)
2660
1100
  handler = createRSCHandler({
2661
1101
  router: router as any,
2662
1102
  cache,
2663
1103
  nonce,
2664
1104
  version,
2665
- });
1105
+ }) as (
1106
+ request: Request,
1107
+ input: RouterRequestInput<TEnv>,
1108
+ ) => Promise<Response>;
2666
1109
  }
2667
- return handler(request, env);
1110
+ return handler!(request, input);
2668
1111
  };
2669
1112
  })(),
2670
1113
 
2671
- // Debug utility for manifest inspection
2672
- async debugManifest(): Promise<SerializedManifest> {
2673
- const manifest = new Map<string, EntryData>();
2674
-
2675
- for (const entry of routesEntries) {
2676
- const Store = {
2677
- manifest,
2678
- namespace: `debug.M${entry.mountIndex}`,
2679
- parent: null as EntryData | null,
2680
- counters: {} as Record<string, number>,
2681
- mountIndex: entry.mountIndex,
2682
- patterns: new Map<string, string>(),
2683
- trailingSlash: new Map<string, TrailingSlashMode>(),
2684
- };
2685
-
2686
- await getContext().runWithStore(
2687
- Store,
2688
- `debug.M${entry.mountIndex}`,
2689
- null,
2690
- async () => {
2691
- const helpers = createRouteHelpers();
2692
-
2693
- // Wrap handler execution in root layout (same as loadManifest)
2694
- let promiseResult: Promise<any> | null = null;
2695
- helpers.layout(MapRootLayout, () => {
2696
- const result = entry.handler();
2697
- if (result instanceof Promise) {
2698
- promiseResult = result;
2699
- return [];
2700
- }
2701
- return result;
2702
- });
2703
-
2704
- if (promiseResult !== null) {
2705
- const load = await (promiseResult as Promise<any>);
2706
- if (load && typeof load === "object" && "default" in load) {
2707
- const useItems = load.default;
2708
- if (typeof useItems === "function") {
2709
- useItems(helpers);
2710
- }
2711
- }
2712
- }
2713
- },
2714
- );
2715
- }
1114
+ // Low-level route matching for request classification
1115
+ findMatch: (pathname: string, metricsStore?: any) =>
1116
+ findMatch(pathname, metricsStore),
2716
1117
 
2717
- return serializeManifest(manifest);
2718
- },
1118
+ // Debug utility for manifest inspection
1119
+ debugManifest: () => buildDebugManifest<TEnv>(routesEntries),
2719
1120
  };
2720
1121
 
2721
1122
  // Register router in the global registry for build-time discovery
2722
1123
  RouterRegistry.set(routerId, router);
2723
1124
 
2724
1125
  // If urls option was provided, auto-register them
2725
- if (urlsOption) {
2726
- return router.routes(urlsOption) as RSCRouter<TEnv, {}>;
1126
+ if (typeof urlsOption === "function") {
1127
+ return router.routes(urlsOption) as Rango<TEnv, {}>;
1128
+ } else if (urlsOption) {
1129
+ return router.routes(urlsOption) as Rango<TEnv, {}>;
2727
1130
  }
2728
1131
 
2729
1132
  return router;