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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (460) hide show
  1. package/AGENTS.md +17 -0
  2. package/README.md +432 -7
  3. package/dist/bin/rango.js +2073 -213
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +7258 -2714
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +140 -67
  8. package/skills/api-client/SKILL.md +211 -0
  9. package/skills/breadcrumbs/SKILL.md +329 -0
  10. package/skills/bundle-analysis/SKILL.md +159 -0
  11. package/skills/cache-guide/SKILL.md +487 -0
  12. package/skills/caching/SKILL.md +357 -25
  13. package/skills/comparison/SKILL.md +50 -0
  14. package/skills/comparison/agents/openai.yaml +4 -0
  15. package/skills/comparison/references/framework-comparison.md +837 -0
  16. package/skills/composability/SKILL.md +246 -0
  17. package/skills/css/SKILL.md +76 -0
  18. package/skills/debug-manifest/SKILL.md +16 -10
  19. package/skills/document-cache/SKILL.md +87 -62
  20. package/skills/fonts/SKILL.md +6 -4
  21. package/skills/handler-use/SKILL.md +364 -0
  22. package/skills/hooks/SKILL.md +557 -79
  23. package/skills/host-router/SKILL.md +320 -0
  24. package/skills/i18n/SKILL.md +276 -0
  25. package/skills/intercept/SKILL.md +207 -15
  26. package/skills/layout/SKILL.md +146 -6
  27. package/skills/links/SKILL.md +304 -25
  28. package/skills/loader/SKILL.md +616 -54
  29. package/skills/middleware/SKILL.md +217 -37
  30. package/skills/migrate-nextjs/SKILL.md +611 -0
  31. package/skills/migrate-react-router/SKILL.md +927 -0
  32. package/skills/mime-routes/SKILL.md +42 -11
  33. package/skills/observability/SKILL.md +194 -0
  34. package/skills/parallel/SKILL.md +284 -3
  35. package/skills/ppr/SKILL.md +426 -0
  36. package/skills/prerender/SKILL.md +437 -52
  37. package/skills/rango/SKILL.md +369 -22
  38. package/skills/react-compiler/SKILL.md +168 -0
  39. package/skills/response-routes/SKILL.md +263 -121
  40. package/skills/route/SKILL.md +350 -21
  41. package/skills/router-setup/SKILL.md +246 -33
  42. package/skills/scripts/SKILL.md +179 -0
  43. package/skills/server-actions/SKILL.md +775 -0
  44. package/skills/shell-manifest/SKILL.md +185 -0
  45. package/skills/streams-and-websockets/SKILL.md +283 -0
  46. package/skills/tailwind/SKILL.md +27 -3
  47. package/skills/testing/SKILL.md +126 -222
  48. package/skills/testing/bindings.md +103 -0
  49. package/skills/testing/cache-prerender.md +127 -0
  50. package/skills/testing/client-components.md +124 -0
  51. package/skills/testing/e2e-parity.md +125 -0
  52. package/skills/testing/flight.md +91 -0
  53. package/skills/testing/handles.md +131 -0
  54. package/skills/testing/loader.md +128 -0
  55. package/skills/testing/middleware.md +99 -0
  56. package/skills/testing/render-handler.md +122 -0
  57. package/skills/testing/response-routes.md +95 -0
  58. package/skills/testing/reverse-and-types.md +85 -0
  59. package/skills/testing/server-actions.md +107 -0
  60. package/skills/testing/server-tree.md +128 -0
  61. package/skills/testing/setup.md +123 -0
  62. package/skills/theme/SKILL.md +9 -8
  63. package/skills/typesafety/SKILL.md +532 -103
  64. package/skills/use-cache/SKILL.md +367 -0
  65. package/skills/vercel/SKILL.md +128 -0
  66. package/skills/view-transitions/SKILL.md +337 -0
  67. package/src/__augment-tests__/augment.ts +81 -0
  68. package/src/__augment-tests__/augmented.check.ts +116 -0
  69. package/src/__internal.ts +77 -44
  70. package/src/bin/rango.ts +312 -15
  71. package/src/browser/action-coordinator.ts +114 -0
  72. package/src/browser/action-fence.ts +47 -0
  73. package/src/browser/app-shell.ts +39 -0
  74. package/src/browser/app-version.ts +14 -0
  75. package/src/browser/connection-warmup.ts +134 -0
  76. package/src/browser/cookie-name.ts +140 -0
  77. package/src/browser/event-controller.ts +293 -202
  78. package/src/browser/history-state.ts +101 -0
  79. package/src/browser/index.ts +3 -3
  80. package/src/browser/intercept-utils.ts +52 -0
  81. package/src/browser/invalidate-client-cache.ts +52 -0
  82. package/src/browser/link-interceptor.ts +24 -4
  83. package/src/browser/logging.ts +11 -0
  84. package/src/browser/merge-segment-loaders.ts +20 -12
  85. package/src/browser/navigation-bridge.ts +385 -576
  86. package/src/browser/navigation-client.ts +245 -75
  87. package/src/browser/navigation-store-handle.ts +38 -0
  88. package/src/browser/navigation-store.ts +184 -118
  89. package/src/browser/navigation-transaction.ts +247 -0
  90. package/src/browser/network-error-handler.ts +88 -0
  91. package/src/browser/partial-update.ts +412 -364
  92. package/src/browser/prefetch/cache.ts +359 -0
  93. package/src/browser/prefetch/fetch.ts +452 -0
  94. package/src/browser/prefetch/observer.ts +65 -0
  95. package/src/browser/prefetch/policy.ts +48 -0
  96. package/src/browser/prefetch/queue.ts +209 -0
  97. package/src/browser/prefetch/resource-ready.ts +77 -0
  98. package/src/browser/rango-state.ts +194 -0
  99. package/src/browser/react/Link.tsx +275 -68
  100. package/src/browser/react/NavigationProvider.tsx +265 -109
  101. package/src/browser/react/ScrollRestoration.tsx +10 -6
  102. package/src/browser/react/context.ts +11 -0
  103. package/src/browser/react/filter-segment-order.ts +70 -0
  104. package/src/browser/react/index.ts +0 -48
  105. package/src/browser/react/location-state-shared.ts +272 -60
  106. package/src/browser/react/location-state.ts +90 -20
  107. package/src/browser/react/mount-context.ts +6 -1
  108. package/src/browser/react/nonce-context.ts +23 -0
  109. package/src/browser/react/shallow-equal.ts +27 -0
  110. package/src/browser/react/use-action.ts +35 -66
  111. package/src/browser/react/use-handle.ts +39 -126
  112. package/src/browser/react/use-href.tsx +8 -1
  113. package/src/browser/react/use-link-status.ts +39 -13
  114. package/src/browser/react/use-navigation.ts +53 -69
  115. package/src/browser/react/use-params.ts +75 -0
  116. package/src/browser/react/use-pathname.ts +47 -0
  117. package/src/browser/react/use-reverse.ts +106 -0
  118. package/src/browser/react/use-router.ts +98 -0
  119. package/src/browser/react/use-search-params.ts +51 -0
  120. package/src/browser/react/use-segments.ts +72 -99
  121. package/src/browser/response-adapter.ts +164 -0
  122. package/src/browser/rsc-router.tsx +300 -72
  123. package/src/browser/scroll-restoration.ts +138 -50
  124. package/src/browser/segment-reconciler.ts +243 -0
  125. package/src/browser/segment-structure-assert.ts +17 -1
  126. package/src/browser/server-action-bridge.ts +668 -613
  127. package/src/browser/types.ts +223 -51
  128. package/src/browser/validate-redirect-origin.ts +56 -0
  129. package/src/build/collect-fallback-refs.ts +107 -0
  130. package/src/build/generate-manifest.ts +252 -161
  131. package/src/build/generate-route-types.ts +41 -1038
  132. package/src/build/index.ts +12 -7
  133. package/src/build/prefix-tree-utils.ts +123 -0
  134. package/src/build/route-trie.ts +225 -42
  135. package/src/build/route-types/ast-helpers.ts +25 -0
  136. package/src/build/route-types/ast-route-extraction.ts +105 -0
  137. package/src/build/route-types/codegen.ts +113 -0
  138. package/src/build/route-types/include-resolution.ts +812 -0
  139. package/src/build/route-types/param-extraction.ts +51 -0
  140. package/src/build/route-types/per-module-writer.ts +144 -0
  141. package/src/build/route-types/router-processing.ts +695 -0
  142. package/src/build/route-types/scan-filter.ts +85 -0
  143. package/src/build/route-types/source-scan.ts +216 -0
  144. package/src/build/runtime-discovery.ts +223 -0
  145. package/src/cache/background-task.ts +34 -0
  146. package/src/cache/cache-error.ts +104 -0
  147. package/src/cache/cache-key-utils.ts +60 -0
  148. package/src/cache/cache-policy.ts +199 -0
  149. package/src/cache/cache-runtime.ts +525 -0
  150. package/src/cache/cache-scope.ts +298 -332
  151. package/src/cache/cache-tag.ts +103 -0
  152. package/src/cache/cf/cf-base64.ts +33 -0
  153. package/src/cache/cf/cf-cache-constants.ts +127 -0
  154. package/src/cache/cf/cf-cache-store.ts +2500 -158
  155. package/src/cache/cf/cf-cache-types.ts +349 -0
  156. package/src/cache/cf/cf-kv-utils.ts +46 -0
  157. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  158. package/src/cache/cf/index.ts +17 -17
  159. package/src/cache/document-cache.ts +199 -92
  160. package/src/cache/handle-capture.ts +81 -0
  161. package/src/cache/handle-snapshot.ts +111 -0
  162. package/src/cache/index.ts +29 -35
  163. package/src/cache/memory-segment-store.ts +363 -30
  164. package/src/cache/profile-registry.ts +88 -0
  165. package/src/cache/read-through-swr.ts +178 -0
  166. package/src/cache/segment-codec.ts +248 -0
  167. package/src/cache/shell-cache.ts +386 -0
  168. package/src/cache/tag-invalidation.ts +230 -0
  169. package/src/cache/taint.ts +153 -0
  170. package/src/cache/types.ts +156 -211
  171. package/src/cache/vercel/index.ts +11 -0
  172. package/src/cache/vercel/vercel-cache-store.ts +1102 -0
  173. package/src/client.rsc.tsx +43 -21
  174. package/src/client.tsx +131 -347
  175. package/src/cloudflare/index.ts +11 -0
  176. package/src/cloudflare/tracing.ts +109 -0
  177. package/src/component-utils.ts +23 -4
  178. package/src/components/DefaultDocument.tsx +13 -3
  179. package/src/context-var.ts +168 -0
  180. package/src/debug.ts +19 -9
  181. package/src/decode-loader-results.ts +52 -0
  182. package/src/defer.ts +185 -0
  183. package/src/deps/ssr.ts +0 -1
  184. package/src/encode-kv.ts +49 -0
  185. package/src/errors.ts +106 -10
  186. package/src/escape-script.ts +52 -0
  187. package/src/handle.ts +110 -35
  188. package/src/handles/MetaTags.tsx +83 -59
  189. package/src/handles/Scripts.tsx +183 -0
  190. package/src/handles/breadcrumbs.ts +93 -0
  191. package/src/handles/deferred-resolution.ts +127 -0
  192. package/src/handles/is-thenable.ts +18 -0
  193. package/src/handles/meta.ts +44 -53
  194. package/src/handles/script.ts +244 -0
  195. package/src/host/cookie-handler.ts +20 -65
  196. package/src/host/errors.ts +21 -30
  197. package/src/host/index.ts +13 -9
  198. package/src/host/pattern-matcher.ts +50 -79
  199. package/src/host/router.ts +151 -121
  200. package/src/host/testing.ts +45 -32
  201. package/src/host/types.ts +52 -11
  202. package/src/host/utils.ts +2 -2
  203. package/src/href-client.ts +192 -57
  204. package/src/index.rsc.ts +177 -35
  205. package/src/index.ts +255 -71
  206. package/src/internal-debug.ts +9 -2
  207. package/src/loader-store.ts +500 -0
  208. package/src/loader.rsc.ts +31 -99
  209. package/src/loader.ts +30 -12
  210. package/src/missing-id-error.ts +68 -0
  211. package/src/outlet-context.ts +1 -1
  212. package/src/outlet-provider.tsx +41 -0
  213. package/src/prerender/param-hash.ts +16 -14
  214. package/src/prerender/store.ts +121 -21
  215. package/src/prerender.ts +460 -26
  216. package/src/redirect-origin.ts +100 -0
  217. package/src/regex-escape.ts +8 -0
  218. package/src/render-error-thrower.tsx +20 -0
  219. package/src/response-utils.ts +62 -0
  220. package/src/reverse.ts +198 -128
  221. package/src/root-error-boundary.tsx +42 -48
  222. package/src/route-content-wrapper.tsx +22 -77
  223. package/src/route-definition/dsl-helpers.ts +1116 -0
  224. package/src/route-definition/helper-factories.ts +88 -0
  225. package/src/route-definition/helpers-types.ts +505 -0
  226. package/src/route-definition/index.ts +54 -0
  227. package/src/route-definition/redirect.ts +134 -0
  228. package/src/route-definition/resolve-handler-use.ts +160 -0
  229. package/src/route-definition/use-item-types.ts +29 -0
  230. package/src/route-definition.ts +1 -1481
  231. package/src/route-map-builder.ts +82 -144
  232. package/src/route-name.ts +53 -0
  233. package/src/route-types.ts +71 -45
  234. package/src/router/basename.ts +14 -0
  235. package/src/router/content-negotiation.ts +263 -0
  236. package/src/router/debug-manifest.ts +72 -0
  237. package/src/router/error-handling.ts +54 -27
  238. package/src/router/find-match.ts +245 -0
  239. package/src/router/handler-context.ts +377 -125
  240. package/src/router/instrument.ts +350 -0
  241. package/src/router/intercept-resolution.ts +59 -28
  242. package/src/router/lazy-includes.ts +254 -0
  243. package/src/router/loader-resolution.ts +421 -157
  244. package/src/router/logging.ts +106 -6
  245. package/src/router/manifest.ts +131 -57
  246. package/src/router/match-api.ts +167 -246
  247. package/src/router/match-context.ts +4 -24
  248. package/src/router/match-handlers.ts +440 -0
  249. package/src/router/match-middleware/background-revalidation.ts +117 -93
  250. package/src/router/match-middleware/cache-lookup.ts +297 -150
  251. package/src/router/match-middleware/cache-store.ts +123 -51
  252. package/src/router/match-middleware/intercept-resolution.ts +44 -43
  253. package/src/router/match-middleware/segment-resolution.ts +64 -22
  254. package/src/router/match-pipelines.ts +11 -87
  255. package/src/router/match-result.ts +121 -50
  256. package/src/router/metrics.ts +219 -28
  257. package/src/router/middleware-types.ts +93 -0
  258. package/src/router/middleware.ts +505 -441
  259. package/src/router/navigation-snapshot.ts +133 -0
  260. package/src/router/params-util.ts +23 -0
  261. package/src/router/parse-pattern.ts +115 -0
  262. package/src/router/pattern-matching.ts +311 -142
  263. package/src/router/prefetch-cache-ttl.ts +51 -0
  264. package/src/router/prefetch-limits.ts +37 -0
  265. package/src/router/prerender-match.ts +547 -0
  266. package/src/router/preview-match.ts +102 -0
  267. package/src/router/request-classification.ts +278 -0
  268. package/src/router/revalidation.ts +203 -62
  269. package/src/router/route-snapshot.ts +246 -0
  270. package/src/router/router-context.ts +45 -48
  271. package/src/router/router-interfaces.ts +554 -0
  272. package/src/router/router-options.ts +779 -0
  273. package/src/router/router-registry.ts +21 -0
  274. package/src/router/segment-resolution/fresh.ts +772 -0
  275. package/src/router/segment-resolution/helpers.ts +348 -0
  276. package/src/router/segment-resolution/loader-cache.ts +250 -0
  277. package/src/router/segment-resolution/loader-mask.ts +44 -0
  278. package/src/router/segment-resolution/revalidation.ts +1331 -0
  279. package/src/router/segment-resolution/static-store.ts +81 -0
  280. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  281. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  282. package/src/router/segment-resolution.ts +25 -1354
  283. package/src/router/segment-wrappers.ts +292 -0
  284. package/src/router/state-cookie-name.ts +33 -0
  285. package/src/router/substitute-pattern-params.ts +75 -0
  286. package/src/router/telemetry-otel.ts +261 -0
  287. package/src/router/telemetry.ts +377 -0
  288. package/src/router/timeout.ts +128 -0
  289. package/src/router/tracing.ts +206 -0
  290. package/src/router/trie-matching.ts +240 -61
  291. package/src/router/types.ts +23 -70
  292. package/src/router/url-params.ts +57 -0
  293. package/src/router.ts +781 -2378
  294. package/src/rsc/full-payload.ts +70 -0
  295. package/src/rsc/handler-context.ts +46 -0
  296. package/src/rsc/handler.ts +905 -1142
  297. package/src/rsc/helpers.ts +275 -19
  298. package/src/rsc/index.ts +2 -25
  299. package/src/rsc/json-route-result.ts +38 -0
  300. package/src/rsc/loader-fetch.ts +305 -0
  301. package/src/rsc/manifest-init.ts +77 -0
  302. package/src/rsc/nonce.ts +14 -0
  303. package/src/rsc/origin-guard.ts +155 -0
  304. package/src/rsc/progressive-enhancement.ts +502 -0
  305. package/src/rsc/redirect-guard.ts +99 -0
  306. package/src/rsc/response-cache-serve.ts +238 -0
  307. package/src/rsc/response-error.ts +104 -0
  308. package/src/rsc/response-route-handler.ts +257 -0
  309. package/src/rsc/rsc-rendering.ts +337 -0
  310. package/src/rsc/runtime-warnings.ts +55 -0
  311. package/src/rsc/server-action.ts +522 -0
  312. package/src/rsc/shell-capture.ts +439 -0
  313. package/src/rsc/ssr-setup.ts +144 -0
  314. package/src/rsc/transition-gate.ts +89 -0
  315. package/src/rsc/types.ts +95 -12
  316. package/src/runtime-env.ts +18 -0
  317. package/src/search-params.ts +99 -82
  318. package/src/segment-content-promise.ts +67 -0
  319. package/src/segment-loader-promise.ts +149 -0
  320. package/src/segment-system.tsx +349 -134
  321. package/src/serialize.ts +243 -0
  322. package/src/server/context.ts +452 -85
  323. package/src/server/cookie-parse.ts +32 -0
  324. package/src/server/cookie-store.ts +310 -0
  325. package/src/server/fetchable-loader-store.ts +11 -6
  326. package/src/server/handle-store.ts +123 -42
  327. package/src/server/live.ts +130 -0
  328. package/src/server/loader-registry.ts +51 -100
  329. package/src/server/request-context.ts +842 -157
  330. package/src/server.ts +15 -8
  331. package/src/ssr/index.tsx +412 -136
  332. package/src/ssr/ssr-root.tsx +228 -0
  333. package/src/static-handler.ts +45 -18
  334. package/src/testing/cache-status.ts +162 -0
  335. package/src/testing/collect-handle.ts +46 -0
  336. package/src/testing/dispatch.ts +701 -0
  337. package/src/testing/dom.entry.ts +22 -0
  338. package/src/testing/e2e/fixture.ts +188 -0
  339. package/src/testing/e2e/index.ts +128 -0
  340. package/src/testing/e2e/matchers.ts +35 -0
  341. package/src/testing/e2e/page-helpers.ts +272 -0
  342. package/src/testing/e2e/parity.ts +387 -0
  343. package/src/testing/e2e/server.ts +195 -0
  344. package/src/testing/flight-matchers.ts +97 -0
  345. package/src/testing/flight-normalize.ts +11 -0
  346. package/src/testing/flight-runtime.d.ts +57 -0
  347. package/src/testing/flight-tree.ts +682 -0
  348. package/src/testing/flight.entry.ts +52 -0
  349. package/src/testing/flight.ts +257 -0
  350. package/src/testing/generated-routes.ts +199 -0
  351. package/src/testing/index.ts +105 -0
  352. package/src/testing/internal/context.ts +371 -0
  353. package/src/testing/internal/flight-client-globals.ts +30 -0
  354. package/src/testing/internal/seed-vars.ts +54 -0
  355. package/src/testing/render-handler.ts +357 -0
  356. package/src/testing/render-route.tsx +584 -0
  357. package/src/testing/run-loader.ts +385 -0
  358. package/src/testing/run-middleware.ts +205 -0
  359. package/src/testing/run-transition-when.ts +164 -0
  360. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  361. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  362. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  363. package/src/testing/vitest-stubs/version.ts +5 -0
  364. package/src/testing/vitest.ts +305 -0
  365. package/src/theme/ThemeProvider.tsx +40 -72
  366. package/src/theme/ThemeScript.tsx +12 -14
  367. package/src/theme/constants.ts +57 -15
  368. package/src/theme/index.ts +3 -20
  369. package/src/theme/theme-context.ts +5 -35
  370. package/src/theme/theme-script.ts +43 -39
  371. package/src/theme/use-theme.ts +0 -3
  372. package/src/types/boundaries.ts +123 -0
  373. package/src/types/cache-types.ts +207 -0
  374. package/src/types/error-types.ts +132 -0
  375. package/src/types/global-namespace.ts +113 -0
  376. package/src/types/handler-context.ts +839 -0
  377. package/src/types/index.ts +81 -0
  378. package/src/types/loader-types.ts +212 -0
  379. package/src/types/request-scope.ts +112 -0
  380. package/src/types/route-config.ts +138 -0
  381. package/src/types/route-entry.ts +114 -0
  382. package/src/types/segments.ts +271 -0
  383. package/src/types.ts +1 -1795
  384. package/src/urls/include-helper.ts +162 -0
  385. package/src/urls/include-provider.ts +71 -0
  386. package/src/urls/index.ts +43 -0
  387. package/src/urls/path-helper-types.ts +413 -0
  388. package/src/urls/path-helper.ts +275 -0
  389. package/src/urls/pattern-types.ts +124 -0
  390. package/src/urls/response-types.ts +109 -0
  391. package/src/urls/type-extraction.ts +316 -0
  392. package/src/urls/urls-function.ts +80 -0
  393. package/src/urls.ts +1 -1341
  394. package/src/use-loader.tsx +406 -141
  395. package/src/vercel/index.ts +11 -0
  396. package/src/vercel/tracing.ts +88 -0
  397. package/src/vite/debug.ts +185 -0
  398. package/src/vite/discovery/bundle-postprocess.ts +182 -0
  399. package/src/vite/discovery/discover-routers.ts +389 -0
  400. package/src/vite/discovery/discovery-errors.ts +255 -0
  401. package/src/vite/discovery/gate-state.ts +171 -0
  402. package/src/vite/discovery/prerender-collection.ts +467 -0
  403. package/src/vite/discovery/route-types-writer.ts +214 -0
  404. package/src/vite/discovery/self-gen-tracking.ts +73 -0
  405. package/src/vite/discovery/state.ts +161 -0
  406. package/src/vite/discovery/virtual-module-codegen.ts +183 -0
  407. package/src/vite/index.ts +23 -2255
  408. package/src/vite/inject-client-debug.ts +36 -0
  409. package/src/vite/plugin-types.ts +303 -0
  410. package/src/vite/plugins/cjs-to-esm.ts +90 -0
  411. package/src/vite/plugins/client-ref-dedup.ts +120 -0
  412. package/src/vite/plugins/client-ref-hashing.ts +118 -0
  413. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  414. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  415. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  416. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +88 -110
  417. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +89 -79
  418. package/src/vite/plugins/expose-ids/export-analysis.ts +363 -0
  419. package/src/vite/plugins/expose-ids/handler-transform.ts +130 -0
  420. package/src/vite/plugins/expose-ids/loader-transform.ts +64 -0
  421. package/src/vite/plugins/expose-ids/router-transform.ts +199 -0
  422. package/src/vite/plugins/expose-ids/types.ts +45 -0
  423. package/src/vite/plugins/expose-internal-ids.ts +805 -0
  424. package/src/vite/plugins/performance-tracks.ts +89 -0
  425. package/src/vite/plugins/refresh-cmd.ts +127 -0
  426. package/src/vite/plugins/use-cache-transform.ts +313 -0
  427. package/src/vite/plugins/vercel-output.ts +384 -0
  428. package/src/vite/plugins/version-injector.ts +94 -0
  429. package/src/vite/plugins/version-plugin.ts +263 -0
  430. package/src/vite/plugins/virtual-entries.ts +234 -0
  431. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  432. package/src/vite/rango.ts +560 -0
  433. package/src/vite/router-discovery.ts +1638 -0
  434. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +200 -37
  435. package/src/vite/utils/banner.ts +36 -0
  436. package/src/vite/utils/bundle-analysis.ts +132 -0
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +15 -0
  441. package/src/vite/utils/package-resolution.ts +89 -0
  442. package/src/vite/utils/prerender-utils.ts +249 -0
  443. package/src/vite/utils/shared-utils.ts +269 -0
  444. package/CLAUDE.md +0 -43
  445. package/dist/vite/index.named-routes.gen.ts +0 -103
  446. package/src/browser/lru-cache.ts +0 -69
  447. package/src/browser/react/use-client-cache.ts +0 -56
  448. package/src/browser/request-controller.ts +0 -164
  449. package/src/browser/shallow.ts +0 -35
  450. package/src/cache/memory-store.ts +0 -253
  451. package/src/handles/index.ts +0 -6
  452. package/src/href-context.ts +0 -33
  453. package/src/network-error-thrower.tsx +0 -21
  454. package/src/router.gen.ts +0 -6
  455. package/src/static-handler.gen.ts +0 -5
  456. package/src/urls.gen.ts +0 -8
  457. package/src/vite/expose-internal-ids.ts +0 -1167
  458. package/src/vite/package-resolution.ts +0 -125
  459. package/src/vite/virtual-entries.ts +0 -114
  460. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -0,0 +1,1638 @@
