@rangojs/router 0.0.0-experimental.10 → 0.0.0-experimental.100

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