@rangojs/router 0.0.0-experimental.9c9afef3 → 0.0.0-experimental.a014d2b7

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 (402) hide show
  1. package/AGENTS.md +8 -0
  2. package/README.md +245 -49
  3. package/dist/bin/rango.js +440 -133
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +3373 -1176
  6. package/dist/vite/index.js.bak +5448 -0
  7. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  8. package/package.json +68 -14
  9. package/skills/api-client/SKILL.md +211 -0
  10. package/skills/breadcrumbs/SKILL.md +64 -2
  11. package/skills/bundle-analysis/SKILL.md +159 -0
  12. package/skills/cache-guide/SKILL.md +224 -32
  13. package/skills/caching/SKILL.md +279 -17
  14. package/skills/composability/SKILL.md +27 -3
  15. package/skills/css/SKILL.md +76 -0
  16. package/skills/debug-manifest/SKILL.md +4 -2
  17. package/skills/document-cache/SKILL.md +78 -55
  18. package/skills/handler-use/SKILL.md +364 -0
  19. package/skills/hooks/SKILL.md +250 -30
  20. package/skills/host-router/SKILL.md +83 -23
  21. package/skills/i18n/SKILL.md +276 -0
  22. package/skills/intercept/SKILL.md +87 -18
  23. package/skills/layout/SKILL.md +35 -9
  24. package/skills/links/SKILL.md +249 -17
  25. package/skills/loader/SKILL.md +235 -9
  26. package/skills/middleware/SKILL.md +52 -13
  27. package/skills/migrate-nextjs/SKILL.md +584 -0
  28. package/skills/migrate-react-router/SKILL.md +771 -0
  29. package/skills/mime-routes/SKILL.md +28 -1
  30. package/skills/observability/SKILL.md +172 -0
  31. package/skills/parallel/SKILL.md +77 -7
  32. package/skills/prerender/SKILL.md +172 -125
  33. package/skills/rango/SKILL.md +251 -22
  34. package/skills/react-compiler/SKILL.md +168 -0
  35. package/skills/response-routes/SKILL.md +123 -48
  36. package/skills/route/SKILL.md +70 -5
  37. package/skills/router-setup/SKILL.md +65 -8
  38. package/skills/scripts/SKILL.md +179 -0
  39. package/skills/server-actions/SKILL.md +775 -0
  40. package/skills/streams-and-websockets/SKILL.md +283 -0
  41. package/skills/tailwind/SKILL.md +27 -3
  42. package/skills/testing/SKILL.md +130 -0
  43. package/skills/testing/bindings.md +103 -0
  44. package/skills/testing/cache-prerender.md +127 -0
  45. package/skills/testing/client-components.md +124 -0
  46. package/skills/testing/e2e-parity.md +125 -0
  47. package/skills/testing/flight.md +91 -0
  48. package/skills/testing/handles.md +129 -0
  49. package/skills/testing/loader.md +128 -0
  50. package/skills/testing/middleware.md +99 -0
  51. package/skills/testing/render-handler.md +122 -0
  52. package/skills/testing/response-routes.md +95 -0
  53. package/skills/testing/reverse-and-types.md +84 -0
  54. package/skills/testing/server-actions.md +107 -0
  55. package/skills/testing/server-tree.md +128 -0
  56. package/skills/testing/setup.md +123 -0
  57. package/skills/typesafety/SKILL.md +322 -29
  58. package/skills/use-cache/SKILL.md +57 -14
  59. package/skills/view-transitions/SKILL.md +337 -0
  60. package/src/__augment-tests__/augment.ts +81 -0
  61. package/src/__augment-tests__/augmented.check.ts +116 -0
  62. package/src/__internal.ts +1 -66
  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 +192 -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/navigation-bridge.ts +131 -30
  74. package/src/browser/navigation-client.ts +186 -100
  75. package/src/browser/navigation-store-handle.ts +38 -0
  76. package/src/browser/navigation-store.ts +157 -74
  77. package/src/browser/navigation-transaction.ts +9 -59
  78. package/src/browser/network-error-handler.ts +34 -7
  79. package/src/browser/partial-update.ts +165 -112
  80. package/src/browser/prefetch/cache.ts +205 -62
  81. package/src/browser/prefetch/fetch.ts +347 -39
  82. package/src/browser/prefetch/queue.ts +42 -8
  83. package/src/browser/rango-state.ts +158 -76
  84. package/src/browser/react/Link.tsx +102 -15
  85. package/src/browser/react/NavigationProvider.tsx +295 -119
  86. package/src/browser/react/ScrollRestoration.tsx +10 -6
  87. package/src/browser/react/context.ts +7 -2
  88. package/src/browser/react/deferred-handle-resolution.ts +75 -0
  89. package/src/browser/react/filter-segment-order.ts +66 -7
  90. package/src/browser/react/index.ts +0 -48
  91. package/src/browser/react/location-state-shared.ts +178 -8
  92. package/src/browser/react/location-state.ts +39 -14
  93. package/src/browser/react/use-action.ts +6 -15
  94. package/src/browser/react/use-handle.ts +23 -69
  95. package/src/browser/react/use-href.tsx +8 -1
  96. package/src/browser/react/use-link-status.ts +33 -8
  97. package/src/browser/react/use-navigation.ts +32 -7
  98. package/src/browser/react/use-params.ts +20 -10
  99. package/src/browser/react/use-reverse.ts +106 -0
  100. package/src/browser/react/use-router.ts +46 -11
  101. package/src/browser/react/use-search-params.ts +0 -5
  102. package/src/browser/react/use-segments.ts +11 -21
  103. package/src/browser/response-adapter.ts +99 -8
  104. package/src/browser/rsc-router.tsx +114 -24
  105. package/src/browser/scroll-restoration.ts +37 -22
  106. package/src/browser/segment-reconciler.ts +36 -14
  107. package/src/browser/segment-structure-assert.ts +2 -2
  108. package/src/browser/server-action-bridge.ts +222 -72
  109. package/src/browser/types.ts +102 -12
  110. package/src/browser/validate-redirect-origin.ts +43 -16
  111. package/src/build/collect-fallback-refs.ts +107 -0
  112. package/src/build/generate-manifest.ts +65 -40
  113. package/src/build/generate-route-types.ts +5 -1
  114. package/src/build/index.ts +8 -2
  115. package/src/build/prefix-tree-utils.ts +123 -0
  116. package/src/build/route-trie.ts +165 -36
  117. package/src/build/route-types/ast-route-extraction.ts +15 -8
  118. package/src/build/route-types/codegen.ts +16 -5
  119. package/src/build/route-types/include-resolution.ts +125 -24
  120. package/src/build/route-types/param-extraction.ts +6 -3
  121. package/src/build/route-types/per-module-writer.ts +22 -6
  122. package/src/build/route-types/router-processing.ts +260 -94
  123. package/src/build/route-types/scan-filter.ts +9 -2
  124. package/src/build/route-types/source-scan.ts +216 -0
  125. package/src/build/runtime-discovery.ts +9 -20
  126. package/src/cache/cache-error.ts +104 -0
  127. package/src/cache/cache-key-utils.ts +29 -13
  128. package/src/cache/cache-policy.ts +108 -34
  129. package/src/cache/cache-runtime.ts +224 -41
  130. package/src/cache/cache-scope.ts +188 -82
  131. package/src/cache/cache-tag.ts +103 -0
  132. package/src/cache/cf/cf-base64.ts +33 -0
  133. package/src/cache/cf/cf-cache-constants.ts +127 -0
  134. package/src/cache/cf/cf-cache-store.ts +1989 -378
  135. package/src/cache/cf/cf-cache-types.ts +349 -0
  136. package/src/cache/cf/cf-kv-utils.ts +46 -0
  137. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  138. package/src/cache/cf/index.ts +6 -16
  139. package/src/cache/document-cache.ts +89 -21
  140. package/src/cache/handle-snapshot.ts +70 -0
  141. package/src/cache/index.ts +10 -20
  142. package/src/cache/memory-segment-store.ts +136 -37
  143. package/src/cache/profile-registry.ts +46 -31
  144. package/src/cache/read-through-swr.ts +56 -12
  145. package/src/cache/segment-codec.ts +9 -17
  146. package/src/cache/tag-invalidation.ts +230 -0
  147. package/src/cache/types.ts +37 -100
  148. package/src/client.rsc.tsx +44 -21
  149. package/src/client.tsx +119 -290
  150. package/src/cloudflare/index.ts +11 -0
  151. package/src/cloudflare/tracing.ts +109 -0
  152. package/src/component-utils.ts +19 -0
  153. package/src/components/DefaultDocument.tsx +8 -2
  154. package/src/context-var.ts +18 -6
  155. package/src/decode-loader-results.ts +52 -0
  156. package/src/defer.ts +196 -0
  157. package/src/deps/ssr.ts +0 -1
  158. package/src/encode-kv.ts +49 -0
  159. package/src/errors.ts +30 -4
  160. package/src/escape-script.ts +52 -0
  161. package/src/handle.ts +70 -22
  162. package/src/handles/MetaTags.tsx +62 -19
  163. package/src/handles/Scripts.tsx +183 -0
  164. package/src/handles/breadcrumbs.ts +37 -8
  165. package/src/handles/is-thenable.ts +19 -0
  166. package/src/handles/meta.ts +51 -40
  167. package/src/handles/script.ts +244 -0
  168. package/src/host/cookie-handler.ts +9 -60
  169. package/src/host/errors.ts +0 -24
  170. package/src/host/index.ts +8 -2
  171. package/src/host/pattern-matcher.ts +23 -52
  172. package/src/host/router.ts +107 -99
  173. package/src/host/testing.ts +40 -27
  174. package/src/host/types.ts +37 -4
  175. package/src/host/utils.ts +1 -1
  176. package/src/href-client.ts +137 -22
  177. package/src/index.rsc.ts +99 -13
  178. package/src/index.ts +139 -19
  179. package/src/internal-debug.ts +11 -10
  180. package/src/loader-store.ts +500 -0
  181. package/src/loader.rsc.ts +20 -13
  182. package/src/loader.ts +12 -11
  183. package/src/missing-id-error.ts +68 -0
  184. package/src/outlet-context.ts +1 -1
  185. package/src/outlet-provider.tsx +1 -5
  186. package/src/prerender/param-hash.ts +16 -16
  187. package/src/prerender/store.ts +37 -41
  188. package/src/prerender.ts +198 -82
  189. package/src/redirect-origin.ts +100 -0
  190. package/src/regex-escape.ts +8 -0
  191. package/src/render-error-thrower.tsx +20 -0
  192. package/src/response-utils.ts +62 -0
  193. package/src/reverse.ts +65 -15
  194. package/src/root-error-boundary.tsx +1 -19
  195. package/src/route-content-wrapper.tsx +19 -77
  196. package/src/route-definition/dsl-helpers.ts +461 -304
  197. package/src/route-definition/helper-factories.ts +28 -140
  198. package/src/route-definition/helpers-types.ts +143 -69
  199. package/src/route-definition/index.ts +4 -2
  200. package/src/route-definition/redirect.ts +51 -10
  201. package/src/route-definition/resolve-handler-use.ts +160 -0
  202. package/src/route-definition/use-item-types.ts +29 -0
  203. package/src/route-map-builder.ts +0 -16
  204. package/src/route-types.ts +37 -46
  205. package/src/router/basename.ts +14 -0
  206. package/src/router/content-negotiation.ts +164 -17
  207. package/src/router/error-handling.ts +45 -18
  208. package/src/router/find-match.ts +44 -23
  209. package/src/router/handler-context.ts +52 -31
  210. package/src/router/instrument.ts +350 -0
  211. package/src/router/intercept-resolution.ts +48 -24
  212. package/src/router/lazy-includes.ts +15 -52
  213. package/src/router/loader-resolution.ts +268 -56
  214. package/src/router/logging.ts +0 -6
  215. package/src/router/manifest.ts +40 -42
  216. package/src/router/match-api.ts +124 -204
  217. package/src/router/match-context.ts +0 -22
  218. package/src/router/match-handlers.ts +58 -58
  219. package/src/router/match-middleware/background-revalidation.ts +40 -24
  220. package/src/router/match-middleware/cache-lookup.ts +170 -276
  221. package/src/router/match-middleware/cache-store.ts +64 -52
  222. package/src/router/match-middleware/intercept-resolution.ts +0 -22
  223. package/src/router/match-middleware/segment-resolution.ts +45 -14
  224. package/src/router/match-pipelines.ts +1 -42
  225. package/src/router/match-result.ts +87 -39
  226. package/src/router/metrics.ts +0 -34
  227. package/src/router/middleware-types.ts +7 -140
  228. package/src/router/middleware.ts +266 -169
  229. package/src/router/navigation-snapshot.ts +131 -0
  230. package/src/router/params-util.ts +23 -0
  231. package/src/router/pattern-matching.ts +132 -90
  232. package/src/router/prefetch-cache-ttl.ts +51 -0
  233. package/src/router/prerender-match.ts +195 -56
  234. package/src/router/preview-match.ts +32 -102
  235. package/src/router/request-classification.ts +276 -0
  236. package/src/router/revalidation.ts +123 -73
  237. package/src/router/route-snapshot.ts +244 -0
  238. package/src/router/router-context.ts +3 -28
  239. package/src/router/router-interfaces.ts +115 -35
  240. package/src/router/router-options.ts +172 -15
  241. package/src/router/router-registry.ts +2 -5
  242. package/src/router/segment-resolution/fresh.ts +162 -84
  243. package/src/router/segment-resolution/helpers.ts +86 -6
  244. package/src/router/segment-resolution/loader-cache.ts +76 -39
  245. package/src/router/segment-resolution/revalidation.ts +351 -321
  246. package/src/router/segment-resolution/static-store.ts +19 -5
  247. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  248. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  249. package/src/router/segment-resolution.ts +5 -1
  250. package/src/router/segment-wrappers.ts +6 -5
  251. package/src/router/state-cookie-name.ts +33 -0
  252. package/src/router/substitute-pattern-params.ts +56 -0
  253. package/src/router/telemetry-otel.ts +161 -199
  254. package/src/router/telemetry.ts +96 -19
  255. package/src/router/timeout.ts +0 -20
  256. package/src/router/tracing.ts +206 -0
  257. package/src/router/trie-matching.ts +163 -59
  258. package/src/router/types.ts +9 -63
  259. package/src/router/url-params.ts +44 -0
  260. package/src/router.ts +157 -54
  261. package/src/rsc/handler-context.ts +3 -2
  262. package/src/rsc/handler.ts +655 -529
  263. package/src/rsc/helpers.ts +168 -46
  264. package/src/rsc/index.ts +2 -5
  265. package/src/rsc/json-route-result.ts +38 -0
  266. package/src/rsc/loader-fetch.ts +122 -31
  267. package/src/rsc/manifest-init.ts +33 -42
  268. package/src/rsc/origin-guard.ts +39 -25
  269. package/src/rsc/progressive-enhancement.ts +131 -14
  270. package/src/rsc/redirect-guard.ts +99 -0
  271. package/src/rsc/response-cache-serve.ts +238 -0
  272. package/src/rsc/response-error.ts +79 -12
  273. package/src/rsc/response-route-handler.ts +99 -189
  274. package/src/rsc/rsc-rendering.ts +109 -74
  275. package/src/rsc/runtime-warnings.ts +23 -10
  276. package/src/rsc/server-action.ts +287 -115
  277. package/src/rsc/ssr-setup.ts +18 -2
  278. package/src/rsc/transition-gate.ts +89 -0
  279. package/src/rsc/types.ts +29 -9
  280. package/src/runtime-env.ts +18 -0
  281. package/src/search-params.ts +35 -30
  282. package/src/segment-content-promise.ts +67 -0
  283. package/src/segment-loader-promise.ts +149 -0
  284. package/src/segment-system.tsx +236 -202
  285. package/src/serialize.ts +243 -0
  286. package/src/server/context.ts +224 -52
  287. package/src/server/cookie-parse.ts +32 -0
  288. package/src/server/cookie-store.ts +80 -5
  289. package/src/server/handle-store.ts +40 -38
  290. package/src/server/loader-registry.ts +38 -46
  291. package/src/server/request-context.ts +401 -173
  292. package/src/ssr/index.tsx +24 -16
  293. package/src/static-handler.ts +27 -18
  294. package/src/testing/cache-status.ts +162 -0
  295. package/src/testing/collect-handle.ts +40 -0
  296. package/src/testing/dispatch.ts +701 -0
  297. package/src/testing/dom.entry.ts +22 -0
  298. package/src/testing/e2e/fixture.ts +188 -0
  299. package/src/testing/e2e/index.ts +128 -0
  300. package/src/testing/e2e/matchers.ts +35 -0
  301. package/src/testing/e2e/page-helpers.ts +272 -0
  302. package/src/testing/e2e/parity.ts +387 -0
  303. package/src/testing/e2e/server.ts +195 -0
  304. package/src/testing/flight-matchers.ts +97 -0
  305. package/src/testing/flight-normalize.ts +11 -0
  306. package/src/testing/flight-runtime.d.ts +57 -0
  307. package/src/testing/flight-tree.ts +682 -0
  308. package/src/testing/flight.entry.ts +52 -0
  309. package/src/testing/flight.ts +257 -0
  310. package/src/testing/generated-routes.ts +183 -0
  311. package/src/testing/index.ts +105 -0
  312. package/src/testing/internal/context.ts +371 -0
  313. package/src/testing/internal/flight-client-globals.ts +30 -0
  314. package/src/testing/internal/seed-vars.ts +54 -0
  315. package/src/testing/render-handler.ts +357 -0
  316. package/src/testing/render-route.tsx +581 -0
  317. package/src/testing/run-loader.ts +385 -0
  318. package/src/testing/run-middleware.ts +205 -0
  319. package/src/testing/run-transition-when.ts +164 -0
  320. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  321. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  322. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  323. package/src/testing/vitest-stubs/version.ts +5 -0
  324. package/src/testing/vitest.ts +305 -0
  325. package/src/theme/ThemeProvider.tsx +20 -58
  326. package/src/theme/ThemeScript.tsx +7 -9
  327. package/src/theme/constants.ts +52 -13
  328. package/src/theme/index.ts +0 -7
  329. package/src/theme/theme-context.ts +1 -5
  330. package/src/theme/theme-script.ts +22 -21
  331. package/src/theme/use-theme.ts +0 -3
  332. package/src/types/boundaries.ts +0 -35
  333. package/src/types/cache-types.ts +17 -8
  334. package/src/types/error-types.ts +30 -90
  335. package/src/types/global-namespace.ts +54 -41
  336. package/src/types/handler-context.ts +125 -71
  337. package/src/types/index.ts +3 -10
  338. package/src/types/loader-types.ts +40 -11
  339. package/src/types/request-scope.ts +112 -0
  340. package/src/types/route-config.ts +6 -50
  341. package/src/types/route-entry.ts +12 -7
  342. package/src/types/segments.ts +136 -15
  343. package/src/urls/include-helper.ts +33 -70
  344. package/src/urls/index.ts +1 -11
  345. package/src/urls/path-helper-types.ts +68 -18
  346. package/src/urls/path-helper.ts +57 -111
  347. package/src/urls/pattern-types.ts +48 -19
  348. package/src/urls/response-types.ts +25 -22
  349. package/src/urls/type-extraction.ts +58 -139
  350. package/src/urls/urls-function.ts +1 -19
  351. package/src/use-loader.tsx +346 -89
  352. package/src/vite/debug.ts +185 -0
  353. package/src/vite/discovery/bundle-postprocess.ts +36 -38
  354. package/src/vite/discovery/discover-routers.ts +130 -85
  355. package/src/vite/discovery/discovery-errors.ts +194 -0
  356. package/src/vite/discovery/gate-state.ts +171 -0
  357. package/src/vite/discovery/prerender-collection.ts +214 -132
  358. package/src/vite/discovery/route-types-writer.ts +40 -84
  359. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  360. package/src/vite/discovery/state.ts +57 -4
  361. package/src/vite/discovery/virtual-module-codegen.ts +14 -34
  362. package/src/vite/index.ts +6 -0
  363. package/src/vite/inject-client-debug.ts +36 -0
  364. package/src/vite/plugin-types.ts +178 -5
  365. package/src/vite/plugins/cjs-to-esm.ts +16 -19
  366. package/src/vite/plugins/client-ref-dedup.ts +16 -11
  367. package/src/vite/plugins/client-ref-hashing.ts +28 -15
  368. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  369. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  370. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  371. package/src/vite/plugins/expose-action-id.ts +48 -95
  372. package/src/vite/plugins/expose-id-utils.ts +96 -51
  373. package/src/vite/plugins/expose-ids/export-analysis.ts +101 -34
  374. package/src/vite/plugins/expose-ids/handler-transform.ts +15 -64
  375. package/src/vite/plugins/expose-ids/loader-transform.ts +14 -24
  376. package/src/vite/plugins/expose-ids/router-transform.ts +118 -29
  377. package/src/vite/plugins/expose-internal-ids.ts +553 -317
  378. package/src/vite/plugins/performance-tracks.ts +64 -170
  379. package/src/vite/plugins/refresh-cmd.ts +89 -27
  380. package/src/vite/plugins/use-cache-transform.ts +73 -83
  381. package/src/vite/plugins/version-injector.ts +40 -29
  382. package/src/vite/plugins/version-plugin.ts +37 -40
  383. package/src/vite/plugins/virtual-entries.ts +39 -25
  384. package/src/vite/rango.ts +118 -114
  385. package/src/vite/router-discovery.ts +941 -142
  386. package/src/vite/utils/ast-handler-extract.ts +26 -35
  387. package/src/vite/utils/banner.ts +1 -1
  388. package/src/vite/utils/bundle-analysis.ts +10 -15
  389. package/src/vite/utils/client-chunks.ts +184 -0
  390. package/src/vite/utils/directive-prologue.ts +40 -0
  391. package/src/vite/utils/forward-user-plugins.ts +171 -0
  392. package/src/vite/utils/manifest-utils.ts +4 -59
  393. package/src/vite/utils/package-resolution.ts +20 -52
  394. package/src/vite/utils/prerender-utils.ts +81 -34
  395. package/src/vite/utils/shared-utils.ts +92 -42
  396. package/src/browser/action-response-classifier.ts +0 -99
  397. package/src/browser/debug-channel.ts +0 -93
  398. package/src/browser/react/use-client-cache.ts +0 -58
  399. package/src/browser/shallow.ts +0 -40
  400. package/src/handles/index.ts +0 -7
  401. package/src/network-error-thrower.tsx +0 -23
  402. package/src/router/middleware-cookies.ts +0 -55
