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