@rangojs/router 0.0.0-experimental.19 → 0.0.0-experimental.1c0bdfad

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