1
+ /**
2
+ * Router Discovery Plugin
3
+ *
4
+ * Vite plugin that discovers router instances at dev/build time via the RSC
5
+ * environment. Delegates to extracted modules for discovery, route types
6
+ * generation, virtual module codegen, and bundle post-processing.
7
+ */
8
+
9
+ import type { Plugin } from "vite";
10
+ import { createServer as createViteServer } from "vite";
11
+ import { resolve } from "node:path";
12
+ import { readFileSync } from "node:fs";
13
+ import { createRequire, register } from "node:module";
14
+ import { pathToFileURL } from "node:url";
15
+ import {
16
+ formatNestedRouterConflictError,
17
+ findNestedRouterConflict,
18
+ findRouterFiles,
19
+ createScanFilter,
20
+ } from "../build/generate-route-types.js";
21
+ import { firstCodeMatchIndex } from "../build/route-types/source-scan.js";
22
+ import { injectClientDebugFlag } from "./inject-client-debug.js";
23
+ import { createVersionPlugin } from "./plugins/version-plugin.js";
24
+ import { createVirtualStubPlugin } from "./plugins/virtual-stub-plugin.js";
25
+ import {
26
+ BUILD_ENV_GLOBAL_KEY,
27
+ createCloudflareProtocolStubPlugin,
28
+ } from "./plugins/cloudflare-protocol-stub.js";
29
+ import {
30
+ exposeInternalIds,
31
+ exposeRouterId,
32
+ } from "./plugins/expose-internal-ids.js";
33
+ import { hashClientRefs } from "./plugins/client-ref-hashing.js";
34
+ import { extractHandlerExportsFromChunk } from "./utils/bundle-analysis.js";
35
+ import {
36
+ createDiscoveryState,
37
+ VIRTUAL_ROUTES_MANIFEST_ID,
38
+ type DiscoveryState,
39
+ type PluginOptions,
40
+ } from "./discovery/state.js";
41
+ import {
42
+ consumeSelfGenWrite,
43
+ peekSelfGenWrite,
44
+ } from "./discovery/self-gen-tracking.js";
45
+ import { discoverRouters } from "./discovery/discover-routers.js";
46
+ import { describeDiscoveryFailure } from "./discovery/discovery-errors.js";
47
+ import {
48
+ writeCombinedRouteTypesWithTracking,
49
+ writeRouteTypesFiles,
50
+ supplementGenFilesWithRuntimeRoutes,
51
+ } from "./discovery/route-types-writer.js";
52
+ import {
53
+ generateRoutesManifestModule,
54
+ generatePerRouterModule,
55
+ } from "./discovery/virtual-module-codegen.js";
56
+ import { postprocessBundle } from "./discovery/bundle-postprocess.js";
57
+ import { createDiscoveryGate } from "./discovery/gate-state.js";
58
+ import { resetStagedBuildAssets } from "./utils/prerender-utils.js";
59
+ import { resolveRscEntryFromConfig } from "./utils/shared-utils.js";
60
+ import {
61
+ pickForwardedRunnerConfig,
62
+ selectForwardableResolvePlugins,
63
+ } from "./utils/forward-user-plugins.js";
64
+ import { createRangoDebugger, timed, timedSync, NS } from "./debug.js";
65
+
66
+ const debugDiscovery = createRangoDebugger(NS.discovery);
67
+ const debugRoutes = createRangoDebugger(NS.routes);
68
+ const debugBuild = createRangoDebugger(NS.build);
69
+ const debugDev = createRangoDebugger(NS.dev);
70
+
71
+ export { VIRTUAL_ROUTES_MANIFEST_ID };
72
+
73
+ // ============================================================================
74
+ // Node ESM Loader Hook Registration
75
+ // ============================================================================
76
+
77
+ /**
78
+ * Registers a Node ESM loader hook that resolves `cloudflare:*` specifiers
79
+ * to a data: URL stub. Defense-in-depth alongside the Vite transform in
80
+ * `cloudflare-protocol-stub.ts`:
81
+ *
82
+ * - The Vite transform catches `cloudflare:*` imports in modules that flow
83
+ * through Vite's plugin pipeline. That's the vast majority of cases.
84
+ * - The Node loader catches imports in modules that Vite/Rollup externalize
85
+ * (e.g. the `partyserver` package, which has a top-level
86
+ * `import { DurableObject, env } from "cloudflare:workers"` and ships
87
+ * shapes plugin-rsc marks as external). Externalized modules are loaded
88
+ * via Node's native ESM loader, which rejects URL schemes.
89
+ *
90
+ * Registration is process-global and one-shot. The hook only intercepts
91
+ * `cloudflare:*` specifiers; everything else passes through via
92
+ * `nextResolve()`. It runs in a separate worker thread (Node ESM loader
93
+ * architecture), so it can't read the `globalThis[BUILD_ENV_GLOBAL_KEY]`
94
+ * bridge that the Vite transform uses — the stubs served here always
95
+ * return `env = {}`. That's fine because externalized libraries don't
96
+ * typically access `env` at module top level; user source (where real
97
+ * `env` matters at build time) flows through the Vite transform.
98
+ */
99
+ let loaderHookRegistered = false;
100
+ function ensureCloudflareProtocolLoaderRegistered(): void {
101
+ if (loaderHookRegistered) return;
102
+ loaderHookRegistered = true;
103
+ try {
104
+ register(
105
+ new URL("./plugins/cloudflare-protocol-loader-hook.mjs", import.meta.url),
106
+ );
107
+ } catch (err: any) {
108
+ // register() requires Node 18.19+ / 20.6+. Older Node still has the
109
+ // Vite transform as primary defense.
110
+ console.warn(
111
+ `[rango] Could not register Node ESM loader hook for cloudflare:* imports (${err?.message ?? err}). Falling back to Vite transform only.`,
112
+ );
113
+ }
114
+ }
115
+
116
+ // ============================================================================
117
+ // Temp Server Factory
118
+ // ============================================================================
119
+
120
+ /**
121
+ * Create a minimal Vite server for router discovery.
122
+ *
123
+ * Both dev-mode prerender and build-mode discovery need a temp RSC server
124
+ * to import user router files via module runner. This factory centralizes
125
+ * the shared config and the mode-specific differences:
126
+ * - Dev: path-based IDs (no forceBuild), separate cacheDir
127
+ * - Build: hashed IDs (forceBuild), hashClientRefs for production bundles
128
+ *
129
+ * Returns the ViteDevServer instance. Callers access .environments.rsc as needed.
130
+ */
131
+ async function createTempRscServer(
132
+ state: DiscoveryState,
133
+ options: { forceBuild?: boolean; cacheDir?: string } = {},
134
+ ) {
135
+ // Install the Node ESM loader hook before any module evaluation so
136
+ // `cloudflare:*` specifiers in externalized/loader-delegated modules
137
+ // (e.g. packages plugin-rsc marks as external) resolve to stubs
138
+ // instead of crashing Node's native loader.
139
+ ensureCloudflareProtocolLoaderRegistered();
140
+ const { default: rsc } = await import("@vitejs/plugin-rsc");
141
+ // Mirror the user's resolution config + plugins so discovery (and the
142
+ // prerender/static rendering that shares this runner) resolves modules the
143
+ // same way the real environment does. Falls back to the legacy alias-only
144
+ // behavior if configResolved hasn't populated the parity slice yet.
145
+ const runnerConfig = state.userRunnerConfig;
146
+ const resolveConfig = runnerConfig?.resolve ?? {
147
+ alias: state.userResolveAlias,
148
+ };
149
+ const oxcConfig = runnerConfig?.oxc ?? {
150
+ jsx: { runtime: "automatic", importSource: "react" },
151
+ };
152
+ return createViteServer({
153
+ root: state.projectRoot,
154
+ configFile: false,
155
+ server: { middlewareMode: true },
156
+ appType: "custom",
157
+ logLevel: "silent",
158
+ resolve: resolveConfig,
159
+ ...(runnerConfig?.define ? { define: runnerConfig.define } : {}),
160
+ oxc: oxcConfig as any,
161
+ ...(options.cacheDir && { cacheDir: options.cacheDir }),
162
+ plugins: [
163
+ rsc({
164
+ entries: {
165
+ client: "virtual:entry-client",
166
+ ssr: "virtual:entry-ssr",
167
+ rsc: state.resolvedEntryPath!,
168
+ },
169
+ }),
170
+ // hashClientRefs only in build mode — production bundles need hashed refs
171
+ ...(options.forceBuild ? [hashClientRefs(state.projectRoot)] : []),
172
+ createVersionPlugin(),
173
+ createVirtualStubPlugin(),
174
+ createCloudflareProtocolStubPlugin(),
175
+ // Dev prerender must use dev-mode IDs (path-based) to match the workerd
176
+ // runtime. forceBuild produces hashed IDs for production bundle consistency.
177
+ exposeInternalIds(options.forceBuild ? { forceBuild: true } : undefined),
178
+ exposeRouterId(),
179
+ // Forwarded user resolution plugins (e.g. vite-tsconfig-paths). Stripped
180
+ // to resolveId/load and placed last so framework resolution runs first;
181
+ // Vite re-sorts by `enforce`, so `enforce: "pre"` resolvers still lead.
182
+ ...state.userResolvePlugins,
183
+ ],
184
+ });
185
+ }
186
+
187
+ // ============================================================================
188
+ // Build-Time Env Resolution
189
+ // ============================================================================
190
+
191
+ import type {
192
+ BuildEnvOption,
193
+ BuildEnvFactoryContext,
194
+ BuildEnvResult,
195
+ } from "./plugin-types.js";
196
+
197
+ /**
198
+ * Resolve the buildEnv option into a concrete { env, dispose? } result.
199
+ * Handles all four input shapes: false, "auto", factory, plain object.
200
+ */
201
+ async function resolveBuildEnv(
202
+ option: BuildEnvOption | undefined,
203
+ factoryCtx: BuildEnvFactoryContext,
204
+ ): Promise<BuildEnvResult | null> {
205
+ if (!option) return null;
206
+
207
+ if (option === "auto") {
208
+ if (factoryCtx.preset !== "cloudflare") {
209
+ throw new Error(
210
+ '[rango] buildEnv: "auto" is only supported with preset: "cloudflare". ' +
211
+ "Use a factory function or plain object for other presets.",
212
+ );
213
+ }
214
+ try {
215
+ // Resolve wrangler from the user's project root (not the router package)
216
+ const userRequire = createRequire(
217
+ resolve(factoryCtx.root, "package.json"),
218
+ );
219
+ const wranglerPath = userRequire.resolve("wrangler");
220
+ const { getPlatformProxy } = (await import(
221
+ pathToFileURL(wranglerPath).href
222
+ )) as {
223
+ getPlatformProxy: (opts?: any) => Promise<any>;
224
+ };
225
+ const proxy = await getPlatformProxy();
226
+ return {
227
+ env: proxy.env as Record<string, unknown>,
228
+ dispose: proxy.dispose,
229
+ };
230
+ } catch (err: any) {
231
+ throw new Error(
232
+ '[rango] buildEnv: "auto" requires wrangler to be installed.\n' +
233
+ `Install it with: pnpm add -D wrangler\n${err.message}`,
234
+ );
235
+ }
236
+ }
237
+
238
+ if (typeof option === "function") {
239
+ return await option(factoryCtx);
240
+ }
241
+
242
+ // Plain object
243
+ return { env: option };
244
+ }
245
+
246
+ /**
247
+ * Acquire build-time env bindings and store on discovery state.
248
+ * Returns true if env was acquired, false if buildEnv is disabled.
249
+ */
250
+ async function acquireBuildEnv(
251
+ s: DiscoveryState,
252
+ command: "serve" | "build",
253
+ mode: string,
254
+ ): Promise<boolean> {
255
+ const option = s.opts?.buildEnv;
256
+ if (!option) return false;
257
+
258
+ const result = await resolveBuildEnv(option, {
259
+ root: s.projectRoot,
260
+ mode,
261
+ command,
262
+ preset: s.opts?.preset ?? "node",
263
+ });
264
+ if (!result) return false;
265
+
266
+ s.resolvedBuildEnv = result.env;
267
+ s.buildEnvDispose = result.dispose ?? null;
268
+ // Bridge the resolved env into `cloudflare:workers`'s stubbed `env`
269
+ // export so user code that does `import { env } from "cloudflare:workers"`
270
+ // sees the real bindings proxy during discovery + prerender instead of
271
+ // an empty object. The stub reads this global at module-evaluation time.
272
+ (globalThis as Record<string, unknown>)[BUILD_ENV_GLOBAL_KEY] = result.env;
273
+ return true;
274
+ }
275
+
276
+ /**
277
+ * Release build-time env resources and clear state.
278
+ */
279
+ async function releaseBuildEnv(s: DiscoveryState): Promise<void> {
280
+ if (s.buildEnvDispose) {
281
+ try {
282
+ await s.buildEnvDispose();
283
+ } catch (err: any) {
284
+ console.warn(`[rango] buildEnv dispose failed: ${err.message}`);
285
+ }
286
+ s.buildEnvDispose = null;
287
+ }
288
+ s.resolvedBuildEnv = undefined;
289
+ delete (globalThis as Record<string, unknown>)[BUILD_ENV_GLOBAL_KEY];
290
+ }
291
+
292
+ /**
293
+ * Plugin that discovers router instances at dev/build time via the RSC environment.
294
+ *
295
+ * Uses `server.environments.rsc.runner.import()` to load the user's router file
296
+ * with full TS/TSX compilation. This triggers `createRouter()` which populates
297
+ * the `RouterRegistry`. The plugin then generates manifests for each router.
298
+ *
299
+ * In dev mode, this runs in `configureServer` (post-middleware setup).
300
+ * In build mode, this will run in `buildStart` (future).
301
+ *
302
+ * @internal
303
+ */
304
+ export function createRouterDiscoveryPlugin(
305
+ entryPath: string | undefined,
306
+ opts?: PluginOptions,
307
+ ): Plugin {
308
+ const s = createDiscoveryState(entryPath, opts);
309
+ let viteCommand: "serve" | "build" = "build";
310
+ let viteMode = "production";
311
+
312
+ return {
313
+ name: "@rangojs/router:discovery",
314
+
315
+ // Make INTERNAL_RANGO_DEBUG reach the CLIENT debug logs by just setting the
316
+ // env var. See injectClientDebugFlag: bakes the resolved flag into the
317
+ // internal-debug module so FE debug no longer depends on Vite delivering the
318
+ // `__RANGO_DEBUG__` define to the client (which it does only as an injected
319
+ // global whose presence varies across consumer setups). Runs in dev and build.
320
+ transform(_code, id) {
321
+ return injectClientDebugFlag(id);
322
+ },
323
+
324
+ configResolved(config) {
325
+ s.projectRoot = config.root;
326
+ // Compile the optional discovery scan filter (glob include/exclude) now
327
+ // that the project root is known. findRouterFiles() below — and the
328
+ // build/HMR rediscovery paths — honor s.scanFilter.
329
+ s.scanFilter = opts?.discovery
330
+ ? createScanFilter(s.projectRoot, opts.discovery)
331
+ : undefined;
332
+ s.isBuildMode = config.command === "build";
333
+ viteCommand = config.command as "serve" | "build";
334
+ viteMode = config.mode;
335
+ // Capture user's resolve aliases for the temp server
336
+ s.userResolveAlias = config.resolve.alias;
337
+ // Capture the data-only resolution config (resolve.*, define, oxc) and
338
+ // the user's resolution plugins (resolveId/load) so the discovery temp
339
+ // server resolves modules the same way the real environment does.
340
+ // Without this, both flavors of user resolution are absent during
341
+ // discovery/prerender/static rendering even though they apply at request
342
+ // time: third-party resolvers (e.g. vite-tsconfig-paths, forwarded as
343
+ // plugins) and Vite 8's native resolve.tsconfigPaths (forwarded in the
344
+ // data slice). See utils/forward-user-plugins.ts.
345
+ s.userRunnerConfig = pickForwardedRunnerConfig(config);
346
+ s.userResolvePlugins = selectForwardableResolvePlugins(
347
+ config.plugins as any,
348
+ );
349
+ // Node preset: pick up auto-discovered router path from the config() hook.
350
+ // The auto-discover plugin runs in config() using Vite's resolved root,
351
+ // populating the mutable ref before configResolved fires.
352
+ if (!s.resolvedEntryPath && opts?.routerPathRef?.path) {
353
+ s.resolvedEntryPath = opts.routerPathRef.path;
354
+ }
355
+ // Cloudflare preset: entry comes from the resolved RSC env config.
356
+ if (!s.resolvedEntryPath) {
357
+ const entry = resolveRscEntryFromConfig(config);
358
+ if (entry) s.resolvedEntryPath = entry;
359
+ }
360
+ // Generate combined named-routes.gen.ts from static source parsing.
361
+ // Runs before the dev server starts so the gen file exists immediately for IDE.
362
+ // In build mode, the runtime discovery in buildStart produces the definitive
363
+ // named-routes.gen.ts (including dynamically generated routes).
364
+ // preserveIfLarger prevents overwriting a previously generated complete
365
+ // file with a partial one.
366
+ if (opts?.staticRouteTypesGeneration !== false) {
367
+ s.cachedRouterFiles = findRouterFiles(s.projectRoot, s.scanFilter);
368
+ writeCombinedRouteTypesWithTracking(s, { preserveIfLarger: true });
369
+ }
370
+ // Resolve prerenderHandlerModules and staticHandlerModules from the consolidated IDs plugin's API.
371
+ if (opts?.enableBuildPrerender) {
372
+ const idsPlugin = config.plugins.find(
373
+ (p: any) => p.name === "@rangojs/router:expose-internal-ids",
374
+ );
375
+ s.resolvedPrerenderModules = (
376
+ idsPlugin?.api as any
377
+ )?.prerenderHandlerModules;
378
+ s.resolvedStaticModules = (idsPlugin?.api as any)?.staticHandlerModules;
379
+ }
380
+ },
381
+
382
+ // Dev mode: discover routers and populate manifest in memory.
383
+ // Skipped in build mode (buildStart handles it).
384
+ configureServer(server) {
385
+ if (s.isBuildMode) return;
386
+ // Skip if this is a temp server created by buildStart
387
+ if ((globalThis as any).__rscRouterDiscoveryActive) return;
388
+ s.devServer = server;
389
+
390
+ // Discovery promise that the handler can await if requests arrive
391
+ // before discovery completes
392
+ let resolveDiscovery: () => void;
393
+ const discoveryPromise = new Promise<void>((resolve) => {
394
+ resolveDiscovery = resolve;
395
+ });
396
+
397
+ // Manifest-readiness gate + rediscovery scheduler.
398
+ // The virtual:rsc-router/routes-manifest module's `load()` hook
399
+ // awaits `s.discoveryDone`; the gate is reset on each discovery
400
+ // cycle so workerd's HMR reloads block until the new gen file is
401
+ // written. State machine + transitions are extracted into
402
+ // ./discovery/gate-state.ts and unit-tested there — see the
403
+ // module's JSDoc for the four-flag contract.
404
+ const gate = createDiscoveryGate(s, debugDiscovery);
405
+ const beginDiscoveryGate = gate.beginGate;
406
+ const resolveDiscoveryGate = gate.resolveGate;
407
+
408
+ // Compute dev server origin from resolved URLs (preferred) or config port (fallback).
409
+ // Called after discovery (or in the load hook) when the server may be listening.
410
+ const getDevServerOrigin = () =>
411
+ server.resolvedUrls?.local?.[0]?.replace(/\/$/, "") ||
412
+ `http://localhost:${server.config.server.port || 5173}`;
413
+
414
+ // Shared temp server for Cloudflare dev (no module runner in workerd).
415
+ // Used by both discover() (route type generation) and the prerender
416
+ // middleware (on-demand prerender evaluation). Created lazily, closed on
417
+ // server shutdown.
418
+ let prerenderTempServer: any = null;
419
+ let prerenderNodeRegistry: Map<string, any> | null = null;
420
+
421
+ // Clean up the temporary server and build env when the dev server shuts down
422
+ server.httpServer?.on("close", () => {
423
+ if (prerenderTempServer) {
424
+ prerenderTempServer.close().catch(() => {});
425
+ prerenderTempServer = null;
426
+ }
427
+ releaseBuildEnv(s).catch(() => {});
428
+ });
429
+
430
+ // Mirror the build-path contract (the buildStart hook below, which sets
431
+ // __rscRouterDiscoveryActive before running user modules):
432
+ // set __rscRouterDiscoveryActive before running user modules so any
433
+ // module-level router.reverse() calls return a placeholder instead
434
+ // of throwing. The temp Vite server's module runner has its own
435
+ // module context; the flag must be on globalThis to cross that
436
+ // boundary. Cleared in finally so the dev request handlers run with
437
+ // strict reverse() semantics afterwards.
438
+ async function importEntryAndRegistry(tempRscEnv: any): Promise<void> {
439
+ const flagAlreadySet = !!(globalThis as any).__rscRouterDiscoveryActive;
440
+ if (!flagAlreadySet) {
441
+ (globalThis as any).__rscRouterDiscoveryActive = true;
442
+ }
443
+ try {
444
+ debugDiscovery?.(
445
+ "importEntryAndRegistry: importing entry (flag=%s)",
446
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
447
+ );
448
+ await tempRscEnv.runner.import(s.resolvedEntryPath!);
449
+ debugDiscovery?.(
450
+ "importEntryAndRegistry: entry import OK, fetching RouterRegistry",
451
+ );
452
+ const serverMod = await tempRscEnv.runner.import(
453
+ "@rangojs/router/server",
454
+ );
455
+ prerenderNodeRegistry = serverMod.RouterRegistry;
456
+ debugDiscovery?.(
457
+ "importEntryAndRegistry: registry size=%d",
458
+ prerenderNodeRegistry?.size ?? 0,
459
+ );
460
+ } finally {
461
+ if (!flagAlreadySet) {
462
+ delete (globalThis as any).__rscRouterDiscoveryActive;
463
+ debugDiscovery?.(
464
+ "importEntryAndRegistry: cleared __rscRouterDiscoveryActive",
465
+ );
466
+ }
467
+ }
468
+ }
469
+
470
+ async function getOrCreateTempServer(): Promise<any | null> {
471
+ // Reuse path: if a temp server is already alive, prefer reusing
472
+ // it over orphaning the existing instance and spinning up a new
473
+ // one. This handles two cases:
474
+ //
475
+ // 1. Steady-state cache hit (cold-start completed, registry
476
+ // cached) — return the env immediately.
477
+ // 2. Recovery from a failed refresh: refreshTempRscEnv() may
478
+ // have invalidated and nulled the registry, then thrown
479
+ // during importEntryAndRegistry. Without reuse, the next
480
+ // call would `createTempRscServer` and overwrite the
481
+ // handle, leaking the previous server. Try to re-import on
482
+ // the existing runner first; only if THAT fails do we
483
+ // close the orphan and create new.
484
+ if (prerenderTempServer) {
485
+ const existingEnv = (prerenderTempServer.environments as any)?.rsc;
486
+ if (existingEnv?.runner) {
487
+ if (prerenderNodeRegistry) {
488
+ debugDiscovery?.(
489
+ "getOrCreateTempServer: cached temp runner reused",
490
+ );
491
+ return existingEnv;
492
+ }
493
+ // Server alive but registry missing — likely after a prior
494
+ // refresh's invalidate + import threw. Try to re-import.
495
+ debugDiscovery?.(
496
+ "getOrCreateTempServer: server alive but registry missing — re-importing",
497
+ );
498
+ try {
499
+ await importEntryAndRegistry(existingEnv);
500
+ return existingEnv;
501
+ } catch (err: any) {
502
+ debugDiscovery?.(
503
+ "getOrCreateTempServer: reuse import failed (%s) — closing orphan and creating fresh",
504
+ err?.message ?? String(err),
505
+ );
506
+ await prerenderTempServer.close().catch(() => {});
507
+ prerenderTempServer = null;
508
+ prerenderNodeRegistry = null;
509
+ // Fall through to create-new path below.
510
+ }
511
+ } else {
512
+ // Server reference exists but its rsc env is unhealthy
513
+ // (no runner). Close and recreate.
514
+ debugDiscovery?.(
515
+ "getOrCreateTempServer: existing server has no rsc.runner — closing and recreating",
516
+ );
517
+ await prerenderTempServer.close().catch(() => {});
518
+ prerenderTempServer = null;
519
+ prerenderNodeRegistry = null;
520
+ }
521
+ }
522
+
523
+ // Create path: no existing temp server (or just nullified above).
524
+ debugDiscovery?.(
525
+ "getOrCreateTempServer: creating new temp server, entry=%s",
526
+ s.resolvedEntryPath ?? "(unset)",
527
+ );
528
+ try {
529
+ prerenderTempServer = await createTempRscServer(s, {
530
+ cacheDir: "node_modules/.vite_prerender",
531
+ });
532
+
533
+ const tempRscEnv = (prerenderTempServer.environments as any)?.rsc;
534
+ if (tempRscEnv?.runner) {
535
+ await importEntryAndRegistry(tempRscEnv);
536
+ return tempRscEnv;
537
+ }
538
+ debugDiscovery?.(
539
+ "getOrCreateTempServer: tempRscEnv.runner unavailable",
540
+ );
541
+ } catch (err: any) {
542
+ debugDiscovery?.(
543
+ "getOrCreateTempServer: FAILED message=%s",
544
+ err.message,
545
+ );
546
+ console.warn(`[rango] Failed to create temp runner: ${err.message}`);
547
+ }
548
+ // Reached only on failure (runner unavailable, or create/import threw
549
+ // AFTER the server was created). Close the just-created server so a
550
+ // failed discovery does not leak it until the next call or dev shutdown,
551
+ // and null the refs so the reuse path above starts clean. Mirrors the
552
+ // close pattern used when an existing server is discarded (above).
553
+ await prerenderTempServer?.close().catch(() => {});
554
+ prerenderTempServer = null;
555
+ prerenderNodeRegistry = null;
556
+ return null;
557
+ }
558
+
559
+ // Clear the package-level singleton registries that survive a Vite
560
+ // moduleGraph.invalidateAll(). createRouter() / createHostRouter()
561
+ // call .set(id, ...) on these Maps; for "router removed" or
562
+ // "router id changed" edits, the OLD entry would persist after
563
+ // re-import without an explicit .clear(), leaving ghost routes
564
+ // in discoverRouters' output.
565
+ //
566
+ // We import the same module the runner imports, so the .clear()
567
+ // here mutates the same Map the freshly re-imported entry will
568
+ // populate.
569
+ async function clearTempRegistries(tempRscEnv: any): Promise<void> {
570
+ try {
571
+ const serverMod = await tempRscEnv.runner.import(
572
+ "@rangojs/router/server",
573
+ );
574
+ if (typeof serverMod?.RouterRegistry?.clear === "function") {
575
+ serverMod.RouterRegistry.clear();
576
+ }
577
+ if (typeof serverMod?.HostRouterRegistry?.clear === "function") {
578
+ serverMod.HostRouterRegistry.clear();
579
+ }
580
+ debugDiscovery?.(
581
+ "clearTempRegistries: cleared RouterRegistry + HostRouterRegistry",
582
+ );
583
+ } catch (err: any) {
584
+ // Non-fatal: if the import fails here, importEntryAndRegistry
585
+ // below will fail loudly with the same root cause and the
586
+ // caller will surface it.
587
+ debugDiscovery?.(
588
+ "clearTempRegistries: import @rangojs/router/server failed (%s)",
589
+ err?.message ?? String(err),
590
+ );
591
+ }
592
+ }
593
+
594
+ // HMR refresh: keep the temp Vite server alive across HMR cycles and
595
+ // invalidate its module graph instead of close+recreate. Closing the
596
+ // temp server during workerd's first post-cold-start module-fetch
597
+ // window disrupted the main dev server's transport — the user-visible
598
+ // symptom was a `transport was disconnected, cannot call "fetchModule"`
599
+ // error on the first urls.tsx edit (workerd's cache was cold, so its
600
+ // eval was still in flight when our close() ran). Module-graph
601
+ // invalidation is the architecturally cleaner refresh: same Vite
602
+ // instance, same transport, fresh source.
603
+ //
604
+ // Falls back to close+recreate when neither the env-level nor
605
+ // server-level moduleGraph exposes invalidateAll() (defensive — Vite
606
+ // versions / preset configurations may differ in which graph carries
607
+ // the module-runner cache).
608
+ async function refreshTempRscEnv(): Promise<any | null> {
609
+ let tempRscEnv = await getOrCreateTempServer();
610
+ if (!tempRscEnv) return null;
611
+
612
+ // Module-runner cache is on the per-environment graph in Vite 6+;
613
+ // older / non-environments setups carry it on the server graph.
614
+ // Try env first, server second.
615
+ const envGraph = (tempRscEnv as any).moduleGraph;
616
+ const serverGraph = (prerenderTempServer as any)?.moduleGraph;
617
+ const target = envGraph?.invalidateAll
618
+ ? envGraph
619
+ : serverGraph?.invalidateAll
620
+ ? serverGraph
621
+ : null;
622
+
623
+ if (!target) {
624
+ // No invalidate method available — fall back to close+recreate.
625
+ // This preserves the previous behavior in case a Vite version
626
+ // doesn't expose invalidateAll on either graph.
627
+ debugDiscovery?.(
628
+ "refreshTempRscEnv: invalidateAll unavailable on env+server graphs, falling back to close+recreate",
629
+ );
630
+ if (prerenderTempServer) {
631
+ await prerenderTempServer.close().catch(() => {});
632
+ prerenderTempServer = null;
633
+ prerenderNodeRegistry = null;
634
+ }
635
+ return await getOrCreateTempServer();
636
+ }
637
+
638
+ debugDiscovery?.(
639
+ "refreshTempRscEnv: invalidating module graph (%s)",
640
+ envGraph?.invalidateAll ? "env" : "server",
641
+ );
642
+ target.invalidateAll();
643
+ // Drop the cached registry so importEntryAndRegistry re-reads it
644
+ // through the now-invalidated module runner.
645
+ prerenderNodeRegistry = null;
646
+ // Clear singleton Maps that Vite's moduleGraph invalidation can't
647
+ // reach (RouterRegistry / HostRouterRegistry). Without this, an
648
+ // edit that REMOVES a createRouter() call or CHANGES a router id
649
+ // would leave the old entry in the registry, and discoverRouters
650
+ // would still emit its routes alongside whatever the new source
651
+ // declares.
652
+ await clearTempRegistries(tempRscEnv);
653
+ await importEntryAndRegistry(tempRscEnv);
654
+ return tempRscEnv;
655
+ }
656
+
657
+ // Surface a discovery failure on either dev path (Node RSC runner or the
658
+ // Cloudflare temp Node server). `hashBefore`/`hashAfter` are the discovering
659
+ // environment's dep-optimizer browserHash snapshots: a change across the
660
+ // attempt means a reload-causing re-optimization landed mid-flight, so an
661
+ // empty registry was the transient race (downgraded to a warning) rather
662
+ // than a genuine misconfig (loud, actionable error). Shared so both catch
663
+ // sites frame the same failure identically.
664
+ const emitDiscoveryFailure = (
665
+ err: unknown,
666
+ hashBefore: string | undefined,
667
+ hashAfter: string | undefined,
668
+ ): void => {
669
+ const reoptimizeObserved =
670
+ hashBefore !== undefined &&
671
+ hashAfter !== undefined &&
672
+ hashBefore !== hashAfter;
673
+ const report = describeDiscoveryFailure(err, { reoptimizeObserved });
674
+ if (report.level === "warn") {
675
+ console.warn(report.message);
676
+ } else {
677
+ console.error(report.message);
678
+ }
679
+ };
680
+
681
+ const discover = async () => {
682
+ const discoverStart = performance.now();
683
+ const rscEnv = (server.environments as any)?.rsc;
684
+ if (!rscEnv?.runner) {
685
+ // Cloudflare dev: no module runner available (workerd-based RSC env).
686
+ // Set devServerOrigin so the virtual module can inject __PRERENDER_DEV_URL
687
+ // for on-demand prerender via the /__rsc_prerender endpoint.
688
+ debugDiscovery?.(
689
+ "dev: cloudflare path start, __rscRouterDiscoveryActive=%s",
690
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
691
+ );
692
+ s.devServerOrigin = getDevServerOrigin();
693
+
694
+ // Create a temp Node.js server to run runtime discovery and generate
695
+ // named route types (static parser can't resolve factory calls).
696
+ // The temp server is a separate Vite instance with its own dep
697
+ // optimizer; snapshot ITS browserHash (hoisted so the catch can tell a
698
+ // transient re-optimization apart from a genuine empty registry, the
699
+ // same way the Node path below does).
700
+ let tempRscEnv: any;
701
+ let optimizerHashBefore: string | undefined;
702
+ try {
703
+ // Acquire build-time env bindings for dev prerender
704
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
705
+ acquireBuildEnv(s, viteCommand, viteMode),
706
+ );
707
+
708
+ tempRscEnv = await timed(
709
+ debugDiscovery,
710
+ "getOrCreateTempServer",
711
+ () => getOrCreateTempServer(),
712
+ );
713
+ if (tempRscEnv) {
714
+ optimizerHashBefore =
715
+ tempRscEnv.depsOptimizer?.metadata?.browserHash;
716
+ await timed(debugDiscovery, "discoverRouters (cloudflare)", () =>
717
+ discoverRouters(s, tempRscEnv),
718
+ );
719
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
720
+ writeRouteTypesFiles(s),
721
+ );
722
+ }
723
+ } catch (err: any) {
724
+ emitDiscoveryFailure(
725
+ err,
726
+ optimizerHashBefore,
727
+ tempRscEnv?.depsOptimizer?.metadata?.browserHash,
728
+ );
729
+ }
730
+
731
+ debugDiscovery?.(
732
+ "dev discovery done (%sms)",
733
+ (performance.now() - discoverStart).toFixed(1),
734
+ );
735
+ resolveDiscovery!();
736
+ return;
737
+ }
738
+
739
+ // Snapshot the dep-optimizer hash before discovery so the catch can tell
740
+ // a transient re-optimization race apart from a genuine empty registry.
741
+ // A reload-causing re-optimization regenerates browserHash; if it changed
742
+ // across the attempt, an empty read was almost certainly the race below.
743
+ const optimizerHashBefore: string | undefined =
744
+ rscEnv.depsOptimizer?.metadata?.browserHash;
745
+
746
+ try {
747
+ // Acquire build-time env bindings for dev prerender (Node.js path)
748
+ debugDiscovery?.("dev: node path start");
749
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
750
+ acquireBuildEnv(s, viteCommand, viteMode),
751
+ );
752
+
753
+ // Discover routers FIRST, then arm the manifest-readiness gate on the
754
+ // server module discovery actually read the registry from.
755
+ //
756
+ // We deliberately do NOT pre-import "@rangojs/router/server" before the
757
+ // entry to arm the gate early. During a Vite dependency re-optimization
758
+ // (dev boot after a lockfile change, or `vite dev --force`), a module
759
+ // imported here before the entry resolves to the pre-optimize copy of
760
+ // the runner's module graph, while discoverRouters' entry import — which
761
+ // awaits the in-flight re-optimization — resolves to the post-optimize
762
+ // copy. createRouter() then populates RouterRegistry on the fresh copy,
763
+ // but a stale pre-imported "@rangojs/router/server" reads the other
764
+ // copy's empty Map and discovery throws a spurious "No routers found"
765
+ // even though the app is configured correctly. discoverRouters imports
766
+ // the entry first and reads the registry off the same instance, keeping
767
+ // read and write on one copy. The virtual manifest module's own gate
768
+ // (s.discoveryDone, armed by beginDiscoveryGate) already blocks early
769
+ // requests during discovery on the Node path, so arming
770
+ // manifestReadyPromise after discovery is sufficient here.
771
+ const serverMod = await timed(debugDiscovery, "discoverRouters", () =>
772
+ discoverRouters(s, rscEnv),
773
+ );
774
+ if (serverMod?.setManifestReadyPromise) {
775
+ serverMod.setManifestReadyPromise(discoveryPromise);
776
+ }
777
+
778
+ // Store server origin for dev prerender endpoint (virtual module injection)
779
+ s.devServerOrigin = getDevServerOrigin();
780
+
781
+ // Update named-routes.gen.ts from runtime discovery.
782
+ // The runtime manifest is the source of truth: it evaluates dynamic
783
+ // routes (e.g. Array.from loops) that the static parser cannot see.
784
+ // writeRouteTypesFiles() only writes when content changes, so this
785
+ // won't cause unnecessary HMR triggers.
786
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
787
+ writeRouteTypesFiles(s),
788
+ );
789
+
790
+ // Populate the route map and per-router data in the RSC env
791
+ await timed(debugDiscovery, "propagateDiscoveryState", () =>
792
+ propagateDiscoveryState(rscEnv),
793
+ );
794
+ } catch (err: any) {
795
+ emitDiscoveryFailure(
796
+ err,
797
+ optimizerHashBefore,
798
+ rscEnv.depsOptimizer?.metadata?.browserHash,
799
+ );
800
+ } finally {
801
+ debugDiscovery?.(
802
+ "dev discovery done (%sms)",
803
+ (performance.now() - discoverStart).toFixed(1),
804
+ );
805
+ resolveDiscovery!();
806
+ }
807
+ };
808
+
809
+ // Schedule after all plugins have finished configureServer.
810
+ // The gate (s.discoveryDone) is reset via beginDiscoveryGate() and
811
+ // resolved when discover() finishes, so the virtual manifest module's
812
+ // load() awaits the populated state.
813
+ beginDiscoveryGate();
814
+ setTimeout(
815
+ () => discover().then(resolveDiscoveryGate, resolveDiscoveryGate),
816
+ 0,
817
+ );
818
+
819
+ // Dev-mode on-demand prerender endpoint.
820
+ // When workerd hits a prerender route, it fetches this endpoint instead of
821
+ // trying to run node:fs-dependent handlers in the Cloudflare environment.
822
+ //
823
+ // Node.js preset: uses the main server's RSC environment directly (router
824
+ // instances are already discovered and have matchForPrerender).
825
+ // Cloudflare preset: lazily creates a Node.js temp server because the main
826
+ // RSC environment uses workerd where node:fs can't access the host filesystem.
827
+
828
+ // Registry from the main server's RSC environment (populated by discoverRouters)
829
+ let mainRegistry: Map<string, any> | null = null;
830
+
831
+ // Push discovery state (manifest, trie, precomputed entries) to the
832
+ // server module so runtime request handling uses the current routes.
833
+ // Shared by initial discovery and HMR-triggered re-discovery.
834
+ const propagateDiscoveryState = async (rscEnv: any) => {
835
+ const serverMod = await rscEnv.runner.import("@rangojs/router/server");
836
+ if (!serverMod) return;
837
+ // Clear stale per-router and global route data before repopulating.
838
+ // Without this, removed routers/routes survive in the per-router maps
839
+ // and shrunk precomputed entries or tries are never purged.
840
+ if (serverMod.clearAllRouterData) {
841
+ serverMod.clearAllRouterData();
842
+ }
843
+ mainRegistry = serverMod.RouterRegistry ?? null;
844
+ if (s.mergedRouteManifest && serverMod.setCachedManifest) {
845
+ serverMod.setCachedManifest(s.mergedRouteManifest);
846
+ }
847
+ if (
848
+ s.mergedPrecomputedEntries &&
849
+ s.mergedPrecomputedEntries.length > 0 &&
850
+ serverMod.setPrecomputedEntries
851
+ ) {
852
+ serverMod.setPrecomputedEntries(s.mergedPrecomputedEntries);
853
+ }
854
+ if (s.mergedRouteTrie && serverMod.setRouteTrie) {
855
+ serverMod.setRouteTrie(s.mergedRouteTrie);
856
+ }
857
+ const perRouterSetters: Array<[Map<string, any>, string]> = [
858
+ [s.perRouterManifestDataMap, "setRouterManifest"],
859
+ [s.perRouterTrieMap, "setRouterTrie"],
860
+ [s.perRouterPrecomputedMap, "setRouterPrecomputedEntries"],
861
+ ];
862
+ for (const [map, fn] of perRouterSetters) {
863
+ const setter = serverMod[fn];
864
+ if (typeof setter !== "function") continue;
865
+ for (const [routerId, value] of map) setter(routerId, value);
866
+ }
867
+ };
868
+
869
+ server.middlewares.use("/__rsc_prerender", async (req: any, res: any) => {
870
+ const reqStart = debugDev ? performance.now() : 0;
871
+ const logResult = (status: number, note: string) => {
872
+ debugDev?.(
873
+ "/__rsc_prerender %s -> %d %s (%sms)",
874
+ req.url,
875
+ status,
876
+ note,
877
+ (performance.now() - reqStart).toFixed(1),
878
+ );
879
+ };
880
+
881
+ if (s.discoveryDone) await s.discoveryDone;
882
+
883
+ const url = new URL(req.url || "/", "http://localhost");
884
+ const pathname = url.searchParams.get("pathname");
885
+ if (!pathname) {
886
+ res.statusCode = 400;
887
+ res.end("Missing pathname");
888
+ logResult(400, "missing pathname");
889
+ return;
890
+ }
891
+
892
+ // Import the user's entry module to force re-evaluation of any
893
+ // HMR-invalidated modules in the chain (entry → router → urls → handlers).
894
+ // This ensures createRouter() re-runs with updated handler code before
895
+ // we read RouterRegistry. Without this, edits to prerender handler files
896
+ // produce stale content because the old router instance remains registered.
897
+ const rscEnv = (server.environments as any)?.rsc;
898
+ let registry: Map<string, any> | null = null;
899
+ if (rscEnv?.runner && s.resolvedEntryPath) {
900
+ try {
901
+ await rscEnv.runner.import(s.resolvedEntryPath);
902
+ const serverMod = await rscEnv.runner.import(
903
+ "@rangojs/router/server",
904
+ );
905
+ registry = serverMod.RouterRegistry ?? null;
906
+ } catch (err: any) {
907
+ console.warn(
908
+ `[rango] Dev prerender module refresh failed: ${err.message}`,
909
+ );
910
+ res.statusCode = 500;
911
+ res.end(`Prerender handler error: ${err.message}`);
912
+ logResult(500, "module refresh failed");
913
+ return;
914
+ }
915
+ } else {
916
+ registry = mainRegistry;
917
+ }
918
+
919
+ if (!registry) {
920
+ // No main registry: the RSC env has no module runner (Cloudflare dev).
921
+ // Lazily create a Node.js temp server for prerender evaluation.
922
+ if (!prerenderNodeRegistry) {
923
+ await getOrCreateTempServer();
924
+ }
925
+ registry = prerenderNodeRegistry;
926
+ }
927
+
928
+ if (!registry || registry.size === 0) {
929
+ res.statusCode = 503;
930
+ res.end("Prerender runner not available");
931
+ logResult(503, "no registry");
932
+ return;
933
+ }
934
+
935
+ const wantIntercept = url.searchParams.get("intercept") === "1";
936
+ const wantRouteName = url.searchParams.get("routeName");
937
+ const wantPassthrough = url.searchParams.get("passthrough") === "1";
938
+
939
+ for (const [, routerInstance] of registry) {
940
+ if (!routerInstance.matchForPrerender) continue;
941
+ try {
942
+ const result = await routerInstance.matchForPrerender(
943
+ pathname,
944
+ {},
945
+ undefined,
946
+ wantPassthrough,
947
+ s.resolvedBuildEnv,
948
+ true, // devMode: check getParams for passthrough routes
949
+ );
950
+ if (!result) continue;
951
+ if (result.passthrough) continue;
952
+ // When routeName is specified, only accept a match for that route.
953
+ // This prevents returning the wrong entry when multiple routers
954
+ // have prerenderable routes sharing the same pathname.
955
+ if (wantRouteName && result.routeName !== wantRouteName) continue;
956
+ res.setHeader("content-type", "application/json");
957
+ let payload: Record<string, unknown>;
958
+ if (wantIntercept && result.interceptSegments?.length) {
959
+ payload = {
960
+ segments: [...result.segments, ...result.interceptSegments],
961
+ // Pre-encoded MERGED handle string from the producer (handles are
962
+ // Flight-encoded so Promise/ReactNode values survive the wire).
963
+ handles: result.interceptHandles ?? "",
964
+ };
965
+ } else {
966
+ payload = { segments: result.segments, handles: result.handles };
967
+ }
968
+ res.end(JSON.stringify(payload));
969
+ logResult(200, `match ${result.routeName}`);
970
+ return;
971
+ } catch (err: any) {
972
+ // matchForPrerender now re-throws render failures instead of baking
973
+ // an error page (issue #587). In dev there is no frozen artifact, so
974
+ // we fall through (404 -> live handler). A `throw new Skip()` is the
975
+ // expected "skip this URL" signal, not a failure, so it stays quiet.
976
+ if (err?.name !== "Skip") {
977
+ console.warn(
978
+ `[rango] Dev prerender error for ${pathname} (serving live instead): ${err.message}`,
979
+ );
980
+ }
981
+ }
982
+ }
983
+
984
+ res.statusCode = 404;
985
+ res.end("No prerender match");
986
+ logResult(404, "no match");
987
+ });
988
+
989
+ // Watch url module and router files for changes and regenerate named-routes.gen.ts.
990
+ // Process files containing urls( or createRouter( to update the combined route map.
991
+ if (opts?.staticRouteTypesGeneration !== false) {
992
+ const isGeneratedRouteFile = (filePath: string): boolean =>
993
+ filePath.endsWith(".gen.ts") &&
994
+ (filePath.includes("named-routes.gen.ts") ||
995
+ filePath.includes("urls.gen.ts"));
996
+
997
+ const regenerateGeneratedRouteFiles = () => {
998
+ if (s.perRouterManifests.length > 0) {
999
+ writeRouteTypesFiles(s);
1000
+ } else {
1001
+ writeCombinedRouteTypesWithTracking(s);
1002
+ }
1003
+ };
1004
+
1005
+ const maybeHandleGeneratedRouteFileMutation = (
1006
+ filePath: string,
1007
+ ): boolean => {
1008
+ if (!isGeneratedRouteFile(filePath)) return false;
1009
+ if (consumeSelfGenWrite(s, filePath)) return true;
1010
+ // In Cloudflare dev (no module runner), perRouterManifests is never
1011
+ // refreshed after HMR so regenerateGeneratedRouteFiles() would use
1012
+ // stale data and revert user edits. Source files own route state;
1013
+ // gen files are derived output. Skip regeneration and let the next
1014
+ // source-file change rebuild them from the static parser.
1015
+ const hasRunner = !!(server.environments as any)?.rsc?.runner;
1016
+ if (!hasRunner) return true;
1017
+ regenerateGeneratedRouteFiles();
1018
+ return true;
1019
+ };
1020
+
1021
+ // Debounce timer for batching rapid route-file changes (e.g. afterEach
1022
+ // restoring two files in quick succession). The cheap checks (extension,
1023
+ // scanFilter, content sniff) run synchronously to gate non-route files;
1024
+ // only the expensive regeneration is debounced.
1025
+ let routeChangeTimer: ReturnType<typeof setTimeout> | undefined;
1026
+
1027
+ // Re-run runtime discovery so factory-generated routes that the
1028
+ // static parser cannot see are refreshed after source changes.
1029
+ // The state-machine concerns (queued/pending/gatePending) are
1030
+ // owned by the gate created above (./discovery/gate-state.ts).
1031
+ // Here we provide just the env-specific work.
1032
+ const refreshRuntimeDiscovery = async () => {
1033
+ const rscEnv = (server.environments as any)?.rsc;
1034
+ const hasMainRunner = !!rscEnv?.runner;
1035
+ // Cloudflare HMR has no main RSC runner (workerd is a separate
1036
+ // runtime). When we have a populated runtime manifest from cold
1037
+ // start, we can re-discover via the temp Node runner — the same
1038
+ // mechanism getOrCreateTempServer() uses at startup. Without a
1039
+ // populated manifest there's nothing useful to do, so bail
1040
+ // before involving the gate machine at all.
1041
+ if (!hasMainRunner && s.perRouterManifests.length === 0) return;
1042
+ await gate.runRefreshCycle(async () => {
1043
+ const hmrStart = performance.now();
1044
+ try {
1045
+ if (hasMainRunner) {
1046
+ await timed(debugDiscovery, "hmr discoverRouters", () =>
1047
+ discoverRouters(s, rscEnv),
1048
+ );
1049
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1050
+ writeRouteTypesFiles(s),
1051
+ );
1052
+ await timed(debugDiscovery, "hmr propagateDiscoveryState", () =>
1053
+ propagateDiscoveryState(rscEnv),
1054
+ );
1055
+ } else {
1056
+ // Cloudflare HMR: invalidate the temp server's RSC module
1057
+ // graph (or close+recreate as a fallback) so the runner
1058
+ // re-reads the freshly edited source. Keeping the same
1059
+ // Vite instance alive avoids disrupting workerd's transport
1060
+ // during the first post-cold-start module-fetch window.
1061
+ const tempRscEnv = await timed(
1062
+ debugDiscovery,
1063
+ "hmr refreshTempRscEnv (cloudflare)",
1064
+ () => refreshTempRscEnv(),
1065
+ );
1066
+ if (!tempRscEnv) {
1067
+ throw new Error(
1068
+ "temp runner unavailable for cloudflare HMR rediscovery",
1069
+ );
1070
+ }
1071
+ await timed(
1072
+ debugDiscovery,
1073
+ "hmr discoverRouters (cloudflare)",
1074
+ () => discoverRouters(s, tempRscEnv),
1075
+ );
1076
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1077
+ writeRouteTypesFiles(s),
1078
+ );
1079
+ }
1080
+ if (s.lastDiscoveryError) {
1081
+ debugDiscovery?.(
1082
+ "hmr: cleared lastDiscoveryError (%s) after successful rediscovery",
1083
+ s.lastDiscoveryError.message,
1084
+ );
1085
+ s.lastDiscoveryError = null;
1086
+ }
1087
+ // Cloudflare dev: on a successful cycle drop the workerd runner's
1088
+ // cached worker-entry chain so the next request re-evaluates
1089
+ // createRouter() with the new routes. Fired here in the work path
1090
+ // (not the caller's .then()) so a queued follow-up cycle that
1091
+ // succeeds after an earlier failed cycle still reloads:
1092
+ // runRefreshCycle recurses queued work without awaiting it, so the
1093
+ // original call already resolved on the failed cycle. A failed
1094
+ // cycle throws above and never reaches here, so a broken edit
1095
+ // never reloads the worker onto bad source.
1096
+ if (rscEnv && !rscEnv.runner) forceCloudflareWorkerReload(rscEnv);
1097
+ } catch (err: any) {
1098
+ s.lastDiscoveryError = {
1099
+ message: err?.message ?? String(err),
1100
+ at: Date.now(),
1101
+ };
1102
+ console.warn(
1103
+ `[rango] Runtime re-discovery failed: ${err.message}`,
1104
+ );
1105
+ debugDiscovery?.(
1106
+ "hmr: lastDiscoveryError set (%s) — manifest preserved at last-good; recovery mode active (any in-scan source change will trigger rediscovery)",
1107
+ err?.message,
1108
+ );
1109
+ } finally {
1110
+ debugDiscovery?.(
1111
+ "hmr re-discovery done (%sms)",
1112
+ (performance.now() - hmrStart).toFixed(1),
1113
+ );
1114
+ }
1115
+ });
1116
+ };
1117
+
1118
+ // Cloudflare dev only. workerd serves every request through the
1119
+ // runner-worker singleton, which re-resolves the worker entry per
1120
+ // request via runner.import("virtual:cloudflare/worker-entry"). The
1121
+ // route table lives in the user's createRouter() instance, captured
1122
+ // when that entry chain (entry -> router -> urls) was last evaluated
1123
+ // and then cached in the runner's evaluatedModules. The route-file
1124
+ // watcher refreshes discovery + types on the Node side, but the worker
1125
+ // keeps serving the cached (stale) router: route-definition modules
1126
+ // have no import.meta.hot boundary, so Vite never sends the worker an
1127
+ // HMR update for them and the entry chain is never evicted.
1128
+ //
1129
+ // Fix: after discovery completes, (1) invalidate the worker env's
1130
+ // Node-side module graph, then (2) send a full-reload to the worker.
1131
+ // Step (2) alone is insufficient: the full-reload handler clears the
1132
+ // runner's evaluatedModules and re-imports entrypoints, but each
1133
+ // re-import fetches the module back through this Node-side graph, which
1134
+ // still holds the pre-edit transform of urls.tsx — so createRouter()
1135
+ // rebuilds the stale route table and the new route 404s/hits the
1136
+ // catch-all. Invalidating the graph forces a fresh transform on
1137
+ // re-fetch (the same mechanism refreshTempRscEnv uses for discovery),
1138
+ // so the re-import re-runs createRouter() with the new routes. This is
1139
+ // the programmatic equivalent of the dev-server "r + enter" restart,
1140
+ // scoped to the worker environment instead of tearing down the server.
1141
+ const forceCloudflareWorkerReload = (rscEnv: any) => {
1142
+ if (!rscEnv?.hot) return;
1143
+ try {
1144
+ const graph = rscEnv.moduleGraph;
1145
+ if (graph?.invalidateAll) {
1146
+ graph.invalidateAll();
1147
+ debugDiscovery?.("hmr: invalidated workerd rsc module graph");
1148
+ }
1149
+ rscEnv.hot.send({ type: "full-reload" });
1150
+ debugDiscovery?.(
1151
+ "hmr: forced workerd rsc env reload (full-reload)",
1152
+ );
1153
+ } catch (err: any) {
1154
+ debugDiscovery?.(
1155
+ "hmr: workerd reload failed: %s",
1156
+ err?.message ?? err,
1157
+ );
1158
+ }
1159
+ };
1160
+
1161
+ const scheduleRouteRegeneration = () => {
1162
+ clearTimeout(routeChangeTimer);
1163
+ routeChangeTimer = setTimeout(() => {
1164
+ routeChangeTimer = undefined;
1165
+ const regenStart = debugDiscovery ? performance.now() : 0;
1166
+ const rscEnv = (server.environments as any)?.rsc;
1167
+ const skipStaticWrite =
1168
+ !rscEnv?.runner && s.perRouterManifests.length > 0;
1169
+ try {
1170
+ // In cloudflare dev with a populated runtime manifest, the
1171
+ // static parser produces a strictly smaller (and actively
1172
+ // wrong) gen file — supplementGenFilesWithRuntimeRoutes can
1173
+ // only restore factory-only prefixes, and apps with mixed
1174
+ // static+factory routes under shared prefixes (cf-stress)
1175
+ // collapse to the 19-route static view. Skip the static
1176
+ // write entirely; runtime rediscovery below will overwrite
1177
+ // the gen file with the authoritative manifest.
1178
+ if (skipStaticWrite) {
1179
+ debugDiscovery?.(
1180
+ "watcher: skipping static write (cloudflare HMR — runtime rediscovery owns gen file)",
1181
+ );
1182
+ } else {
1183
+ writeCombinedRouteTypesWithTracking(s);
1184
+ if (s.perRouterManifests.length > 0) {
1185
+ supplementGenFilesWithRuntimeRoutes(s);
1186
+ }
1187
+ }
1188
+ } catch (err: any) {
1189
+ console.error(`[rango] Route regeneration error: ${err.message}`);
1190
+ }
1191
+ debugDiscovery?.(
1192
+ "watcher: regenerated gen files (%sms)",
1193
+ (performance.now() - regenStart).toFixed(1),
1194
+ );
1195
+ // Async: re-run runtime discovery to refresh factory-generated
1196
+ // routes that the static parser cannot resolve. Resolves the
1197
+ // discovery gate when complete.
1198
+ if (s.perRouterManifests.length > 0) {
1199
+ // The cloudflare workerd reload fires inside refreshRuntimeDiscovery
1200
+ // on the successful cycle (see forceCloudflareWorkerReload call
1201
+ // there) so queued follow-up cycles also trigger it.
1202
+ refreshRuntimeDiscovery().catch((err: any) => {
1203
+ console.warn(
1204
+ `[rango] Runtime re-discovery error: ${err.message}`,
1205
+ );
1206
+ // Even on error, unblock the gate so workerd's reload doesn't
1207
+ // hang indefinitely against the previous manifest.
1208
+ resolveDiscoveryGate();
1209
+ });
1210
+ }
1211
+ }, 100);
1212
+ };
1213
+
1214
+ const handleRouteFileChange = (filePath: string) => {
1215
+ if (maybeHandleGeneratedRouteFileMutation(filePath)) return;
1216
+ if (
1217
+ !filePath.endsWith(".ts") &&
1218
+ !filePath.endsWith(".tsx") &&
1219
+ !filePath.endsWith(".js") &&
1220
+ !filePath.endsWith(".jsx")
1221
+ ) {
1222
+ if (s.lastDiscoveryError) {
1223
+ debugDiscovery?.(
1224
+ "watcher: skip non-source %s [LASTERR %s]",
1225
+ filePath,
1226
+ s.lastDiscoveryError.message,
1227
+ );
1228
+ }
1229
+ return;
1230
+ }
1231
+ // Apply scan filter as early-exit before reading file
1232
+ if (s.scanFilter && !s.scanFilter(filePath)) {
1233
+ if (s.lastDiscoveryError) {
1234
+ debugDiscovery?.(
1235
+ "watcher: skip scan-filter %s [LASTERR %s]",
1236
+ filePath,
1237
+ s.lastDiscoveryError.message,
1238
+ );
1239
+ }
1240
+ return;
1241
+ }
1242
+ // Recovery mode: when the previous HMR re-discovery failed, the
1243
+ // import graph is incomplete and the manifest is stuck at the
1244
+ // last-good state. The fix may land in a non-route file (e.g. a
1245
+ // helper imported by the router, a missing module being created,
1246
+ // or a "use client" component) that the narrow content sniff
1247
+ // would otherwise filter out. While in recovery, treat any
1248
+ // in-scan source change as a candidate for rediscovery; the
1249
+ // tighter filter resumes once discovery succeeds again.
1250
+ const inRecoveryMode = !!s.lastDiscoveryError;
1251
+ try {
1252
+ const source = readFileSync(filePath, "utf-8");
1253
+ const trimmed = source.trimStart();
1254
+ const isUseClient =
1255
+ trimmed.startsWith('"use client"') ||
1256
+ trimmed.startsWith("'use client'");
1257
+ if (!inRecoveryMode && isUseClient) return;
1258
+ // Cheap raw pre-check first; only when a candidate token is present
1259
+ // do we confirm it occurs in real code (not a comment/string) via a
1260
+ // single allocation-free code-region scan. Most saved files contain
1261
+ // neither token and skip the scan entirely. This avoids a comment or
1262
+ // string mention spuriously marking a file relevant and triggering an
1263
+ // unnecessary re-discovery on save.
1264
+ let hasUrls = source.includes("urls(");
1265
+ let hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
1266
+ if (hasUrls) hasUrls = firstCodeMatchIndex(source, /urls\(/g) >= 0;
1267
+ if (hasCreateRouter) {
1268
+ hasCreateRouter =
1269
+ firstCodeMatchIndex(source, /\bcreateRouter\s*[<(]/g) >= 0;
1270
+ }
1271
+ if (!inRecoveryMode && !hasUrls && !hasCreateRouter) return;
1272
+ if (inRecoveryMode) {
1273
+ debugDiscovery?.(
1274
+ "watcher: recovery rediscovery for %s (urls=%s, router=%s, useClient=%s) [LASTERR %s]",
1275
+ filePath,
1276
+ hasUrls,
1277
+ hasCreateRouter,
1278
+ isUseClient,
1279
+ s.lastDiscoveryError!.message,
1280
+ );
1281
+ } else {
1282
+ debugDiscovery?.(
1283
+ "watcher: %s matches (urls=%s, router=%s)",
1284
+ filePath,
1285
+ hasUrls,
1286
+ hasCreateRouter,
1287
+ );
1288
+ }
1289
+ // Invalidate cache when a router file changes (new router added/removed)
1290
+ if (hasCreateRouter) {
1291
+ const nestedRouterConflict = findNestedRouterConflict([
1292
+ ...(s.cachedRouterFiles ?? []),
1293
+ resolve(filePath),
1294
+ ]);
1295
+ if (nestedRouterConflict) {
1296
+ server.config.logger.error(
1297
+ formatNestedRouterConflictError(nestedRouterConflict),
1298
+ );
1299
+ return;
1300
+ }
1301
+ s.cachedRouterFiles = undefined;
1302
+ }
1303
+ // Note the event in the gate machine IMMEDIATELY (before the
1304
+ // 100ms debounce and any downstream HMR fanout). This sets
1305
+ // both `pendingEvents` (so refresh's finally holds the gate
1306
+ // through the tail window even if no rediscovery is queued)
1307
+ // and resets `discoveryDone` to a fresh pending promise (so
1308
+ // workerd reloads triggered by the same source change can't
1309
+ // observe a stale resolved gate from cold-start). Resolved
1310
+ // by the trailing refreshRuntimeDiscovery() cycle.
1311
+ if (s.perRouterManifests.length > 0) {
1312
+ gate.noteRouteEvent();
1313
+ }
1314
+ scheduleRouteRegeneration();
1315
+ } catch (readErr: any) {
1316
+ if (s.lastDiscoveryError) {
1317
+ debugDiscovery?.(
1318
+ "watcher: read error %s: %s [LASTERR %s]",
1319
+ filePath,
1320
+ readErr?.message,
1321
+ s.lastDiscoveryError.message,
1322
+ );
1323
+ }
1324
+ // Ignore read errors for deleted/moved files
1325
+ }
1326
+ };
1327
+
1328
+ // Handle both "add" and "change" events: editors with atomic saves
1329
+ // (unlink + rename) emit "add" instead of "change", and chokidar's
1330
+ // polling mode on CI Linux can also emit "add" for overwrites.
1331
+ server.watcher.on("add", handleRouteFileChange);
1332
+ server.watcher.on("change", handleRouteFileChange);
1333
+
1334
+ // Regenerate gen files when they are deleted (e.g. manual cleanup).
1335
+ // Same no-runner guard as change/add: stale perRouterManifests would
1336
+ // reintroduce reverted content.
1337
+ server.watcher.on("unlink", (filePath) => {
1338
+ if (!isGeneratedRouteFile(filePath)) return;
1339
+ const hasRunner = !!(server.environments as any)?.rsc?.runner;
1340
+ if (!hasRunner) return;
1341
+ regenerateGeneratedRouteFiles();
1342
+ });
1343
+ }
1344
+ },
1345
+
1346
+ // Build mode: create a temporary Vite dev server to access the RSC
1347
+ // environment's module runner, then discover routers and generate manifests.
1348
+ // The manifest data is stored for the virtual module's load hook.
1349
+ async buildStart() {
1350
+ if (!s.isBuildMode) return;
1351
+ // Only run once across environment builds
1352
+ if (s.mergedRouteManifest !== null) {
1353
+ debugDiscovery?.(
1354
+ "build: skip (already discovered, env=%s)",
1355
+ this.environment?.name ?? "?",
1356
+ );
1357
+ return;
1358
+ }
1359
+ const buildStartTime = performance.now();
1360
+ debugDiscovery?.("build: start (env=%s)", this.environment?.name ?? "?");
1361
+ resetStagedBuildAssets(s.projectRoot);
1362
+ s.prerenderManifestEntries = null;
1363
+ s.staticManifestEntries = null;
1364
+
1365
+ // Acquire build-time env bindings if configured
1366
+ await timed(debugDiscovery, "build acquireBuildEnv", () =>
1367
+ acquireBuildEnv(s, viteCommand, viteMode),
1368
+ );
1369
+
1370
+ let tempServer: any = null;
1371
+ // Signal to user-space code (e.g. reverse.ts) that build-time discovery
1372
+ // is active. Uses globalThis because the temp server's module runner
1373
+ // creates a separate module context — there is no shared import path
1374
+ // between the vite plugin and user code loaded via runner.import().
1375
+ (globalThis as any).__rscRouterDiscoveryActive = true;
1376
+ try {
1377
+ tempServer = await timed(
1378
+ debugDiscovery,
1379
+ "build createTempRscServer",
1380
+ () => createTempRscServer(s, { forceBuild: true }),
1381
+ );
1382
+
1383
+ const rscEnv = (tempServer.environments as any)?.rsc;
1384
+ if (!rscEnv?.runner) {
1385
+ console.warn(
1386
+ "[rango] RSC environment runner not available during build, skipping manifest generation",
1387
+ );
1388
+ return;
1389
+ }
1390
+
1391
+ // Point resolvedStaticModules at the temp server's expose-internal-ids
1392
+ // plugin so that discoverRouters() can access the static handler module
1393
+ // map after the temp server's transforms populate it.
1394
+ const tempIdsPlugin = (tempServer as any).config?.plugins?.find(
1395
+ (p: any) => p.name === "@rangojs/router:expose-internal-ids",
1396
+ );
1397
+ if (tempIdsPlugin?.api?.staticHandlerModules) {
1398
+ s.resolvedStaticModules = tempIdsPlugin.api.staticHandlerModules;
1399
+ }
1400
+
1401
+ await timed(debugDiscovery, "build discoverRouters", () =>
1402
+ discoverRouters(s, rscEnv),
1403
+ );
1404
+ // Update named-routes.gen.ts from runtime discovery.
1405
+ // The runtime manifest includes dynamically generated routes
1406
+ // that the static parser cannot extract from source code.
1407
+ timedSync(debugDiscovery, "build writeRouteTypesFiles", () =>
1408
+ writeRouteTypesFiles(s),
1409
+ );
1410
+ } catch (err: any) {
1411
+ // Extract the user source file from the stack trace (skip internal frames)
1412
+ const sourceFile = err.stack
1413
+ ?.split("\n")
1414
+ .find(
1415
+ (line: string) =>
1416
+ line.includes(s.projectRoot) && !line.includes("node_modules"),
1417
+ )
1418
+ ?.match(/\(([^)]+)\)/)?.[1];
1419
+ // Extract the route name from "Unknown route: <name>" errors
1420
+ const routeName = err.message?.match(/Unknown route: (.+)/)?.[1];
1421
+ const details = [
1422
+ routeName ? ` Route name: ${routeName}` : null,
1423
+ sourceFile ? ` File: ${sourceFile}` : null,
1424
+ err.stack ? ` Stack:\n${err.stack}` : null,
1425
+ ]
1426
+ .filter(Boolean)
1427
+ .join("\n");
1428
+ throw new Error(
1429
+ `[rango] Build-time router discovery failed:\n${details}`,
1430
+ { cause: err },
1431
+ );
1432
+ } finally {
1433
+ delete (globalThis as any).__rscRouterDiscoveryActive;
1434
+ if (tempServer) {
1435
+ await timed(debugDiscovery, "build tempServer.close", () =>
1436
+ tempServer.close(),
1437
+ );
1438
+ }
1439
+ await releaseBuildEnv(s);
1440
+ debugDiscovery?.(
1441
+ "build discovery done (%sms)",
1442
+ (performance.now() - buildStartTime).toFixed(1),
1443
+ );
1444
+ }
1445
+ },
1446
+
1447
+ // Suppress vite's HMR cascade for our own gen-file writes.
1448
+ //
1449
+ // After every cf HMR cycle, refreshTempRscEnv → writeRouteTypesFiles
1450
+ // writes the configured gen files (default `router.named-routes.gen.ts`,
1451
+ // but the source filenames and gen suffix are user-configurable). The
1452
+ // chokidar watcher then fires twice independently: our
1453
+ // `handleRouteFileChange` (already short-circuited by
1454
+ // `consumeSelfGenWrite` inside `maybeHandleGeneratedRouteFileMutation`),
1455
+ // AND vite's own HMR pipeline (which invalidates the gen file's
1456
+ // importers and triggers a second workerd full reload — visible to the
1457
+ // user as a duplicate "[Rango] HMR: version changed" on the client).
1458
+ //
1459
+ // `peekSelfGenWrite` is the authoritative filter: its map only contains
1460
+ // paths that `markSelfGenWrite` has registered, so it natively works
1461
+ // for any configured gen-file name. It is non-consuming so the chokidar
1462
+ // handler that fires later can still consume the same entry. Returning
1463
+ // [] tells vite "no modules invalidated by this change" — safe because
1464
+ // `s.perRouterManifests` is already up-to-date (the write that just
1465
+ // happened is the consequence of our just-completed rediscovery).
1466
+ handleHotUpdate(ctx) {
1467
+ if (peekSelfGenWrite(s, ctx.file)) {
1468
+ debugDiscovery?.(
1469
+ "handleHotUpdate: suppressing self-write HMR cascade for %s",
1470
+ ctx.file,
1471
+ );
1472
+ return [];
1473
+ }
1474
+ },
1475
+
1476
+ // Virtual module: provides the pre-generated route manifest as a JS module
1477
+ // that calls setCachedManifest() at import time.
1478
+ resolveId(id) {
1479
+ if (id === VIRTUAL_ROUTES_MANIFEST_ID) {
1480
+ return "\0" + VIRTUAL_ROUTES_MANIFEST_ID;
1481
+ }
1482
+ // Per-router virtual modules: virtual:rsc-router/routes-manifest/<routerId>
1483
+ if (id.startsWith(VIRTUAL_ROUTES_MANIFEST_ID + "/")) {
1484
+ return "\0" + id;
1485
+ }
1486
+ // virtual:rsc-router/prerender-paths removed: prerender data is served through the worker
1487
+ return null;
1488
+ },
1489
+
1490
+ async load(id) {
1491
+ if (id === "\0" + VIRTUAL_ROUTES_MANIFEST_ID) {
1492
+ // In dev mode, wait for discovery to complete before emitting module content.
1493
+ // This is critical for Cloudflare dev where the worker runs in a separate
1494
+ // Miniflare process and can only receive manifest data via the virtual module.
1495
+ if (s.discoveryDone) {
1496
+ await timed(
1497
+ debugRoutes,
1498
+ "await discoveryDone (manifest)",
1499
+ () => s.discoveryDone,
1500
+ );
1501
+ }
1502
+ const code = await timed(
1503
+ debugRoutes,
1504
+ "generateRoutesManifestModule",
1505
+ () => generateRoutesManifestModule(s),
1506
+ );
1507
+ debugRoutes?.("manifest module emitted (%d bytes)", code?.length ?? 0);
1508
+ return code;
1509
+ }
1510
+ // Per-router virtual modules: pure data exports (no side effects).
1511
+ // ensureRouterManifest() imports the module and stores the data.
1512
+ const perRouterPrefix = "\0" + VIRTUAL_ROUTES_MANIFEST_ID + "/";
1513
+ if (id.startsWith(perRouterPrefix)) {
1514
+ if (s.discoveryDone) {
1515
+ await timed(
1516
+ debugRoutes,
1517
+ "await discoveryDone (per-router)",
1518
+ () => s.discoveryDone,
1519
+ );
1520
+ }
1521
+ const routerId = id.slice(perRouterPrefix.length);
1522
+ const code = await timed(
1523
+ debugRoutes,
1524
+ `generatePerRouterModule ${routerId}`,
1525
+ () => generatePerRouterModule(s, routerId),
1526
+ );
1527
+ return code;
1528
+ }
1529
+ // virtual:rsc-router/prerender-paths load handler removed
1530
+ return null;
1531
+ },
1532
+
1533
+ // Record handler chunk metadata and RSC entry filename during RSC build.
1534
+ // Used by closeBundle for handler code eviction and prerender data injection.
1535
+ generateBundle(_options: any, bundle: any) {
1536
+ if (this.environment?.name !== "rsc") return;
1537
+ const genStart = debugBuild ? performance.now() : 0;
1538
+
1539
+ // Record RSC entry chunk filename for closeBundle injection
1540
+ for (const [fileName, chunk] of Object.entries(bundle) as [
1541
+ string,
1542
+ any,
1543
+ ][]) {
1544
+ if (chunk.type === "chunk" && chunk.isEntry) {
1545
+ s.rscEntryFileName = fileName;
1546
+ break;
1547
+ }
1548
+ }
1549
+
1550
+ if (!s.resolvedPrerenderModules?.size && !s.resolvedStaticModules?.size) {
1551
+ debugBuild?.(
1552
+ "generateBundle (rsc): no handlers to scan (%sms)",
1553
+ (performance.now() - genStart).toFixed(1),
1554
+ );
1555
+ return;
1556
+ }
1557
+
1558
+ // Clear maps at the start of each RSC generateBundle pass.
1559
+ // Vite 6 multi-environment builds run RSC twice (analysis + production);
1560
+ // clearing prevents stale/duplicate records from the analysis pass.
1561
+ s.handlerChunkInfoMap.clear();
1562
+ s.staticHandlerChunkInfoMap.clear();
1563
+
1564
+ for (const [fileName, chunk] of Object.entries(bundle) as [
1565
+ string,
1566
+ any,
1567
+ ][]) {
1568
+ if (chunk.type !== "chunk") continue;
1569
+
1570
+ // Scan all chunks for handler exports (handlers may land in any chunk)
1571
+ if (s.resolvedPrerenderModules?.size) {
1572
+ const handlers = extractHandlerExportsFromChunk(
1573
+ chunk.code,
1574
+ s.resolvedPrerenderModules,
1575
+ "Prerender",
1576
+ false,
1577
+ );
1578
+ if (handlers.length > 0) {
1579
+ const existing = s.handlerChunkInfoMap.get(fileName);
1580
+ if (existing) {
1581
+ existing.exports.push(...handlers);
1582
+ } else {
1583
+ s.handlerChunkInfoMap.set(fileName, {
1584
+ fileName,
1585
+ exports: handlers,
1586
+ });
1587
+ }
1588
+ }
1589
+ }
1590
+
1591
+ if (s.resolvedStaticModules?.size) {
1592
+ const handlers = extractHandlerExportsFromChunk(
1593
+ chunk.code,
1594
+ s.resolvedStaticModules,
1595
+ "Static",
1596
+ false,
1597
+ );
1598
+ if (handlers.length > 0) {
1599
+ const existing = s.staticHandlerChunkInfoMap.get(fileName);
1600
+ if (existing) {
1601
+ existing.exports.push(...handlers);
1602
+ } else {
1603
+ s.staticHandlerChunkInfoMap.set(fileName, {
1604
+ fileName,
1605
+ exports: handlers,
1606
+ });
1607
+ }
1608
+ }
1609
+ }
1610
+ }
1611
+
1612
+ debugBuild?.(
1613
+ "generateBundle (rsc): scanned %d chunks, %d prerender chunk(s), %d static chunk(s) (%sms)",
1614
+ Object.keys(bundle).length,
1615
+ s.handlerChunkInfoMap.size,
1616
+ s.staticHandlerChunkInfoMap.size,
1617
+ (performance.now() - genStart).toFixed(1),
1618
+ );
1619
+ },
1620
+
1621
+ // Build-time pre-rendering: evict handler code and inject collected prerender data.
1622
+ // Collection now happens in-process during discoverRouters() via RSC runner.
1623
+ // closeBundle only needs to evict handlers and inject the in-memory data.
1624
+ closeBundle: {
1625
+ order: "post" as const,
1626
+ sequential: true,
1627
+ async handler(this: any) {
1628
+ if (!s.isBuildMode) return;
1629
+ // Only run for the RSC environment — other environments (client, ssr) have
1630
+ // no prerender/static data to process and would just do redundant file I/O.
1631
+ if (this.environment && this.environment.name !== "rsc") return;
1632
+ timedSync(debugBuild, "closeBundle postprocessBundle", () =>
1633
+ postprocessBundle(s),
1634
+ );
1635
+ },
1636
+ },
1637
+ };
1638
+ }