@@ -10,13 +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 {
14
16
  formatNestedRouterConflictError,
15
17
  findNestedRouterConflict,
16
18
  findRouterFiles,
19
+ createScanFilter,
17
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";
18
23
  import { createVersionPlugin } from "./plugins/version-plugin.js";
19
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";
20
29
  import {
21
30
  exposeInternalIds,
22
31
  exposeRouterId,
@@ -29,7 +38,10 @@ import {
29
38
  type DiscoveryState,
30
39
  type PluginOptions,
31
40
  } from "./discovery/state.js";
32
- import { consumeSelfGenWrite } from "./discovery/self-gen-tracking.js";
41
+ import {
42
+ consumeSelfGenWrite,
43
+ peekSelfGenWrite,
44
+ } from "./discovery/self-gen-tracking.js";
33
45
  import { discoverRouters } from "./discovery/discover-routers.js";
34
46
  import {
35
47
  writeCombinedRouteTypesWithTracking,
@@ -41,10 +53,65 @@ import {
41
53
  generatePerRouterModule,
42
54
  } from "./discovery/virtual-module-codegen.js";
43
55
  import { postprocessBundle } from "./discovery/bundle-postprocess.js";
56
+ import { createDiscoveryGate } from "./discovery/gate-state.js";
44
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);
45
69
 
46
70
  export { VIRTUAL_ROUTES_MANIFEST_ID };
47
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
+
48
115
  // ============================================================================
49
116
  // Temp Server Factory
50
117
  // ============================================================================
@@ -64,15 +131,32 @@ async function createTempRscServer(
64
131
  state: DiscoveryState,
65
132
  options: { forceBuild?: boolean; cacheDir?: string } = {},
66
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();
67
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
+ };
68
151
  return createViteServer({
69
152
  root: state.projectRoot,
70
153
  configFile: false,
71
154
  server: { middlewareMode: true },
72
155
  appType: "custom",
73
156
  logLevel: "silent",
74
- resolve: { alias: state.userResolveAlias },
75
- esbuild: { jsx: "automatic", jsxImportSource: "react" },
157
+ resolve: resolveConfig,
158
+ ...(runnerConfig?.define ? { define: runnerConfig.define } : {}),
159
+ oxc: oxcConfig as any,
76
160
  ...(options.cacheDir && { cacheDir: options.cacheDir }),
77
161
  plugins: [
78
162
  rsc({
@@ -86,14 +170,124 @@ async function createTempRscServer(
86
170
  ...(options.forceBuild ? [hashClientRefs(state.projectRoot)] : []),
87
171
  createVersionPlugin(),
88
172
  createVirtualStubPlugin(),
173
+ createCloudflareProtocolStubPlugin(),
89
174
  // Dev prerender must use dev-mode IDs (path-based) to match the workerd
90
175
  // runtime. forceBuild produces hashed IDs for production bundle consistency.
91
176
  exposeInternalIds(options.forceBuild ? { forceBuild: true } : undefined),
92
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,
93
182
  ],
94
183
  });
95
184
  }
96
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
+
97
291
  /**
98
292
  * Plugin that discovers router instances at dev/build time via the RSC environment.
99
293
  *
@@ -111,61 +305,56 @@ export function createRouterDiscoveryPlugin(
111
305
  opts?: PluginOptions,
112
306
  ): Plugin {
113
307
  const s = createDiscoveryState(entryPath, opts);
308
+ let viteCommand: "serve" | "build" = "build";
309
+ let viteMode = "production";
114
310
 
115
311
  return {
116
312
  name: "@rangojs/router:discovery",
117
313
 
118
- config() {
119
- const config: any = {
120
- define: {
121
- __RANGO_DEBUG__: JSON.stringify(!!process.env.INTERNAL_RANGO_DEBUG),
122
- },
123
- };
124
- if (opts?.enableBuildPrerender) {
125
- config.environments = {
126
- rsc: {
127
- build: {
128
- rollupOptions: {
129
- output: {
130
- manualChunks(id: string) {
131
- if (s.resolvedPrerenderModules?.has(id)) {
132
- return "__prerender-handlers";
133
- }
134
- if (s.resolvedStaticModules?.has(id)) {
135
- return "__static-handlers";
136
- }
137
- },
138
- },
139
- },
140
- },
141
- },
142
- };
143
- }
144
- 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);
145
321
  },
146
322
 
147
323
  configResolved(config) {
148
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;
149
331
  s.isBuildMode = config.command === "build";
332
+ viteCommand = config.command as "serve" | "build";
333
+ viteMode = config.mode;
150
334
  // Capture user's resolve aliases for the temp server
151
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
+ );
152
348
  // Node preset: pick up auto-discovered router path from the config() hook.
153
349
  // The auto-discover plugin runs in config() using Vite's resolved root,
154
350
  // populating the mutable ref before configResolved fires.
155
351
  if (!s.resolvedEntryPath && opts?.routerPathRef?.path) {
156
352
  s.resolvedEntryPath = opts.routerPathRef.path;
157
353
  }
158
- // Cloudflare preset: read entry from resolved environment config.
159
- // The @cloudflare/vite-plugin reads wrangler config (toml/json/jsonc)
160
- // and sets optimizeDeps.entries on the RSC environment.
354
+ // Cloudflare preset: entry comes from the resolved RSC env config.
161
355
  if (!s.resolvedEntryPath) {
162
- const rscEnvConfig = (config.environments as any)?.["rsc"];
163
- const entries = rscEnvConfig?.optimizeDeps?.entries;
164
- if (typeof entries === "string") {
165
- s.resolvedEntryPath = entries;
166
- } else if (Array.isArray(entries) && entries.length > 0) {
167
- s.resolvedEntryPath = entries[0];
168
- }
356
+ const entry = resolveRscEntryFromConfig(config);
357
+ if (entry) s.resolvedEntryPath = entry;
169
358
  }
170
359
  // Generate combined named-routes.gen.ts from static source parsing.
171
360
  // Runs before the dev server starts so the gen file exists immediately for IDE.
@@ -204,6 +393,17 @@ export function createRouterDiscoveryPlugin(
204
393
  resolveDiscovery = resolve;
205
394
  });
206
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
+
207
407
  // Compute dev server origin from resolved URLs (preferred) or config port (fallback).
208
408
  // Called after discovery (or in the load hook) when the server may be listening.
209
409
  const getDevServerOrigin = () =>
@@ -217,18 +417,113 @@ export function createRouterDiscoveryPlugin(
217
417
  let prerenderTempServer: any = null;
218
418
  let prerenderNodeRegistry: Map<string, any> | null = null;
219
419
 
220
- // 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
221
421
  server.httpServer?.on("close", () => {
222
422
  if (prerenderTempServer) {
223
423
  prerenderTempServer.close().catch(() => {});
224
424
  prerenderTempServer = null;
225
425
  }
426
+ releaseBuildEnv(s).catch(() => {});
226
427
  });
227
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
+
228
469
  async function getOrCreateTempServer(): Promise<any | null> {
229
- if (prerenderNodeRegistry) {
230
- 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
+ }
231
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
+ );
232
527
  try {
233
528
  prerenderTempServer = await createTempRscServer(s, {
234
529
  cacheDir: "node_modules/.vite_prerender",
@@ -236,58 +531,189 @@ export function createRouterDiscoveryPlugin(
236
531
 
237
532
  const tempRscEnv = (prerenderTempServer.environments as any)?.rsc;
238
533
  if (tempRscEnv?.runner) {
239
- await tempRscEnv.runner.import(s.resolvedEntryPath!);
240
- const serverMod = await tempRscEnv.runner.import(
241
- "@rangojs/router/server",
242
- );
243
- prerenderNodeRegistry = serverMod.RouterRegistry;
534
+ await importEntryAndRegistry(tempRscEnv);
244
535
  return tempRscEnv;
245
536
  }
537
+ debugDiscovery?.(
538
+ "getOrCreateTempServer: tempRscEnv.runner unavailable",
539
+ );
246
540
  } catch (err: any) {
247
- console.warn(
248
- `[rsc-router] Failed to create temp runner: ${err.message}`,
541
+ debugDiscovery?.(
542
+ "getOrCreateTempServer: FAILED message=%s",
543
+ err.message,
249
544
  );
545
+ console.warn(`[rango] Failed to create temp runner: ${err.message}`);
250
546
  }
251
547
  return null;
252
548
  }
253
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
+
254
648
  const discover = async () => {
649
+ const discoverStart = performance.now();
255
650
  const rscEnv = (server.environments as any)?.rsc;
256
651
  if (!rscEnv?.runner) {
257
652
  // Cloudflare dev: no module runner available (workerd-based RSC env).
258
653
  // Set devServerOrigin so the virtual module can inject __PRERENDER_DEV_URL
259
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
+ );
260
659
  s.devServerOrigin = getDevServerOrigin();
261
660
 
262
661
  // Create a temp Node.js server to run runtime discovery and generate
263
662
  // named route types (static parser can't resolve factory calls).
264
663
  try {
265
- 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
+ );
266
674
  if (tempRscEnv) {
267
- await discoverRouters(s, tempRscEnv);
268
- writeRouteTypesFiles(s);
675
+ await timed(debugDiscovery, "discoverRouters (cloudflare)", () =>
676
+ discoverRouters(s, tempRscEnv),
677
+ );
678
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
679
+ writeRouteTypesFiles(s),
680
+ );
269
681
  }
270
682
  } catch (err: any) {
271
683
  console.warn(
272
- `[rsc-router] Cloudflare dev discovery failed: ${err.message}\n${err.stack}`,
684
+ `[rango] Cloudflare dev discovery failed: ${err.message}\n${err.stack}`,
273
685
  );
274
686
  }
275
687
 
688
+ debugDiscovery?.(
689
+ "dev discovery done (%sms)",
690
+ (performance.now() - discoverStart).toFixed(1),
691
+ );
276
692
  resolveDiscovery!();
277
693
  return;
278
694
  }
279
695
 
280
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
+
281
703
  // Set the readiness gate BEFORE discovery so early requests
282
704
  // block until manifest is populated
283
- const serverMod = await rscEnv.runner.import(
284
- "@rangojs/router/server",
705
+ const serverMod = await timed(
706
+ debugDiscovery,
707
+ "import @rangojs/router/server",
708
+ () => rscEnv.runner.import("@rangojs/router/server"),
285
709
  );
286
710
  if (serverMod?.setManifestReadyPromise) {
287
711
  serverMod.setManifestReadyPromise(discoveryPromise);
288
712
  }
289
713
 
290
- await discoverRouters(s, rscEnv);
714
+ await timed(debugDiscovery, "discoverRouters", () =>
715
+ discoverRouters(s, rscEnv),
716
+ );
291
717
 
292
718
  // Store server origin for dev prerender endpoint (virtual module injection)
293
719
  s.devServerOrigin = getDevServerOrigin();
@@ -297,24 +723,36 @@ export function createRouterDiscoveryPlugin(
297
723
  // routes (e.g. Array.from loops) that the static parser cannot see.
298
724
  // writeRouteTypesFiles() only writes when content changes, so this
299
725
  // won't cause unnecessary HMR triggers.
300
- writeRouteTypesFiles(s);
726
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
727
+ writeRouteTypesFiles(s),
728
+ );
301
729
 
302
730
  // Populate the route map and per-router data in the RSC env
303
- await propagateDiscoveryState(rscEnv);
731
+ await timed(debugDiscovery, "propagateDiscoveryState", () =>
732
+ propagateDiscoveryState(rscEnv),
733
+ );
304
734
  } catch (err: any) {
305
735
  console.warn(
306
- `[rsc-router] Router discovery failed: ${err.message}\n${err.stack}`,
736
+ `[rango] Router discovery failed: ${err.message}\n${err.stack}`,
307
737
  );
308
738
  } finally {
739
+ debugDiscovery?.(
740
+ "dev discovery done (%sms)",
741
+ (performance.now() - discoverStart).toFixed(1),
742
+ );
309
743
  resolveDiscovery!();
310
744
  }
311
745
  };
312
746
 
313
747
  // Schedule after all plugins have finished configureServer.
314
- // Store the promise so the virtual module's load hook can await it.
315
- s.discoveryDone = new Promise<void>((resolve) => {
316
- setTimeout(() => discover().then(resolve, resolve), 0);
317
- });
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
+ );
318
756
 
319
757
  // Dev-mode on-demand prerender endpoint.
320
758
  // When workerd hits a prerender route, it fetches this endpoint instead of
@@ -354,24 +792,30 @@ export function createRouterDiscoveryPlugin(
354
792
  if (s.mergedRouteTrie && serverMod.setRouteTrie) {
355
793
  serverMod.setRouteTrie(s.mergedRouteTrie);
356
794
  }
357
- if (serverMod.setRouterManifest) {
358
- for (const [routerId, manifest] of s.perRouterManifestDataMap) {
359
- serverMod.setRouterManifest(routerId, manifest);
360
- }
361
- }
362
- if (serverMod.setRouterTrie) {
363
- for (const [routerId, trie] of s.perRouterTrieMap) {
364
- serverMod.setRouterTrie(routerId, trie);
365
- }
366
- }
367
- if (serverMod.setRouterPrecomputedEntries) {
368
- for (const [routerId, entries] of s.perRouterPrecomputedMap) {
369
- serverMod.setRouterPrecomputedEntries(routerId, entries);
370
- }
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);
371
804
  }
372
805
  };
373
806
 
374
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
+
375
819
  if (s.discoveryDone) await s.discoveryDone;
376
820
 
377
821
  const url = new URL(req.url || "/", "http://localhost");
@@ -379,12 +823,36 @@ export function createRouterDiscoveryPlugin(
379
823
  if (!pathname) {
380
824
  res.statusCode = 400;
381
825
  res.end("Missing pathname");
826
+ logResult(400, "missing pathname");
382
827
  return;
383
828
  }
384
829
 
385
- // Prefer the main server's registry (Node.js preset: module runner available).
386
- // Fall back to a temp server for Cloudflare where the main RSC env uses workerd.
387
- 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
+ }
388
856
 
389
857
  if (!registry) {
390
858
  // No main registry: the RSC env has no module runner (Cloudflare dev).
@@ -398,6 +866,7 @@ export function createRouterDiscoveryPlugin(
398
866
  if (!registry || registry.size === 0) {
399
867
  res.statusCode = 503;
400
868
  res.end("Prerender runner not available");
869
+ logResult(503, "no registry");
401
870
  return;
402
871
  }
403
872
 
@@ -413,6 +882,8 @@ export function createRouterDiscoveryPlugin(
413
882
  {},
414
883
  undefined,
415
884
  wantPassthrough,
885
+ s.resolvedBuildEnv,
886
+ true, // devMode: check getParams for passthrough routes
416
887
  );
417
888
  if (!result) continue;
418
889
  if (result.passthrough) continue;
@@ -425,25 +896,32 @@ export function createRouterDiscoveryPlugin(
425
896
  if (wantIntercept && result.interceptSegments?.length) {
426
897
  payload = {
427
898
  segments: [...result.segments, ...result.interceptSegments],
428
- handles: {
429
- ...result.handles,
430
- ...(result.interceptHandles || {}),
431
- },
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 ?? "",
432
902
  };
433
903
  } else {
434
904
  payload = { segments: result.segments, handles: result.handles };
435
905
  }
436
906
  res.end(JSON.stringify(payload));
907
+ logResult(200, `match ${result.routeName}`);
437
908
  return;
438
909
  } catch (err: any) {
439
- console.warn(
440
- `[rsc-router] Dev prerender failed for ${pathname}: ${err.message}`,
441
- );
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
+ }
442
919
  }
443
920
  }
444
921
 
445
922
  res.statusCode = 404;
446
923
  res.end("No prerender match");
924
+ logResult(404, "no match");
447
925
  });
448
926
 
449
927
  // Watch url module and router files for changes and regenerate named-routes.gen.ts.
@@ -486,21 +964,135 @@ export function createRouterDiscoveryPlugin(
486
964
 
487
965
  // Re-run runtime discovery so factory-generated routes that the
488
966
  // static parser cannot see are refreshed after source changes.
489
- 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.
490
970
  const refreshRuntimeDiscovery = async () => {
491
971
  const rscEnv = (server.environments as any)?.rsc;
492
- if (!rscEnv?.runner || runtimeRediscoveryInProgress) return;
493
- 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;
494
1081
  try {
495
- await discoverRouters(s, rscEnv);
496
- writeRouteTypesFiles(s);
497
- 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
+ );
498
1091
  } catch (err: any) {
499
- console.warn(
500
- `[rsc-router] Runtime re-discovery failed: ${err.message}`,
1092
+ debugDiscovery?.(
1093
+ "hmr: workerd reload failed: %s",
1094
+ err?.message ?? err,
501
1095
  );
502
- } finally {
503
- runtimeRediscoveryInProgress = false;
504
1096
  }
505
1097
  };
506
1098
 
@@ -508,23 +1100,50 @@ export function createRouterDiscoveryPlugin(
508
1100
  clearTimeout(routeChangeTimer);
509
1101
  routeChangeTimer = setTimeout(() => {
510
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;
511
1107
  try {
512
- writeCombinedRouteTypesWithTracking(s);
513
- if (s.perRouterManifests.length > 0) {
514
- 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
+ }
515
1125
  }
516
1126
  } catch (err: any) {
517
- console.error(
518
- `[rsc-router] Route regeneration error: ${err.message}`,
519
- );
1127
+ console.error(`[rango] Route regeneration error: ${err.message}`);
520
1128
  }
1129
+ debugDiscovery?.(
1130
+ "watcher: regenerated gen files (%sms)",
1131
+ (performance.now() - regenStart).toFixed(1),
1132
+ );
521
1133
  // Async: re-run runtime discovery to refresh factory-generated
522
- // routes that the static parser cannot resolve.
1134
+ // routes that the static parser cannot resolve. Resolves the
1135
+ // discovery gate when complete.
523
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.
524
1140
  refreshRuntimeDiscovery().catch((err: any) => {
525
1141
  console.warn(
526
- `[rsc-router] Runtime re-discovery error: ${err.message}`,
1142
+ `[rango] Runtime re-discovery error: ${err.message}`,
527
1143
  );
1144
+ // Even on error, unblock the gate so workerd's reload doesn't
1145
+ // hang indefinitely against the previous manifest.
1146
+ resolveDiscoveryGate();
528
1147
  });
529
1148
  }
530
1149
  }, 100);
@@ -537,21 +1156,74 @@ export function createRouterDiscoveryPlugin(
537
1156
  !filePath.endsWith(".tsx") &&
538
1157
  !filePath.endsWith(".js") &&
539
1158
  !filePath.endsWith(".jsx")
540
- )
1159
+ ) {
1160
+ if (s.lastDiscoveryError) {
1161
+ debugDiscovery?.(
1162
+ "watcher: skip non-source %s [LASTERR %s]",
1163
+ filePath,
1164
+ s.lastDiscoveryError.message,
1165
+ );
1166
+ }
541
1167
  return;
1168
+ }
542
1169
  // Apply scan filter as early-exit before reading file
543
- 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;
544
1189
  try {
545
1190
  const source = readFileSync(filePath, "utf-8");
546
1191
  const trimmed = source.trimStart();
547
- if (
1192
+ const isUseClient =
548
1193
  trimmed.startsWith('"use client"') ||
549
- trimmed.startsWith("'use client'")
550
- )
551
- return;
552
- const hasUrls = source.includes("urls(");
553
- const hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
554
- 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
+ }
555
1227
  // Invalidate cache when a router file changes (new router added/removed)
556
1228
  if (hasCreateRouter) {
557
1229
  const nestedRouterConflict = findNestedRouterConflict([
@@ -566,8 +1238,27 @@ export function createRouterDiscoveryPlugin(
566
1238
  }
567
1239
  s.cachedRouterFiles = undefined;
568
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
+ }
569
1252
  scheduleRouteRegeneration();
570
- } 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
+ }
571
1262
  // Ignore read errors for deleted/moved files
572
1263
  }
573
1264
  };
@@ -596,11 +1287,24 @@ export function createRouterDiscoveryPlugin(
596
1287
  async buildStart() {
597
1288
  if (!s.isBuildMode) return;
598
1289
  // Only run once across environment builds
599
- 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 ?? "?");
600
1299
  resetStagedBuildAssets(s.projectRoot);
601
1300
  s.prerenderManifestEntries = null;
602
1301
  s.staticManifestEntries = null;
603
1302
 
1303
+ // Acquire build-time env bindings if configured
1304
+ await timed(debugDiscovery, "build acquireBuildEnv", () =>
1305
+ acquireBuildEnv(s, viteCommand, viteMode),
1306
+ );
1307
+
604
1308
  let tempServer: any = null;
605
1309
  // Signal to user-space code (e.g. reverse.ts) that build-time discovery
606
1310
  // is active. Uses globalThis because the temp server's module runner
@@ -608,12 +1312,16 @@ export function createRouterDiscoveryPlugin(
608
1312
  // between the vite plugin and user code loaded via runner.import().
609
1313
  (globalThis as any).__rscRouterDiscoveryActive = true;
610
1314
  try {
611
- tempServer = await createTempRscServer(s, { forceBuild: true });
1315
+ tempServer = await timed(
1316
+ debugDiscovery,
1317
+ "build createTempRscServer",
1318
+ () => createTempRscServer(s, { forceBuild: true }),
1319
+ );
612
1320
 
613
1321
  const rscEnv = (tempServer.environments as any)?.rsc;
614
1322
  if (!rscEnv?.runner) {
615
1323
  console.warn(
616
- "[rsc-router] RSC environment runner not available during build, skipping manifest generation",
1324
+ "[rango] RSC environment runner not available during build, skipping manifest generation",
617
1325
  );
618
1326
  return;
619
1327
  }
@@ -628,11 +1336,15 @@ export function createRouterDiscoveryPlugin(
628
1336
  s.resolvedStaticModules = tempIdsPlugin.api.staticHandlerModules;
629
1337
  }
630
1338
 
631
- await discoverRouters(s, rscEnv);
1339
+ await timed(debugDiscovery, "build discoverRouters", () =>
1340
+ discoverRouters(s, rscEnv),
1341
+ );
632
1342
  // Update named-routes.gen.ts from runtime discovery.
633
1343
  // The runtime manifest includes dynamically generated routes
634
1344
  // that the static parser cannot extract from source code.
635
- writeRouteTypesFiles(s);
1345
+ timedSync(debugDiscovery, "build writeRouteTypesFiles", () =>
1346
+ writeRouteTypesFiles(s),
1347
+ );
636
1348
  } catch (err: any) {
637
1349
  // Extract the user source file from the stack trace (skip internal frames)
638
1350
  const sourceFile = err.stack
@@ -652,13 +1364,50 @@ export function createRouterDiscoveryPlugin(
652
1364
  .filter(Boolean)
653
1365
  .join("\n");
654
1366
  throw new Error(
655
- `[rsc-router] Build-time router discovery failed:\n${details}`,
1367
+ `[rango] Build-time router discovery failed:\n${details}`,
1368
+ { cause: err },
656
1369
  );
657
1370
  } finally {
658
1371
  delete (globalThis as any).__rscRouterDiscoveryActive;
659
1372
  if (tempServer) {
660
- await tempServer.close();
1373
+ await timed(debugDiscovery, "build tempServer.close", () =>
1374
+ tempServer.close(),
1375
+ );
661
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 [];
662
1411
  }
663
1412
  },
664
1413
 
@@ -682,19 +1431,38 @@ export function createRouterDiscoveryPlugin(
682
1431
  // This is critical for Cloudflare dev where the worker runs in a separate
683
1432
  // Miniflare process and can only receive manifest data via the virtual module.
684
1433
  if (s.discoveryDone) {
685
- await s.discoveryDone;
1434
+ await timed(
1435
+ debugRoutes,
1436
+ "await discoveryDone (manifest)",
1437
+ () => s.discoveryDone,
1438
+ );
686
1439
  }
687
- 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;
688
1447
  }
689
1448
  // Per-router virtual modules: pure data exports (no side effects).
690
1449
  // ensureRouterManifest() imports the module and stores the data.
691
1450
  const perRouterPrefix = "\0" + VIRTUAL_ROUTES_MANIFEST_ID + "/";
692
1451
  if (id.startsWith(perRouterPrefix)) {
693
1452
  if (s.discoveryDone) {
694
- await s.discoveryDone;
1453
+ await timed(
1454
+ debugRoutes,
1455
+ "await discoveryDone (per-router)",
1456
+ () => s.discoveryDone,
1457
+ );
695
1458
  }
696
1459
  const routerId = id.slice(perRouterPrefix.length);
697
- return generatePerRouterModule(s, routerId);
1460
+ const code = await timed(
1461
+ debugRoutes,
1462
+ `generatePerRouterModule ${routerId}`,
1463
+ () => generatePerRouterModule(s, routerId),
1464
+ );
1465
+ return code;
698
1466
  }
699
1467
  // virtual:rsc-router/prerender-paths load handler removed
700
1468
  return null;
@@ -704,6 +1472,7 @@ export function createRouterDiscoveryPlugin(
704
1472
  // Used by closeBundle for handler code eviction and prerender data injection.
705
1473
  generateBundle(_options: any, bundle: any) {
706
1474
  if (this.environment?.name !== "rsc") return;
1475
+ const genStart = debugBuild ? performance.now() : 0;
707
1476
 
708
1477
  // Record RSC entry chunk filename for closeBundle injection
709
1478
  for (const [fileName, chunk] of Object.entries(bundle) as [
@@ -716,8 +1485,19 @@ export function createRouterDiscoveryPlugin(
716
1485
  }
717
1486
  }
718
1487
 
719
- 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
+ );
720
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();
721
1501
 
722
1502
  for (const [fileName, chunk] of Object.entries(bundle) as [
723
1503
  string,
@@ -725,27 +1505,28 @@ export function createRouterDiscoveryPlugin(
725
1505
  ][]) {
726
1506
  if (chunk.type !== "chunk") continue;
727
1507
 
728
- // Prerender handlers chunk
729
- if (
730
- fileName.includes("__prerender-handlers") &&
731
- s.resolvedPrerenderModules?.size
732
- ) {
1508
+ // Scan all chunks for handler exports (handlers may land in any chunk)
1509
+ if (s.resolvedPrerenderModules?.size) {
733
1510
  const handlers = extractHandlerExportsFromChunk(
734
1511
  chunk.code,
735
1512
  s.resolvedPrerenderModules,
736
1513
  "Prerender",
737
- true,
1514
+ false,
738
1515
  );
739
1516
  if (handlers.length > 0) {
740
- 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
+ }
741
1526
  }
742
1527
  }
743
1528
 
744
- // Static handlers chunk
745
- if (
746
- fileName.includes("__static-handlers") &&
747
- s.resolvedStaticModules?.size
748
- ) {
1529
+ if (s.resolvedStaticModules?.size) {
749
1530
  const handlers = extractHandlerExportsFromChunk(
750
1531
  chunk.code,
751
1532
  s.resolvedStaticModules,
@@ -753,10 +1534,26 @@ export function createRouterDiscoveryPlugin(
753
1534
  false,
754
1535
  );
755
1536
  if (handlers.length > 0) {
756
- 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
+ }
757
1546
  }
758
1547
  }
759
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
+ );
760
1557
  },
761
1558
 
762
1559
  // Build-time pre-rendering: evict handler code and inject collected prerender data.
@@ -770,7 +1567,9 @@ export function createRouterDiscoveryPlugin(
770
1567
  // Only run for the RSC environment — other environments (client, ssr) have
771
1568
  // no prerender/static data to process and would just do redundant file I/O.
772
1569
  if (this.environment && this.environment.name !== "rsc") return;
773
- postprocessBundle(s);
1570
+ timedSync(debugBuild, "closeBundle postprocessBundle", () =>
1571
+ postprocessBundle(s),
1572
+ );
774
1573
  },
775
1574
  },
776
1575
  };