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

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