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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (460) hide show
  1. package/AGENTS.md +17 -0
  2. package/README.md +432 -7
  3. package/dist/bin/rango.js +2073 -213
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +7258 -2714
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +140 -67
  8. package/skills/api-client/SKILL.md +211 -0
  9. package/skills/breadcrumbs/SKILL.md +329 -0
  10. package/skills/bundle-analysis/SKILL.md +159 -0
  11. package/skills/cache-guide/SKILL.md +487 -0
  12. package/skills/caching/SKILL.md +357 -25
  13. package/skills/comparison/SKILL.md +50 -0
  14. package/skills/comparison/agents/openai.yaml +4 -0
  15. package/skills/comparison/references/framework-comparison.md +837 -0
  16. package/skills/composability/SKILL.md +246 -0
  17. package/skills/css/SKILL.md +76 -0
  18. package/skills/debug-manifest/SKILL.md +16 -10
  19. package/skills/document-cache/SKILL.md +87 -62
  20. package/skills/fonts/SKILL.md +6 -4
  21. package/skills/handler-use/SKILL.md +364 -0
  22. package/skills/hooks/SKILL.md +557 -79
  23. package/skills/host-router/SKILL.md +320 -0
  24. package/skills/i18n/SKILL.md +276 -0
  25. package/skills/intercept/SKILL.md +207 -15
  26. package/skills/layout/SKILL.md +146 -6
  27. package/skills/links/SKILL.md +304 -25
  28. package/skills/loader/SKILL.md +616 -54
  29. package/skills/middleware/SKILL.md +217 -37
  30. package/skills/migrate-nextjs/SKILL.md +611 -0
  31. package/skills/migrate-react-router/SKILL.md +927 -0
  32. package/skills/mime-routes/SKILL.md +42 -11
  33. package/skills/observability/SKILL.md +194 -0
  34. package/skills/parallel/SKILL.md +284 -3
  35. package/skills/ppr/SKILL.md +293 -0
  36. package/skills/prerender/SKILL.md +437 -52
  37. package/skills/rango/SKILL.md +369 -22
  38. package/skills/react-compiler/SKILL.md +168 -0
  39. package/skills/response-routes/SKILL.md +263 -121
  40. package/skills/route/SKILL.md +350 -21
  41. package/skills/router-setup/SKILL.md +246 -33
  42. package/skills/scripts/SKILL.md +179 -0
  43. package/skills/server-actions/SKILL.md +775 -0
  44. package/skills/shell-manifest/SKILL.md +185 -0
  45. package/skills/streams-and-websockets/SKILL.md +283 -0
  46. package/skills/tailwind/SKILL.md +27 -3
  47. package/skills/testing/SKILL.md +126 -222
  48. package/skills/testing/bindings.md +103 -0
  49. package/skills/testing/cache-prerender.md +127 -0
  50. package/skills/testing/client-components.md +124 -0
  51. package/skills/testing/e2e-parity.md +125 -0
  52. package/skills/testing/flight.md +91 -0
  53. package/skills/testing/handles.md +131 -0
  54. package/skills/testing/loader.md +128 -0
  55. package/skills/testing/middleware.md +99 -0
  56. package/skills/testing/render-handler.md +122 -0
  57. package/skills/testing/response-routes.md +95 -0
  58. package/skills/testing/reverse-and-types.md +85 -0
  59. package/skills/testing/server-actions.md +107 -0
  60. package/skills/testing/server-tree.md +128 -0
  61. package/skills/testing/setup.md +123 -0
  62. package/skills/theme/SKILL.md +9 -8
  63. package/skills/typesafety/SKILL.md +532 -103
  64. package/skills/use-cache/SKILL.md +367 -0
  65. package/skills/vercel/SKILL.md +128 -0
  66. package/skills/view-transitions/SKILL.md +337 -0
  67. package/src/__augment-tests__/augment.ts +81 -0
  68. package/src/__augment-tests__/augmented.check.ts +116 -0
  69. package/src/__internal.ts +77 -44
  70. package/src/bin/rango.ts +312 -15
  71. package/src/browser/action-coordinator.ts +114 -0
  72. package/src/browser/action-fence.ts +47 -0
  73. package/src/browser/app-shell.ts +39 -0
  74. package/src/browser/app-version.ts +14 -0
  75. package/src/browser/connection-warmup.ts +134 -0
  76. package/src/browser/cookie-name.ts +140 -0
  77. package/src/browser/event-controller.ts +293 -202
  78. package/src/browser/history-state.ts +101 -0
  79. package/src/browser/index.ts +3 -3
  80. package/src/browser/intercept-utils.ts +52 -0
  81. package/src/browser/invalidate-client-cache.ts +52 -0
  82. package/src/browser/link-interceptor.ts +24 -4
  83. package/src/browser/logging.ts +11 -0
  84. package/src/browser/merge-segment-loaders.ts +20 -12
  85. package/src/browser/navigation-bridge.ts +385 -576
  86. package/src/browser/navigation-client.ts +245 -75
  87. package/src/browser/navigation-store-handle.ts +38 -0
  88. package/src/browser/navigation-store.ts +184 -118
  89. package/src/browser/navigation-transaction.ts +247 -0
  90. package/src/browser/network-error-handler.ts +88 -0
  91. package/src/browser/partial-update.ts +412 -364
  92. package/src/browser/prefetch/cache.ts +359 -0
  93. package/src/browser/prefetch/fetch.ts +452 -0
  94. package/src/browser/prefetch/observer.ts +65 -0
  95. package/src/browser/prefetch/policy.ts +48 -0
  96. package/src/browser/prefetch/queue.ts +209 -0
  97. package/src/browser/prefetch/resource-ready.ts +77 -0
  98. package/src/browser/rango-state.ts +194 -0
  99. package/src/browser/react/Link.tsx +275 -68
  100. package/src/browser/react/NavigationProvider.tsx +265 -109
  101. package/src/browser/react/ScrollRestoration.tsx +10 -6
  102. package/src/browser/react/context.ts +11 -0
  103. package/src/browser/react/filter-segment-order.ts +70 -0
  104. package/src/browser/react/index.ts +0 -48
  105. package/src/browser/react/location-state-shared.ts +272 -60
  106. package/src/browser/react/location-state.ts +90 -20
  107. package/src/browser/react/mount-context.ts +6 -1
  108. package/src/browser/react/nonce-context.ts +23 -0
  109. package/src/browser/react/shallow-equal.ts +27 -0
  110. package/src/browser/react/use-action.ts +35 -66
  111. package/src/browser/react/use-handle.ts +39 -126
  112. package/src/browser/react/use-href.tsx +8 -1
  113. package/src/browser/react/use-link-status.ts +39 -13
  114. package/src/browser/react/use-navigation.ts +53 -69
  115. package/src/browser/react/use-params.ts +75 -0
  116. package/src/browser/react/use-pathname.ts +47 -0
  117. package/src/browser/react/use-reverse.ts +106 -0
  118. package/src/browser/react/use-router.ts +98 -0
  119. package/src/browser/react/use-search-params.ts +51 -0
  120. package/src/browser/react/use-segments.ts +72 -99
  121. package/src/browser/response-adapter.ts +164 -0
  122. package/src/browser/rsc-router.tsx +300 -72
  123. package/src/browser/scroll-restoration.ts +138 -50
  124. package/src/browser/segment-reconciler.ts +243 -0
  125. package/src/browser/segment-structure-assert.ts +17 -1
  126. package/src/browser/server-action-bridge.ts +668 -613
  127. package/src/browser/types.ts +223 -51
  128. package/src/browser/validate-redirect-origin.ts +56 -0
  129. package/src/build/collect-fallback-refs.ts +107 -0
  130. package/src/build/generate-manifest.ts +252 -161
  131. package/src/build/generate-route-types.ts +41 -1038
  132. package/src/build/index.ts +12 -7
  133. package/src/build/prefix-tree-utils.ts +123 -0
  134. package/src/build/route-trie.ts +225 -42
  135. package/src/build/route-types/ast-helpers.ts +25 -0
  136. package/src/build/route-types/ast-route-extraction.ts +105 -0
  137. package/src/build/route-types/codegen.ts +113 -0
  138. package/src/build/route-types/include-resolution.ts +812 -0
  139. package/src/build/route-types/param-extraction.ts +51 -0
  140. package/src/build/route-types/per-module-writer.ts +144 -0
  141. package/src/build/route-types/router-processing.ts +695 -0
  142. package/src/build/route-types/scan-filter.ts +85 -0
  143. package/src/build/route-types/source-scan.ts +216 -0
  144. package/src/build/runtime-discovery.ts +223 -0
  145. package/src/cache/background-task.ts +34 -0
  146. package/src/cache/cache-error.ts +104 -0
  147. package/src/cache/cache-key-utils.ts +60 -0
  148. package/src/cache/cache-policy.ts +199 -0
  149. package/src/cache/cache-runtime.ts +525 -0
  150. package/src/cache/cache-scope.ts +298 -332
  151. package/src/cache/cache-tag.ts +103 -0
  152. package/src/cache/cf/cf-base64.ts +33 -0
  153. package/src/cache/cf/cf-cache-constants.ts +127 -0
  154. package/src/cache/cf/cf-cache-store.ts +2508 -158
  155. package/src/cache/cf/cf-cache-types.ts +349 -0
  156. package/src/cache/cf/cf-kv-utils.ts +46 -0
  157. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  158. package/src/cache/cf/index.ts +17 -17
  159. package/src/cache/document-cache.ts +199 -92
  160. package/src/cache/handle-capture.ts +81 -0
  161. package/src/cache/handle-snapshot.ts +111 -0
  162. package/src/cache/index.ts +24 -35
  163. package/src/cache/memory-segment-store.ts +363 -30
  164. package/src/cache/profile-registry.ts +88 -0
  165. package/src/cache/read-through-swr.ts +178 -0
  166. package/src/cache/segment-codec.ts +248 -0
  167. package/src/cache/shell-snapshot.ts +368 -0
  168. package/src/cache/tag-invalidation.ts +230 -0
  169. package/src/cache/taint.ts +153 -0
  170. package/src/cache/types.ts +222 -211
  171. package/src/cache/vercel/index.ts +11 -0
  172. package/src/cache/vercel/vercel-cache-store.ts +1113 -0
  173. package/src/client.rsc.tsx +43 -21
  174. package/src/client.tsx +131 -347
  175. package/src/cloudflare/index.ts +11 -0
  176. package/src/cloudflare/tracing.ts +109 -0
  177. package/src/component-utils.ts +23 -4
  178. package/src/components/DefaultDocument.tsx +13 -3
  179. package/src/context-var.ts +168 -0
  180. package/src/debug.ts +19 -9
  181. package/src/decode-loader-results.ts +52 -0
  182. package/src/defer.ts +185 -0
  183. package/src/deps/ssr.ts +0 -1
  184. package/src/encode-kv.ts +49 -0
  185. package/src/errors.ts +106 -10
  186. package/src/escape-script.ts +52 -0
  187. package/src/handle.ts +110 -35
  188. package/src/handles/MetaTags.tsx +83 -59
  189. package/src/handles/Scripts.tsx +183 -0
  190. package/src/handles/breadcrumbs.ts +93 -0
  191. package/src/handles/deferred-resolution.ts +127 -0
  192. package/src/handles/is-thenable.ts +18 -0
  193. package/src/handles/meta.ts +44 -53
  194. package/src/handles/script.ts +244 -0
  195. package/src/host/cookie-handler.ts +20 -65
  196. package/src/host/errors.ts +21 -30
  197. package/src/host/index.ts +13 -9
  198. package/src/host/pattern-matcher.ts +50 -79
  199. package/src/host/router.ts +151 -121
  200. package/src/host/testing.ts +45 -32
  201. package/src/host/types.ts +52 -11
  202. package/src/host/utils.ts +2 -2
  203. package/src/href-client.ts +192 -57
  204. package/src/index.rsc.ts +173 -35
  205. package/src/index.ts +241 -73
  206. package/src/internal-debug.ts +9 -2
  207. package/src/loader-store.ts +500 -0
  208. package/src/loader.rsc.ts +31 -99
  209. package/src/loader.ts +30 -12
  210. package/src/missing-id-error.ts +68 -0
  211. package/src/outlet-context.ts +1 -1
  212. package/src/outlet-provider.tsx +41 -0
  213. package/src/prerender/param-hash.ts +16 -14
  214. package/src/prerender/store.ts +121 -21
  215. package/src/prerender.ts +460 -26
  216. package/src/redirect-origin.ts +100 -0
  217. package/src/regex-escape.ts +8 -0
  218. package/src/render-error-thrower.tsx +20 -0
  219. package/src/response-utils.ts +62 -0
  220. package/src/reverse.ts +198 -128
  221. package/src/root-error-boundary.tsx +42 -48
  222. package/src/route-content-wrapper.tsx +22 -77
  223. package/src/route-definition/dsl-helpers.ts +1116 -0
  224. package/src/route-definition/helper-factories.ts +88 -0
  225. package/src/route-definition/helpers-types.ts +505 -0
  226. package/src/route-definition/index.ts +54 -0
  227. package/src/route-definition/redirect.ts +134 -0
  228. package/src/route-definition/resolve-handler-use.ts +160 -0
  229. package/src/route-definition/use-item-types.ts +29 -0
  230. package/src/route-definition.ts +1 -1481
  231. package/src/route-map-builder.ts +82 -144
  232. package/src/route-name.ts +53 -0
  233. package/src/route-types.ts +71 -45
  234. package/src/router/basename.ts +14 -0
  235. package/src/router/content-negotiation.ts +263 -0
  236. package/src/router/debug-manifest.ts +72 -0
  237. package/src/router/error-handling.ts +54 -27
  238. package/src/router/find-match.ts +245 -0
  239. package/src/router/handler-context.ts +377 -125
  240. package/src/router/instrument.ts +350 -0
  241. package/src/router/intercept-resolution.ts +59 -28
  242. package/src/router/lazy-includes.ts +254 -0
  243. package/src/router/loader-resolution.ts +421 -157
  244. package/src/router/logging.ts +106 -6
  245. package/src/router/manifest.ts +131 -57
  246. package/src/router/match-api.ts +167 -246
  247. package/src/router/match-context.ts +4 -24
  248. package/src/router/match-handlers.ts +440 -0
  249. package/src/router/match-middleware/background-revalidation.ts +117 -93
  250. package/src/router/match-middleware/cache-lookup.ts +297 -150
  251. package/src/router/match-middleware/cache-store.ts +123 -51
  252. package/src/router/match-middleware/intercept-resolution.ts +44 -43
  253. package/src/router/match-middleware/segment-resolution.ts +64 -22
  254. package/src/router/match-pipelines.ts +11 -87
  255. package/src/router/match-result.ts +121 -50
  256. package/src/router/metrics.ts +219 -28
  257. package/src/router/middleware-types.ts +93 -0
  258. package/src/router/middleware.ts +505 -441
  259. package/src/router/navigation-snapshot.ts +133 -0
  260. package/src/router/params-util.ts +23 -0
  261. package/src/router/parse-pattern.ts +115 -0
  262. package/src/router/pattern-matching.ts +311 -142
  263. package/src/router/prefetch-cache-ttl.ts +51 -0
  264. package/src/router/prefetch-limits.ts +37 -0
  265. package/src/router/prerender-match.ts +547 -0
  266. package/src/router/preview-match.ts +102 -0
  267. package/src/router/request-classification.ts +278 -0
  268. package/src/router/revalidation.ts +203 -62
  269. package/src/router/route-snapshot.ts +246 -0
  270. package/src/router/router-context.ts +45 -48
  271. package/src/router/router-interfaces.ts +554 -0
  272. package/src/router/router-options.ts +779 -0
  273. package/src/router/router-registry.ts +21 -0
  274. package/src/router/segment-resolution/fresh.ts +772 -0
  275. package/src/router/segment-resolution/helpers.ts +348 -0
  276. package/src/router/segment-resolution/loader-cache.ts +250 -0
  277. package/src/router/segment-resolution/loader-mask.ts +44 -0
  278. package/src/router/segment-resolution/revalidation.ts +1331 -0
  279. package/src/router/segment-resolution/static-store.ts +81 -0
  280. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  281. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  282. package/src/router/segment-resolution.ts +25 -1354
  283. package/src/router/segment-wrappers.ts +292 -0
  284. package/src/router/state-cookie-name.ts +33 -0
  285. package/src/router/substitute-pattern-params.ts +75 -0
  286. package/src/router/telemetry-otel.ts +261 -0
  287. package/src/router/telemetry.ts +377 -0
  288. package/src/router/timeout.ts +128 -0
  289. package/src/router/tracing.ts +206 -0
  290. package/src/router/trie-matching.ts +240 -61
  291. package/src/router/types.ts +23 -70
  292. package/src/router/url-params.ts +57 -0
  293. package/src/router.ts +781 -2378
  294. package/src/rsc/full-payload.ts +70 -0
  295. package/src/rsc/handler-context.ts +46 -0
  296. package/src/rsc/handler.ts +905 -1142
  297. package/src/rsc/helpers.ts +275 -19
  298. package/src/rsc/index.ts +2 -25
  299. package/src/rsc/json-route-result.ts +38 -0
  300. package/src/rsc/loader-fetch.ts +305 -0
  301. package/src/rsc/manifest-init.ts +77 -0
  302. package/src/rsc/nonce.ts +14 -0
  303. package/src/rsc/origin-guard.ts +155 -0
  304. package/src/rsc/progressive-enhancement.ts +502 -0
  305. package/src/rsc/redirect-guard.ts +99 -0
  306. package/src/rsc/response-cache-serve.ts +238 -0
  307. package/src/rsc/response-error.ts +104 -0
  308. package/src/rsc/response-route-handler.ts +257 -0
  309. package/src/rsc/rsc-rendering.ts +527 -0
  310. package/src/rsc/runtime-warnings.ts +55 -0
  311. package/src/rsc/server-action.ts +522 -0
  312. package/src/rsc/shell-capture.ts +897 -0
  313. package/src/rsc/shell-serve.ts +124 -0
  314. package/src/rsc/ssr-setup.ts +144 -0
  315. package/src/rsc/transition-gate.ts +89 -0
  316. package/src/rsc/types.ts +95 -12
  317. package/src/runtime-env.ts +18 -0
  318. package/src/search-params.ts +99 -82
  319. package/src/segment-content-promise.ts +67 -0
  320. package/src/segment-loader-promise.ts +149 -0
  321. package/src/segment-system.tsx +349 -134
  322. package/src/serialize.ts +243 -0
  323. package/src/server/context.ts +459 -85
  324. package/src/server/cookie-parse.ts +32 -0
  325. package/src/server/cookie-store.ts +310 -0
  326. package/src/server/fetchable-loader-store.ts +11 -6
  327. package/src/server/handle-store.ts +123 -42
  328. package/src/server/loader-registry.ts +51 -100
  329. package/src/server/request-context.ts +848 -157
  330. package/src/server.ts +15 -8
  331. package/src/ssr/index.tsx +443 -135
  332. package/src/ssr/ssr-root.tsx +228 -0
  333. package/src/static-handler.ts +45 -18
  334. package/src/testing/cache-status.ts +162 -0
  335. package/src/testing/collect-handle.ts +46 -0
  336. package/src/testing/dispatch.ts +701 -0
  337. package/src/testing/dom.entry.ts +22 -0
  338. package/src/testing/e2e/fixture.ts +188 -0
  339. package/src/testing/e2e/index.ts +128 -0
  340. package/src/testing/e2e/matchers.ts +35 -0
  341. package/src/testing/e2e/page-helpers.ts +272 -0
  342. package/src/testing/e2e/parity.ts +387 -0
  343. package/src/testing/e2e/server.ts +195 -0
  344. package/src/testing/flight-matchers.ts +97 -0
  345. package/src/testing/flight-normalize.ts +11 -0
  346. package/src/testing/flight-runtime.d.ts +57 -0
  347. package/src/testing/flight-tree.ts +682 -0
  348. package/src/testing/flight.entry.ts +52 -0
  349. package/src/testing/flight.ts +257 -0
  350. package/src/testing/generated-routes.ts +199 -0
  351. package/src/testing/index.ts +105 -0
  352. package/src/testing/internal/context.ts +371 -0
  353. package/src/testing/internal/flight-client-globals.ts +30 -0
  354. package/src/testing/internal/seed-vars.ts +54 -0
  355. package/src/testing/render-handler.ts +357 -0
  356. package/src/testing/render-route.tsx +584 -0
  357. package/src/testing/run-loader.ts +385 -0
  358. package/src/testing/run-middleware.ts +205 -0
  359. package/src/testing/run-transition-when.ts +164 -0
  360. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  361. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  362. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  363. package/src/testing/vitest-stubs/version.ts +5 -0
  364. package/src/testing/vitest.ts +305 -0
  365. package/src/theme/ThemeProvider.tsx +76 -98
  366. package/src/theme/ThemeScript.tsx +12 -14
  367. package/src/theme/constants.ts +57 -15
  368. package/src/theme/index.ts +3 -20
  369. package/src/theme/theme-context.ts +5 -35
  370. package/src/theme/theme-script.ts +43 -39
  371. package/src/theme/use-theme.ts +0 -3
  372. package/src/types/boundaries.ts +123 -0
  373. package/src/types/cache-types.ts +207 -0
  374. package/src/types/error-types.ts +132 -0
  375. package/src/types/global-namespace.ts +113 -0
  376. package/src/types/handler-context.ts +839 -0
  377. package/src/types/index.ts +81 -0
  378. package/src/types/loader-types.ts +212 -0
  379. package/src/types/request-scope.ts +112 -0
  380. package/src/types/route-config.ts +138 -0
  381. package/src/types/route-entry.ts +114 -0
  382. package/src/types/segments.ts +271 -0
  383. package/src/types.ts +1 -1795
  384. package/src/urls/include-helper.ts +162 -0
  385. package/src/urls/include-provider.ts +71 -0
  386. package/src/urls/index.ts +44 -0
  387. package/src/urls/path-helper-types.ts +413 -0
  388. package/src/urls/path-helper.ts +280 -0
  389. package/src/urls/pattern-types.ts +160 -0
  390. package/src/urls/response-types.ts +109 -0
  391. package/src/urls/type-extraction.ts +316 -0
  392. package/src/urls/urls-function.ts +80 -0
  393. package/src/urls.ts +1 -1341
  394. package/src/use-loader.tsx +406 -141
  395. package/src/vercel/index.ts +11 -0
  396. package/src/vercel/tracing.ts +88 -0
  397. package/src/vite/debug.ts +185 -0
  398. package/src/vite/discovery/bundle-postprocess.ts +182 -0
  399. package/src/vite/discovery/discover-routers.ts +389 -0
  400. package/src/vite/discovery/discovery-errors.ts +255 -0
  401. package/src/vite/discovery/gate-state.ts +171 -0
  402. package/src/vite/discovery/prerender-collection.ts +467 -0
  403. package/src/vite/discovery/route-types-writer.ts +214 -0
  404. package/src/vite/discovery/self-gen-tracking.ts +73 -0
  405. package/src/vite/discovery/state.ts +161 -0
  406. package/src/vite/discovery/virtual-module-codegen.ts +183 -0
  407. package/src/vite/index.ts +23 -2255
  408. package/src/vite/inject-client-debug.ts +36 -0
  409. package/src/vite/plugin-types.ts +303 -0
  410. package/src/vite/plugins/cjs-to-esm.ts +90 -0
  411. package/src/vite/plugins/client-ref-dedup.ts +120 -0
  412. package/src/vite/plugins/client-ref-hashing.ts +118 -0
  413. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  414. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  415. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  416. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +88 -110
  417. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +89 -79
  418. package/src/vite/plugins/expose-ids/export-analysis.ts +363 -0
  419. package/src/vite/plugins/expose-ids/handler-transform.ts +130 -0
  420. package/src/vite/plugins/expose-ids/loader-transform.ts +64 -0
  421. package/src/vite/plugins/expose-ids/router-transform.ts +199 -0
  422. package/src/vite/plugins/expose-ids/types.ts +45 -0
  423. package/src/vite/plugins/expose-internal-ids.ts +805 -0
  424. package/src/vite/plugins/performance-tracks.ts +89 -0
  425. package/src/vite/plugins/refresh-cmd.ts +127 -0
  426. package/src/vite/plugins/use-cache-transform.ts +313 -0
  427. package/src/vite/plugins/vercel-output.ts +384 -0
  428. package/src/vite/plugins/version-injector.ts +94 -0
  429. package/src/vite/plugins/version-plugin.ts +263 -0
  430. package/src/vite/plugins/virtual-entries.ts +234 -0
  431. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  432. package/src/vite/rango.ts +560 -0
  433. package/src/vite/router-discovery.ts +1638 -0
  434. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +200 -37
  435. package/src/vite/utils/banner.ts +36 -0
  436. package/src/vite/utils/bundle-analysis.ts +132 -0
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +15 -0
  441. package/src/vite/utils/package-resolution.ts +89 -0
  442. package/src/vite/utils/prerender-utils.ts +249 -0
  443. package/src/vite/utils/shared-utils.ts +269 -0
  444. package/CLAUDE.md +0 -43
  445. package/dist/vite/index.named-routes.gen.ts +0 -103
  446. package/src/browser/lru-cache.ts +0 -69
  447. package/src/browser/react/use-client-cache.ts +0 -56
  448. package/src/browser/request-controller.ts +0 -164
  449. package/src/browser/shallow.ts +0 -35
  450. package/src/cache/memory-store.ts +0 -253
  451. package/src/handles/index.ts +0 -6
  452. package/src/href-context.ts +0 -33
  453. package/src/network-error-thrower.tsx +0 -21
  454. package/src/router.gen.ts +0 -6
  455. package/src/static-handler.gen.ts +0 -5
  456. package/src/urls.gen.ts +0 -8
  457. package/src/vite/expose-internal-ids.ts +0 -1167
  458. package/src/vite/package-resolution.ts +0 -125
  459. package/src/vite/virtual-entries.ts +0 -114
  460. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
package/src/vite/index.ts CHANGED
@@ -1,2256 +1,24 @@
1
- import type { Plugin, PluginOption } from "vite";
2
- import { createServer as createViteServer } from "vite";
3
- import * as Vite from "vite";
4
- import { resolve, join, dirname, basename, relative } from "node:path";
5
- import { createHash } from "node:crypto";
6
- import { createRequire } from "node:module";
7
- import { mkdirSync, writeFileSync, readFileSync, existsSync, unlinkSync } from "node:fs";
8
- import {
9
- generateRouteTypesSource,
10
- writeCombinedRouteTypes,
11
- findRouterFiles,
12
- createScanFilter,
13
- buildCombinedRouteMapForRouterFile,
14
- type ScanFilter,
15
- } from "../build/generate-route-types.ts";
16
- import { exposeActionId } from "./expose-action-id.ts";
17
- import { exposeInternalIds, exposeRouterId } from "./expose-internal-ids.ts";
18
- import {
19
- VIRTUAL_ENTRY_BROWSER,
20
- VIRTUAL_ENTRY_SSR,
21
- getVirtualEntryRSC,
22
- getVirtualVersionContent,
23
- VIRTUAL_IDS,
24
- } from "./virtual-entries.ts";
25
- import {
26
- getExcludeDeps,
27
- getPackageAliases,
28
- getPublishedPackageName,
29
- } from "./package-resolution.ts";
30
-
31
- // Re-export plugins
32
- export { exposeActionId } from "./expose-action-id.ts";
33
- export { exposeInternalIds, exposeRouterId } from "./expose-internal-ids.ts";
34
- export type { ExposeInternalIdsApi } from "./expose-internal-ids.ts";
35
-
36
- // Virtual module type declarations in ./version.d.ts
37
-
38
- /**
39
- * esbuild plugin to provide rsc-router:version virtual module during optimization.
40
- * This is needed because esbuild runs during Vite's dependency optimization phase,
41
- * before Vite's plugin system can handle virtual modules.
42
- */
43
- const versionEsbuildPlugin = {
44
- name: "@rangojs/router-version",
45
- setup(build: any) {
46
- build.onResolve({ filter: /^rsc-router:version$/ }, (args: any) => ({
47
- path: args.path,
48
- namespace: "@rangojs/router-virtual",
49
- }));
50
- build.onLoad({ filter: /.*/, namespace: "@rangojs/router-virtual" }, () => ({
51
- contents: `export const VERSION = "dev";`,
52
- loader: "js",
53
- }));
54
- },
55
- };
56
-
57
- /**
58
- * Shared esbuild options for dependency optimization.
59
- * Includes the version stub plugin for all environments.
60
- */
61
- const sharedEsbuildOptions = {
62
- plugins: [versionEsbuildPlugin],
63
- };
64
-
65
- /**
66
- * RSC plugin entry points configuration.
67
- * All entries use virtual modules by default. Specify a path to use a custom entry file.
68
- */
69
- export interface RscEntries {
70
- /**
71
- * Path to a custom browser/client entry file.
72
- * If not specified, a default virtual entry is used.
73
- */
74
- client?: string;
75
-
76
- /**
77
- * Path to a custom SSR entry file.
78
- * If not specified, a default virtual entry is used.
79
- */
80
- ssr?: string;
81
-
82
- /**
83
- * Path to a custom RSC entry file.
84
- * If not specified, a default virtual entry is used that imports the router from the `entry` option.
85
- */
86
- rsc?: string;
87
- }
88
-
89
- /**
90
- * Options for @vitejs/plugin-rsc integration
91
- */
92
- export interface RscPluginOptions {
93
- /**
94
- * Entry points for client, ssr, and rsc environments.
95
- * All entries use virtual modules by default.
96
- * Specify paths only when you need custom entry files.
97
- */
98
- entries?: RscEntries;
99
- }
100
-
101
- /**
102
- * Base options shared by all presets
103
- */
104
- interface RangoBaseOptions {
105
- /**
106
- * Show startup banner. Set to false to disable.
107
- * @default true
108
- */
109
- banner?: boolean;
110
-
111
- /**
112
- * Generate named-routes.gen.ts by parsing url modules at startup.
113
- * Provides type-safe Handler<"name"> and href() without executing router code.
114
- * Set to `false` to disable (run `npx rango extract-names` manually instead).
115
- * @default true
116
- */
117
- staticRouteTypesGeneration?: boolean;
118
-
119
- /**
120
- * Glob patterns for files to include in route type scanning.
121
- * Only files matching at least one pattern will be scanned.
122
- * Patterns are relative to the project root.
123
- * When unset, all .ts/.tsx files are scanned.
124
- */
125
- include?: string[];
126
-
127
- /**
128
- * Glob patterns for files to exclude from route type scanning.
129
- * Takes precedence over `include`. Patterns are relative to the project root.
130
- * Defaults to common test/build directories.
131
- */
132
- exclude?: string[];
133
- }
134
-
135
- /**
136
- * Options for Node.js deployment (default)
137
- */
138
- export interface RangoNodeOptions extends RangoBaseOptions {
139
- /**
140
- * Deployment preset. Defaults to 'node' when not specified.
141
- */
142
- preset?: "node";
143
-
144
- /**
145
- * Path to your router configuration file that exports the route tree.
146
- * This file must export a `router` object created with `createRouter()`.
147
- *
148
- * When omitted, auto-discovers the router by scanning for files containing
149
- * `createRouter`. If exactly one is found, it is used automatically.
150
- * If multiple are found, an error is thrown with the list of candidates.
151
- *
152
- * @example
153
- * ```ts
154
- * rango({ router: './src/router.tsx' })
155
- * // or simply:
156
- * rango()
157
- * ```
158
- */
159
- router?: string;
160
-
161
- /**
162
- * RSC plugin configuration. By default, rsc-router includes @vitejs/plugin-rsc
163
- * with sensible defaults.
164
- *
165
- * Entry files (browser, ssr, rsc) are optional - if they don't exist,
166
- * virtual defaults are used.
167
- *
168
- * - Omit or pass `true`/`{}` to use defaults (recommended)
169
- * - Pass `{ entries: {...} }` to customize entry paths
170
- * - Pass `false` to disable (for manual @vitejs/plugin-rsc configuration)
171
- *
172
- * @default true
173
- */
174
- rsc?: boolean | RscPluginOptions;
175
- }
176
-
177
1
  /**
178
- * Options for Cloudflare Workers deployment
179
- */
180
- export interface RangoCloudflareOptions extends RangoBaseOptions {
181
- /**
182
- * Deployment preset for Cloudflare Workers.
183
- * When using cloudflare preset:
184
- * - @vitejs/plugin-rsc is NOT added (cloudflare plugin adds it)
185
- * - Your worker entry (e.g., worker.rsc.tsx) imports the router directly
186
- * - Browser and SSR use virtual entries
187
- * - Build-time manifest generation is auto-detected from wrangler.json main entry
188
- */
189
- preset: "cloudflare";
190
- }
191
-
192
- /**
193
- * Options for rango() Vite plugin
194
- */
195
- export type RangoOptions = RangoNodeOptions | RangoCloudflareOptions;
196
-
197
- /**
198
- * Create a virtual modules plugin for default entry files.
199
- * Provides virtual module content when entries use VIRTUAL_IDS (no custom entry configured).
200
- */
201
- function createVirtualEntriesPlugin(
202
- entries: { client: string; ssr: string; rsc?: string },
203
- routerPath?: string
204
- ): Plugin {
205
-
206
- // Build virtual modules map based on which entries use virtual IDs
207
- const virtualModules: Record<string, string> = {};
208
-
209
- if (entries.client === VIRTUAL_IDS.browser) {
210
- virtualModules[VIRTUAL_IDS.browser] = VIRTUAL_ENTRY_BROWSER;
211
- }
212
- if (entries.ssr === VIRTUAL_IDS.ssr) {
213
- virtualModules[VIRTUAL_IDS.ssr] = VIRTUAL_ENTRY_SSR;
214
- }
215
- if (entries.rsc === VIRTUAL_IDS.rsc && routerPath) {
216
- // Convert relative path to absolute for virtual module imports
217
- const absoluteRouterPath = routerPath.startsWith(".")
218
- ? "/" + routerPath.slice(2) // ./src/router.tsx -> /src/router.tsx
219
- : routerPath;
220
- virtualModules[VIRTUAL_IDS.rsc] = getVirtualEntryRSC(absoluteRouterPath);
221
- }
222
-
223
- return {
224
- name: "@rangojs/router:virtual-entries",
225
- enforce: "pre",
226
-
227
- resolveId(id) {
228
- if (id in virtualModules) {
229
- return "\0" + id;
230
- }
231
- // Handle if the id already has the null prefix (RSC plugin wrapper imports)
232
- if (id.startsWith("\0") && id.slice(1) in virtualModules) {
233
- return id;
234
- }
235
- return null;
236
- },
237
-
238
- load(id) {
239
- if (id.startsWith("\0virtual:rsc-router/")) {
240
- const virtualId = id.slice(1);
241
- if (virtualId in virtualModules) {
242
- return virtualModules[virtualId];
243
- }
244
- }
245
- return null;
246
- },
247
- };
248
- }
249
-
250
- /**
251
- * Rollup onwarn handler that suppresses known harmless warnings:
252
- * - "use client" directives: handled by the RSC plugin, not relevant to Rollup
253
- * - sourcemap errors: caused by "use client" directive at line 1:0 confusing sourcemap resolution
254
- * - sourcemap incomplete: plugins that transform without generating sourcemaps (router + RSC plugin)
255
- * - dynamic/static mixed imports: expected for router internals (e.g. request-context, cache-scope)
256
- */
257
- function onwarn(warning: Vite.Rollup.RollupLog, defaultHandler: (warning: Vite.Rollup.RollupLog) => void): void {
258
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" || warning.code === "SOURCEMAP_ERROR") {
259
- return;
260
- }
261
- // @vitejs/plugin-rsc@0.5.14: rsc:virtual:vite-rsc/assets-manifest renderChunk
262
- // returns { code } without map, causing Rollup to warn about incorrect sourcemaps.
263
- // This is harmless (simple string replacement). Remove this suppression if a
264
- // future version of @vitejs/plugin-rsc fixes the missing sourcemap.
265
- if (warning.message?.includes("Sourcemap is likely to be incorrect")) {
266
- return;
267
- }
268
- if (
269
- warning.plugin === "vite:reporter" &&
270
- warning.message?.includes("dynamic import will not move module into another chunk")
271
- ) {
272
- return;
273
- }
274
- defaultHandler(warning);
275
- }
276
-
277
- /**
278
- * Manual chunks configuration for client build.
279
- * Splits React and router packages into separate chunks for better caching.
280
- */
281
- function getManualChunks(id: string): string | undefined {
282
- const normalized = Vite.normalizePath(id);
283
-
284
- if (
285
- normalized.includes("node_modules/react/") ||
286
- normalized.includes("node_modules/react-dom/") ||
287
- normalized.includes("node_modules/react-server-dom-webpack/") ||
288
- normalized.includes("node_modules/@vitejs/plugin-rsc/")
289
- ) {
290
- return "react";
291
- }
292
- // Use dynamic package name from package.json
293
- // Check both npm install path and workspace symlink resolved path
294
- const packageName = getPublishedPackageName();
295
- if (
296
- normalized.includes(`node_modules/${packageName}/`) ||
297
- normalized.includes("packages/rsc-router/") ||
298
- normalized.includes("packages/rangojs-router/")
299
- ) {
300
- return "router";
301
- }
302
- return undefined;
303
- }
304
-
305
- /**
306
- * Plugin providing rsc-router:version virtual module.
307
- * Exports VERSION that changes when RSC modules change (dev) or at build time (production).
308
- *
309
- * The version is used for:
310
- * 1. Cache invalidation - CFCacheStore uses VERSION to invalidate stale cache
311
- * 2. Version mismatch detection - client sends version, server reloads on mismatch
312
- *
313
- * In dev mode, the version updates when:
314
- * - Server starts (initial version)
315
- * - RSC modules change via HMR (triggers version module invalidation)
316
- *
317
- * Client-only HMR changes don't update the version since they don't affect
318
- * server-rendered content or cached RSC payloads.
319
- * @internal
320
- */
321
- function createVersionPlugin(): Plugin {
322
- // Generate version at plugin creation time (build/server start)
323
- const buildVersion = Date.now().toString(16);
324
- let currentVersion = buildVersion;
325
- let isDev = false;
326
- let server: any = null;
327
-
328
- return {
329
- name: "@rangojs/router:version",
330
- enforce: "pre",
331
-
332
- configResolved(config) {
333
- isDev = config.command === "serve";
334
- },
335
-
336
- configureServer(devServer) {
337
- server = devServer;
338
- },
339
-
340
- resolveId(id) {
341
- if (id === VIRTUAL_IDS.version) {
342
- return "\0" + id;
343
- }
344
- return null;
345
- },
346
-
347
- load(id) {
348
- if (id === "\0" + VIRTUAL_IDS.version) {
349
- return getVirtualVersionContent(currentVersion);
350
- }
351
- return null;
352
- },
353
-
354
- // Track RSC module changes and update version
355
- hotUpdate(ctx) {
356
- if (!isDev) return;
357
-
358
- // Check if this is an RSC environment update (not client/ssr)
359
- // RSC modules affect server-rendered content and cached payloads
360
- // In Vite 6, environment is accessed via `this.environment`
361
- const isRscModule = this.environment?.name === "rsc";
362
-
363
- if (isRscModule && ctx.modules.length > 0) {
364
- // Update version when RSC modules change
365
- currentVersion = Date.now().toString(16);
366
- console.log(
367
- `[rsc-router] RSC module changed, version updated: ${currentVersion}`
368
- );
369
-
370
- // Invalidate the version module so it gets reloaded with new version
371
- if (server) {
372
- const rscEnv = server.environments?.rsc;
373
- if (rscEnv?.moduleGraph) {
374
- const versionMod = rscEnv.moduleGraph.getModuleById(
375
- "\0" + VIRTUAL_IDS.version
376
- );
377
- if (versionMod) {
378
- rscEnv.moduleGraph.invalidateModule(versionMod);
379
- }
380
- }
381
- }
382
- }
383
- },
384
- };
385
- }
386
-
387
- /**
388
- * Flatten prefix tree leaf nodes into precomputed route entries.
389
- * Leaf nodes have no children (no nested includes), so their routes can be
390
- * used directly by evaluateLazyEntry() without running the handler.
391
- * Non-leaf nodes are skipped because they have nested lazy includes that
392
- * require the handler to run for discovery.
393
- */
394
- function flattenLeafEntries(
395
- prefixTree: Record<string, any>,
396
- routeManifest: Record<string, string>,
397
- result: Array<{ staticPrefix: string; routes: Record<string, string> }>,
398
- ): void {
399
- function visit(node: any): void {
400
- const children = node.children || {};
401
- if (Object.keys(children).length === 0 && node.routes && node.routes.length > 0) {
402
- // Leaf node: collect its routes from the manifest
403
- const routes: Record<string, string> = {};
404
- for (const name of node.routes) {
405
- if (name in routeManifest) {
406
- routes[name] = routeManifest[name];
407
- }
408
- }
409
- result.push({ staticPrefix: node.staticPrefix, routes });
410
- } else {
411
- // Non-leaf: recurse into children
412
- for (const child of Object.values(children)) {
413
- visit(child);
414
- }
415
- }
416
- }
417
- for (const node of Object.values(prefixTree)) {
418
- visit(node);
419
- }
420
- }
421
-
422
- /**
423
- * Walk prefix tree to map each route name to its scope's staticPrefix.
424
- */
425
- function buildRouteToStaticPrefix(
426
- prefixTree: Record<string, any>,
427
- result: Record<string, string>,
428
- ): void {
429
- function visit(node: any): void {
430
- const sp = node.staticPrefix || "";
431
- for (const name of (node.routes || [])) {
432
- result[name] = sp;
433
- }
434
- for (const child of Object.values(node.children || {})) {
435
- visit(child);
436
- }
437
- }
438
- for (const node of Object.values(prefixTree)) {
439
- visit(node);
440
- }
441
- }
442
-
443
- /**
444
- * Encode route param values for path interpolation while preserving path
445
- * separators for wildcard params (splat-style values can include `/`).
446
- */
447
- function encodePathParam(value: unknown): string {
448
- return String(value)
449
- .split("/")
450
- .map((segment) => encodeURIComponent(segment))
451
- .join("/");
452
- }
453
-
454
- /**
455
- * Plugin that discovers router instances at dev/build time via the RSC environment.
456
- *
457
- * Uses `server.environments.rsc.runner.import()` to load the user's router file
458
- * with full TS/TSX compilation. This triggers `createRouter()` which populates
459
- * the `RouterRegistry`. The plugin then generates manifests for each router.
460
- *
461
- * In dev mode, this runs in `configureServer` (post-middleware setup).
462
- * In build mode, this will run in `buildStart` (future).
463
- *
464
- * @internal
465
- */
466
- function createRouterDiscoveryPlugin(
467
- entryPath: string,
468
- opts?: { enableBuildPrerender?: boolean; staticRouteTypesGeneration?: boolean; include?: string[]; exclude?: string[] },
469
- ): Plugin {
470
- let projectRoot = "";
471
- let isBuildMode = false;
472
- let userResolveAlias: any = undefined;
473
-
474
- // Scan filter compiled from include/exclude patterns (created in configResolved)
475
- let scanFilter: ScanFilter | undefined;
476
-
477
- // Cached router file paths (files containing createRouter) from initial scan.
478
- // Reused by the file watcher to avoid re-scanning the entire directory tree.
479
- let cachedRouterFiles: string[] | undefined;
480
-
481
- // Merged route manifest from all discovered routers.
482
- // Populated during discovery (dev: configureServer, build: buildStart).
483
- // Read by the virtual module's load hook to emit setCachedManifest() call.
484
- let mergedRouteManifest: Record<string, string> | null = null;
485
-
486
- // Per-router route manifests for generating typed route files.
487
- let perRouterManifests: Array<{
488
- id: string;
489
- routeManifest: Record<string, string>;
490
- routeSearchSchemas?: Record<string, Record<string, string>>;
491
- sourceFile?: string;
492
- }> = [];
493
-
494
-
495
- // Collected prerender data from in-process collection during discoverRouters().
496
- // Consumed by closeBundle to inject into the RSC entry bundle.
497
- let prerenderCollectedData: Record<string, any> | null = null;
498
-
499
- // Handler chunk metadata recorded during generateBundle for post-build eviction.
500
- let handlerChunkInfo: {
501
- fileName: string;
502
- exports: Array<{ name: string; handlerId: string; passthrough: boolean }>;
503
- } | null = null;
504
-
505
- // RSC entry chunk filename recorded during generateBundle for closeBundle injection.
506
- let rscEntryFileName: string | null = null;
507
-
508
- // Resolved prerender handler modules from the expose-internal-ids plugin.
509
- let resolvedPrerenderModules: Map<string, string[]> | undefined;
510
-
511
- // Resolved static handler modules from the expose-internal-ids plugin.
512
- let resolvedStaticModules: Map<string, string[]> | undefined;
513
-
514
- // Promise that resolves when dev-mode discovery completes.
515
- // The virtual module's load hook awaits this to ensure data is available.
516
- let discoveryDone: Promise<void> | null = null;
517
-
518
- // Pre-computed route entries from prefix tree leaf nodes.
519
- // Leaf nodes have no nested includes, so their routes can be used directly
520
- // by evaluateLazyEntry() without running the handler.
521
- let mergedPrecomputedEntries: Array<{
522
- staticPrefix: string;
523
- routes: Record<string, string>;
524
- }> | null = null;
525
-
526
- // Route trie for O(path_length) matching at runtime.
527
- let mergedRouteTrie: any = null;
528
-
529
- // Per-router isolated data for multi-router manifest splitting.
530
- // Each router gets its own manifest, trie, and precomputed entries so that
531
- // virtual:rsc-router/routes-manifest/<routerId> modules can be emitted.
532
- let perRouterTrieMap: Map<string, any> = new Map();
533
- let perRouterPrecomputedMap: Map<string, Array<{ staticPrefix: string; routes: Record<string, string> }>> = new Map();
534
- let perRouterManifestDataMap: Map<string, Record<string, string>> = new Map();
535
-
536
- // Dev-mode state for on-demand prerender endpoint.
537
- let devServerOrigin: string | null = null;
538
- let devServer: any = null;
539
-
540
- // Shared discovery logic: import entry via RSC runner, generate manifests,
541
- // write static files, and populate mergedRouteManifest.
542
- async function discoverRouters(rscEnv: any) {
543
- // Import the entry file via RSC environment.
544
- // For node preset: this is the router file (createRouter() registers in RouterRegistry).
545
- // For cloudflare preset: this is the worker entry (which imports the router).
546
- await rscEnv.runner.import(entryPath);
547
-
548
- // Import the router package to access the registry
549
- const serverMod = await rscEnv.runner.import("@rangojs/router/server");
550
- let registry: Map<string, any> = serverMod.RouterRegistry;
551
-
552
- if (!registry || registry.size === 0) {
553
- // No RSC routers found directly. Check for host routers with lazy handlers
554
- // that need to be resolved to trigger sub-app createRouter() calls.
555
- try {
556
- const hostMod = await rscEnv.runner.import("@rangojs/router/host");
557
- const hostRegistry: Map<string, any> | undefined = hostMod.HostRouterRegistry;
558
-
559
- if (hostRegistry && hostRegistry.size > 0) {
560
- console.log(
561
- `[rsc-router] Found ${hostRegistry.size} host router(s), resolving lazy handlers...`
562
- );
563
-
564
- for (const [, entry] of hostRegistry) {
565
- for (const route of entry.routes) {
566
- if (typeof route.handler === 'function') {
567
- try {
568
- await route.handler();
569
- } catch {
570
- // Lazy handler may fail in temp server context, that's OK
571
- }
572
- }
573
- }
574
- if (entry.fallback && typeof entry.fallback.handler === 'function') {
575
- try {
576
- await entry.fallback.handler();
577
- } catch {
578
- // Fallback handler may fail in temp server context
579
- }
580
- }
581
- }
582
-
583
- // Re-read RouterRegistry - sub-app createRouter() calls should have populated it
584
- const freshServerMod = await rscEnv.runner.import("@rangojs/router/server");
585
- const freshRegistry: Map<string, any> = freshServerMod.RouterRegistry;
586
-
587
- if (freshRegistry && freshRegistry.size > 0) {
588
- // Update references so the manifest generation below uses the fresh data
589
- Object.assign(serverMod, freshServerMod);
590
- registry = freshRegistry;
591
- }
592
- }
593
- } catch {
594
- // @rangojs/router/host not available or import failed, skip
595
- }
596
-
597
- // If still no routers after host router resolution, fail
598
- if (!registry || registry.size === 0) {
599
- throw new Error(
600
- `[rsc-router] No routers found in registry after importing ${entryPath}`
601
- );
602
- }
603
- }
604
-
605
- // Import build utilities for manifest generation
606
- const buildMod = await rscEnv.runner.import("@rangojs/router/build");
607
- const generateManifest = buildMod.generateManifest;
608
-
609
- mergedRouteManifest = {};
610
- mergedPrecomputedEntries = [];
611
- perRouterManifests = [];
612
- perRouterManifestDataMap = new Map();
613
- perRouterPrecomputedMap = new Map();
614
- perRouterTrieMap = new Map();
615
- let mergedRouteAncestry: Record<string, string[]> = {};
616
- let mergedRouteTrailingSlash: Record<string, string> = {};
617
-
618
- let routerMountIndex = 0;
619
- // Collect all manifests for trie building (avoid re-running generateManifest)
620
- const allManifests: Array<{ id: string; manifest: any }> = [];
621
-
622
- for (const [id, router] of registry) {
623
- if (!router.urlpatterns || !generateManifest) {
624
- continue;
625
- }
626
-
627
- const manifest = generateManifest(router.urlpatterns, routerMountIndex);
628
- routerMountIndex++;
629
- allManifests.push({ id, manifest });
630
- const routeCount = Object.keys(manifest.routeManifest).length;
631
- const staticRoutes = Object.values(manifest.routeManifest).filter(
632
- (p: any) => !p.includes(":") && !p.includes("*")
633
- ).length;
634
- const dynamicRoutes = routeCount - staticRoutes;
635
-
636
- // Merge into the combined manifest
637
- Object.assign(mergedRouteManifest, manifest.routeManifest);
638
- perRouterManifests.push({
639
- id,
640
- routeManifest: manifest.routeManifest,
641
- routeSearchSchemas: manifest.routeSearchSchemas,
642
- sourceFile: router.__sourceFile,
643
- });
644
-
645
- // Merge ancestry (internal field, used only for trie building)
646
- if (manifest._routeAncestry) {
647
- Object.assign(mergedRouteAncestry, manifest._routeAncestry);
648
- }
649
- // Merge trailing slash config
650
- if (manifest.routeTrailingSlash) {
651
- Object.assign(mergedRouteTrailingSlash, manifest.routeTrailingSlash);
652
- }
653
-
654
- // Flatten prefix tree leaf nodes into precomputed entries.
655
- // Leaf nodes (no children) can have their routes used directly by
656
- // evaluateLazyEntry() without running the handler at runtime.
657
- flattenLeafEntries(manifest.prefixTree, manifest.routeManifest, mergedPrecomputedEntries);
658
-
659
- // Store per-router manifest and precomputed entries for isolated virtual modules.
660
- perRouterManifestDataMap.set(id, manifest.routeManifest);
661
- const routerPrecomputed: Array<{ staticPrefix: string; routes: Record<string, string> }> = [];
662
- flattenLeafEntries(manifest.prefixTree, manifest.routeManifest, routerPrecomputed);
663
- perRouterPrecomputedMap.set(id, routerPrecomputed);
664
-
665
- console.log(
666
- `[rsc-router] Router "${id}" -> ${routeCount} routes ` +
667
- `(${staticRoutes} static, ${dynamicRoutes} dynamic)`
668
- );
669
- }
670
-
671
- // Warn if multiple routers use auto-generated IDs (router_0, router_1, ...).
672
- // Auto-IDs are assigned by counter and depend on module evaluation order,
673
- // which can differ between build time and runtime (especially with dynamic
674
- // imports in host routers). This causes per-router data to be loaded into
675
- // the wrong router at runtime.
676
- if (registry.size > 1) {
677
- const autoIds = [...registry.keys()].filter((id) => /^router_\d+$/.test(id));
678
- if (autoIds.length > 1) {
679
- console.warn(
680
- `[rsc-router] WARNING: ${autoIds.length} routers use auto-generated IDs (${autoIds.join(", ")}). ` +
681
- `In multi-router setups, each createRouter() must have an explicit \`id\` option ` +
682
- `to ensure per-router manifest data is matched correctly at runtime. ` +
683
- `Example: createRouter({ id: "site", ... })`
684
- );
685
- }
686
- }
687
-
688
- // Build route trie from merged manifest + ancestry
689
- if (mergedRouteManifest && Object.keys(mergedRouteManifest).length > 0) {
690
- const buildRouteTrie = buildMod.buildRouteTrie;
691
- if (buildRouteTrie && mergedRouteAncestry) {
692
- // Build routeToStaticPrefix from saved manifests
693
- const routeToStaticPrefix: Record<string, string> = {};
694
- for (const { manifest } of allManifests) {
695
- // Root-level routes have empty static prefix
696
- for (const name of Object.keys(manifest.routeManifest)) {
697
- if (!(name in routeToStaticPrefix)) {
698
- routeToStaticPrefix[name] = "";
699
- }
700
- }
701
- buildRouteToStaticPrefix(manifest.prefixTree, routeToStaticPrefix);
702
- }
703
-
704
- // Collect prerender route names and response type routes from all manifests
705
- const prerenderRouteNames = new Set<string>();
706
- const passthroughRouteNames = new Set<string>();
707
- const mergedResponseTypeRoutes: Record<string, string> = {};
708
- for (const { manifest } of allManifests) {
709
- if (manifest.prerenderRoutes) {
710
- for (const name of manifest.prerenderRoutes) {
711
- prerenderRouteNames.add(name);
712
- }
713
- }
714
- if (manifest.passthroughRoutes) {
715
- for (const name of manifest.passthroughRoutes) {
716
- passthroughRouteNames.add(name);
717
- }
718
- }
719
- if (manifest.responseTypeRoutes) {
720
- Object.assign(mergedResponseTypeRoutes, manifest.responseTypeRoutes);
721
- }
722
- }
723
-
724
- mergedRouteTrie = buildRouteTrie(
725
- mergedRouteManifest,
726
- mergedRouteAncestry,
727
- routeToStaticPrefix,
728
- Object.keys(mergedRouteTrailingSlash).length > 0 ? mergedRouteTrailingSlash : undefined,
729
- prerenderRouteNames.size > 0 ? prerenderRouteNames : undefined,
730
- passthroughRouteNames.size > 0 ? passthroughRouteNames : undefined,
731
- Object.keys(mergedResponseTypeRoutes).length > 0 ? mergedResponseTypeRoutes : undefined,
732
- );
733
-
734
- // Build per-router tries for multi-router isolation.
735
- for (const { id, manifest } of allManifests) {
736
- if (!manifest._routeAncestry || Object.keys(manifest._routeAncestry).length === 0) continue;
737
- const perRouterStaticPrefix: Record<string, string> = {};
738
- for (const name of Object.keys(manifest.routeManifest)) {
739
- perRouterStaticPrefix[name] = "";
740
- }
741
- buildRouteToStaticPrefix(manifest.prefixTree, perRouterStaticPrefix);
742
-
743
- const perRouterPrerenderNames = manifest.prerenderRoutes
744
- ? new Set<string>(manifest.prerenderRoutes)
745
- : undefined;
746
- const perRouterPassthroughNames = manifest.passthroughRoutes
747
- ? new Set<string>(manifest.passthroughRoutes)
748
- : undefined;
749
-
750
- const perRouterTrie = buildRouteTrie(
751
- manifest.routeManifest,
752
- manifest._routeAncestry,
753
- perRouterStaticPrefix,
754
- manifest.routeTrailingSlash && Object.keys(manifest.routeTrailingSlash).length > 0
755
- ? manifest.routeTrailingSlash : undefined,
756
- perRouterPrerenderNames && perRouterPrerenderNames.size > 0 ? perRouterPrerenderNames : undefined,
757
- perRouterPassthroughNames && perRouterPassthroughNames.size > 0 ? perRouterPassthroughNames : undefined,
758
- manifest.responseTypeRoutes && Object.keys(manifest.responseTypeRoutes).length > 0
759
- ? manifest.responseTypeRoutes : undefined,
760
- );
761
- perRouterTrieMap.set(id, perRouterTrie);
762
- }
763
- }
764
- }
765
-
766
- // Expand prerender routes into concrete URLs for build-time rendering.
767
- // Static routes use pattern as-is; dynamic routes call getParams() to enumerate.
768
- if (opts?.enableBuildPrerender && isBuildMode) {
769
- const urls: string[] = [];
770
- for (const { manifest } of allManifests) {
771
- if (!manifest.prerenderRoutes) continue;
772
- const defs = manifest._prerenderDefs || {};
773
- for (const routeName of manifest.prerenderRoutes) {
774
- const pattern = manifest.routeManifest[routeName];
775
- if (!pattern) continue;
776
- const hasDynamic = pattern.includes(":") || pattern.includes("*");
777
- if (!hasDynamic) {
778
- // Static route: use pattern directly (strip trailing slash for URL)
779
- urls.push(pattern.replace(/\/$/, "") || "/");
780
- } else {
781
- // Dynamic route: call getParams() to enumerate param combinations
782
- const def = defs[routeName];
783
- if (def?.getParams) {
784
- try {
785
- const paramsList = await def.getParams();
786
- for (const params of paramsList) {
787
- let url = pattern;
788
- for (const [key, value] of Object.entries(params as Record<string, string>)) {
789
- const encoded = encodePathParam(value);
790
- url = url.replace(`:${key}`, encoded);
791
- url = url.replace(`*${key}`, encoded);
792
- }
793
- // Anonymous wildcard fallback: use conventional keys if provided
794
- if (url.includes("*")) {
795
- const wildcardValue =
796
- (params as Record<string, string>)["*"]
797
- ?? (params as Record<string, string>).splat;
798
- if (wildcardValue !== undefined) {
799
- url = url.replace(/\*[^/]*$/, encodePathParam(wildcardValue));
800
- }
801
- }
802
- urls.push(url.replace(/\/$/, "") || "/");
803
- }
804
- } catch (err: any) {
805
- console.warn(
806
- `[rsc-router] Failed to get params for prerender route "${routeName}": ${err.message}`
807
- );
808
- }
809
- } else {
810
- console.warn(
811
- `[rsc-router] Dynamic prerender route "${routeName}" has no getParams(), skipping`
812
- );
813
- }
814
- }
815
- }
816
- }
817
- if (urls.length > 0) {
818
- console.log(
819
- `[rsc-router] Pre-render URLs: ${urls.join(", ")}`
820
- );
821
-
822
- const { hashParams } = await rscEnv.runner.import("@rangojs/router/build");
823
-
824
- const collectedData: Record<string, any> = {};
825
- let rendered = 0;
826
-
827
- for (const urlPath of urls) {
828
- // Try all routers since the URL->router mapping isn't direct
829
- for (const [, routerInstance] of registry) {
830
- if (!routerInstance.matchForPrerender) continue;
831
- try {
832
- const result = await routerInstance.matchForPrerender(urlPath, {});
833
- if (!result) continue;
834
- const paramHash = hashParams(result.params || {});
835
- collectedData[`${result.routeName}/${paramHash}`] = {
836
- segments: result.segments,
837
- handles: result.handles,
838
- };
839
- rendered++;
840
- break;
841
- } catch (err: any) {
842
- console.warn(`[rsc-router] Pre-render failed for ${urlPath}: ${err.message}`);
843
- }
844
- }
845
- }
846
-
847
- if (rendered > 0) {
848
- prerenderCollectedData = collectedData;
849
- console.log(`[rsc-router] Pre-rendered ${rendered}/${urls.length} route(s)`);
850
- }
851
- }
852
- }
853
-
854
- return serverMod;
855
- }
856
-
857
- // Write per-router named-routes type files next to each router's source file.
858
- // Each router gets its own {basename}.named-routes.gen.ts with only its routes.
859
- // Only writes when content has changed to avoid triggering HMR loops.
860
- function writeRouteTypesFiles() {
861
- if (perRouterManifests.length === 0) return;
862
-
863
- // Delete old combined named-routes.gen.ts if it exists
864
- try {
865
- const entryDir = dirname(resolve(projectRoot, entryPath));
866
- const oldCombinedPath = join(entryDir, "named-routes.gen.ts");
867
- if (existsSync(oldCombinedPath)) {
868
- unlinkSync(oldCombinedPath);
869
- console.log(`[rsc-router] Removed stale combined route types: ${oldCombinedPath}`);
870
- }
871
- } catch {}
872
-
873
- for (const { id, routeManifest, routeSearchSchemas, sourceFile } of perRouterManifests) {
874
- if (!sourceFile) continue;
875
-
876
- // Validate sourceFile points to a real project file, not node_modules or
877
- // a Vite internal path. A bad sourceFile leads to route types written to
878
- // the wrong location, causing non-deterministic type resolution.
879
- if (sourceFile.includes("node_modules")) {
880
- throw new Error(
881
- `[rsc-router] Router "${id}" has sourceFile inside node_modules: ${sourceFile}\n` +
882
- `This means createRouter() stack trace parsing matched a Vite internal frame.\n` +
883
- `Set an explicit \`id\` on createRouter() or check the call site.`,
884
- );
885
- }
886
-
887
- const routerDir = dirname(sourceFile);
888
- const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
889
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
890
- let effectiveSearchSchemas = routeSearchSchemas;
891
-
892
- // Runtime manifest may omit search schema metadata in some module-runner
893
- // flows. Fall back to static source parsing from the router file.
894
- if (
895
- (!effectiveSearchSchemas || Object.keys(effectiveSearchSchemas).length === 0) &&
896
- sourceFile
897
- ) {
898
- const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
899
- if (Object.keys(staticParsed.searchSchemas).length > 0) {
900
- const filtered: Record<string, Record<string, string>> = {};
901
- for (const name of Object.keys(routeManifest)) {
902
- const schema = staticParsed.searchSchemas[name];
903
- if (schema) filtered[name] = schema;
904
- }
905
- if (Object.keys(filtered).length > 0) {
906
- effectiveSearchSchemas = filtered;
907
- }
908
- }
909
- }
910
-
911
- const source = generateRouteTypesSource(
912
- routeManifest,
913
- effectiveSearchSchemas && Object.keys(effectiveSearchSchemas).length > 0
914
- ? effectiveSearchSchemas
915
- : undefined,
916
- );
917
- const existing = existsSync(outPath) ? readFileSync(outPath, "utf-8") : null;
918
- if (existing !== source) {
919
- writeFileSync(outPath, source);
920
- console.log(`[rsc-router] Generated route types -> ${outPath}`);
921
- }
922
- }
923
- }
924
-
925
- return {
926
- name: "@rangojs/router:discovery",
927
-
928
- config() {
929
- if (!opts?.enableBuildPrerender) return {};
930
- return {
931
- environments: {
932
- rsc: {
933
- build: {
934
- rollupOptions: {
935
- output: {
936
- manualChunks(id: string) {
937
- if (resolvedPrerenderModules?.has(id)) {
938
- return "__prerender-handlers";
939
- }
940
- if (resolvedStaticModules?.has(id)) {
941
- return "__static-handlers";
942
- }
943
- },
944
- },
945
- },
946
- },
947
- },
948
- },
949
- };
950
- },
951
-
952
- configResolved(config) {
953
- projectRoot = config.root;
954
- isBuildMode = config.command === "build";
955
- // Capture user's resolve aliases for the temp server
956
- userResolveAlias = config.resolve.alias;
957
- // Compile include/exclude patterns into a scan filter
958
- if (opts?.include || opts?.exclude) {
959
- scanFilter = createScanFilter(projectRoot, {
960
- include: opts.include,
961
- exclude: opts.exclude,
962
- });
963
- }
964
- // Generate combined named-routes.gen.ts from static source parsing.
965
- // Runs before the dev server starts so the gen file exists immediately for IDE.
966
- // In build mode, the runtime discovery in buildStart produces the definitive
967
- // named-routes.gen.ts (including dynamically generated routes).
968
- // preserveIfLarger prevents overwriting a previously generated complete
969
- // file with a partial one.
970
- if (opts?.staticRouteTypesGeneration !== false) {
971
- cachedRouterFiles = findRouterFiles(projectRoot, scanFilter);
972
- writeCombinedRouteTypes(projectRoot, cachedRouterFiles, { preserveIfLarger: true });
973
- }
974
- // Resolve prerenderHandlerModules and staticHandlerModules from the consolidated IDs plugin's API.
975
- if (opts?.enableBuildPrerender) {
976
- const idsPlugin = config.plugins.find(
977
- (p: any) => p.name === "@rangojs/router:expose-internal-ids",
978
- );
979
- resolvedPrerenderModules =
980
- (idsPlugin?.api as any)?.prerenderHandlerModules;
981
- resolvedStaticModules =
982
- (idsPlugin?.api as any)?.staticHandlerModules;
983
- }
984
- },
985
-
986
- // Dev mode: discover routers and populate manifest in memory.
987
- // Skipped in build mode (buildStart handles it).
988
- configureServer(server) {
989
- if (isBuildMode) return;
990
- // Skip if this is a temp server created by buildStart
991
- if ((globalThis as any).__rscRouterDiscoveryActive) return;
992
- devServer = server;
993
-
994
- // Discovery promise that the handler can await if requests arrive
995
- // before discovery completes
996
- let resolveDiscovery: () => void;
997
- const discoveryPromise = new Promise<void>((resolve) => {
998
- resolveDiscovery = resolve;
999
- });
1000
-
1001
- // Compute dev server origin from resolved URLs (preferred) or config port (fallback).
1002
- // Called after discovery (or in the load hook) when the server may be listening.
1003
- const getDevServerOrigin = () =>
1004
- server.resolvedUrls?.local?.[0]?.replace(/\/$/, '')
1005
- || `http://localhost:${server.config.server.port || 5173}`;
1006
-
1007
- const discover = async () => {
1008
- const rscEnv = (server.environments as any)?.rsc;
1009
- if (!rscEnv?.runner) {
1010
- // Cloudflare dev: no module runner available (workerd-based RSC env).
1011
- // Set devServerOrigin so the virtual module can inject __PRERENDER_DEV_URL
1012
- // for on-demand prerender via the /__rsc_prerender endpoint.
1013
- devServerOrigin = getDevServerOrigin();
1014
- resolveDiscovery!();
1015
- return;
1016
- }
1017
-
1018
- try {
1019
- // Set the readiness gate BEFORE discovery so early requests
1020
- // block until manifest is populated
1021
- const serverMod = await rscEnv.runner.import("@rangojs/router/server");
1022
- if (serverMod?.setManifestReadyPromise) {
1023
- serverMod.setManifestReadyPromise(discoveryPromise);
1024
- }
1025
-
1026
- const serverModAfterDiscovery = await discoverRouters(rscEnv);
1027
-
1028
- // Save registry for the /__rsc_prerender endpoint (avoids creating a temp server)
1029
- mainRegistry = serverModAfterDiscovery?.RouterRegistry ?? null;
1030
-
1031
- // Store server origin for dev prerender endpoint (virtual module injection)
1032
- devServerOrigin = getDevServerOrigin();
1033
-
1034
- // Update named-routes.gen.ts from runtime discovery.
1035
- // The runtime manifest is the source of truth: it evaluates dynamic
1036
- // routes (e.g. Array.from loops) that the static parser cannot see.
1037
- // writeRouteTypesFiles() only writes when content changes, so this
1038
- // won't cause unnecessary HMR triggers.
1039
- writeRouteTypesFiles();
1040
-
1041
- // Populate the route map in the RSC env
1042
- if (mergedRouteManifest && serverMod?.setCachedManifest) {
1043
- serverMod.setCachedManifest(mergedRouteManifest);
1044
- }
1045
- if (mergedPrecomputedEntries && mergedPrecomputedEntries.length > 0 && serverMod?.setPrecomputedEntries) {
1046
- serverMod.setPrecomputedEntries(mergedPrecomputedEntries);
1047
- }
1048
- if (mergedRouteTrie && serverMod?.setRouteTrie) {
1049
- serverMod.setRouteTrie(mergedRouteTrie);
1050
- }
1051
- // Populate per-router isolated data eagerly in dev (HMR).
1052
- // In production builds, per-router data is loaded lazily via import().
1053
- if (serverMod?.setRouterManifest) {
1054
- for (const [routerId, manifest] of perRouterManifestDataMap) {
1055
- serverMod.setRouterManifest(routerId, manifest);
1056
- }
1057
- }
1058
- if (serverMod?.setRouterTrie) {
1059
- for (const [routerId, trie] of perRouterTrieMap) {
1060
- serverMod.setRouterTrie(routerId, trie);
1061
- }
1062
- }
1063
- if (serverMod?.setRouterPrecomputedEntries) {
1064
- for (const [routerId, entries] of perRouterPrecomputedMap) {
1065
- serverMod.setRouterPrecomputedEntries(routerId, entries);
1066
- }
1067
- }
1068
- } catch (err: any) {
1069
- console.warn(
1070
- `[rsc-router] Router discovery failed: ${err.message}\n${err.stack}`
1071
- );
1072
- } finally {
1073
- resolveDiscovery!();
1074
- }
1075
- };
1076
-
1077
- // Schedule after all plugins have finished configureServer.
1078
- // Store the promise so the virtual module's load hook can await it.
1079
- discoveryDone = new Promise<void>((resolve) => {
1080
- setTimeout(() => discover().then(resolve, resolve), 0);
1081
- });
1082
-
1083
- // Dev-mode on-demand prerender endpoint.
1084
- // When workerd hits a prerender route, it fetches this endpoint instead of
1085
- // trying to run node:fs-dependent handlers in the Cloudflare environment.
1086
- //
1087
- // Node.js preset: uses the main server's RSC environment directly (router
1088
- // instances are already discovered and have matchForPrerender).
1089
- // Cloudflare preset: lazily creates a Node.js temp server because the main
1090
- // RSC environment uses workerd where node:fs can't access the host filesystem.
1091
- let prerenderTempServer: any = null;
1092
- let prerenderNodeRegistry: Map<string, any> | null = null;
1093
- // Registry from the main server's RSC environment (populated by discoverRouters)
1094
- let mainRegistry: Map<string, any> | null = null;
1095
-
1096
- server.middlewares.use("/__rsc_prerender", async (req: any, res: any) => {
1097
- if (discoveryDone) await discoveryDone;
1098
-
1099
- const url = new URL(req.url || "/", "http://localhost");
1100
- const pathname = url.searchParams.get("pathname");
1101
- if (!pathname) {
1102
- res.statusCode = 400;
1103
- res.end("Missing pathname");
1104
- return;
1105
- }
1106
-
1107
- // Prefer the main server's registry (Node.js preset: module runner available).
1108
- // Fall back to a temp server for Cloudflare where the main RSC env uses workerd.
1109
- let registry = mainRegistry;
1110
-
1111
- if (!registry) {
1112
- // No main registry: the RSC env has no module runner (Cloudflare dev).
1113
- // Lazily create a Node.js temp server for prerender evaluation.
1114
- if (!prerenderNodeRegistry) {
1115
- try {
1116
- const { default: rsc } = await import("@vitejs/plugin-rsc");
1117
- prerenderTempServer = await createViteServer({
1118
- root: projectRoot,
1119
- configFile: false,
1120
- server: { middlewareMode: true },
1121
- appType: "custom",
1122
- logLevel: "silent",
1123
- cacheDir: "node_modules/.vite_prerender",
1124
- resolve: { alias: userResolveAlias },
1125
- esbuild: { jsx: "automatic", jsxImportSource: "react" },
1126
- plugins: [
1127
- rsc({ entries: { client: "virtual:entry-client", ssr: "virtual:entry-ssr", rsc: entryPath } }),
1128
- createVersionPlugin(),
1129
- createVirtualStubPlugin(),
1130
- exposeInternalIds({ forceBuild: true }),
1131
- exposeRouterId(),
1132
- ],
1133
- });
1134
-
1135
- const tempRscEnv = (prerenderTempServer.environments as any)?.rsc;
1136
- if (tempRscEnv?.runner) {
1137
- await tempRscEnv.runner.import(entryPath);
1138
- const serverMod = await tempRscEnv.runner.import("@rangojs/router/server");
1139
- prerenderNodeRegistry = serverMod.RouterRegistry;
1140
- }
1141
- } catch (err: any) {
1142
- console.warn(`[rsc-router] Failed to create prerender runner: ${err.message}`);
1143
- }
1144
- }
1145
- registry = prerenderNodeRegistry;
1146
- }
1147
-
1148
- if (!registry || registry.size === 0) {
1149
- res.statusCode = 503;
1150
- res.end("Prerender runner not available");
1151
- return;
1152
- }
1153
-
1154
- for (const [, routerInstance] of registry) {
1155
- if (!routerInstance.matchForPrerender) continue;
1156
- try {
1157
- const result = await routerInstance.matchForPrerender(pathname, {});
1158
- if (!result) continue;
1159
- res.setHeader("content-type", "application/json");
1160
- res.end(JSON.stringify({ segments: result.segments, handles: result.handles }));
1161
- return;
1162
- } catch (err: any) {
1163
- console.warn(`[rsc-router] Dev prerender failed for ${pathname}: ${err.message}`);
1164
- }
1165
- }
1166
-
1167
- res.statusCode = 404;
1168
- res.end("No prerender match");
1169
- });
1170
-
1171
- // Watch url module and router files for changes and regenerate named-routes.gen.ts.
1172
- // Process files containing urls( or createRouter( to update the combined route map.
1173
- if (opts?.staticRouteTypesGeneration !== false) {
1174
- server.watcher.on("change", (filePath) => {
1175
- if (filePath.endsWith(".gen.ts")) return;
1176
- if (!filePath.endsWith(".ts") && !filePath.endsWith(".tsx")) return;
1177
- // Apply scan filter as early-exit before reading file
1178
- if (scanFilter && !scanFilter(filePath)) return;
1179
- try {
1180
- const source = readFileSync(filePath, "utf-8");
1181
- const trimmed = source.trimStart();
1182
- if (trimmed.startsWith('"use client"') || trimmed.startsWith("'use client'")) return;
1183
- const hasUrls = source.includes("urls(");
1184
- const hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
1185
- if (!hasUrls && !hasCreateRouter) return;
1186
- // Invalidate cache when a router file changes (new router added/removed)
1187
- if (hasCreateRouter) {
1188
- cachedRouterFiles = undefined;
1189
- }
1190
- writeCombinedRouteTypes(projectRoot, cachedRouterFiles);
1191
- } catch {
1192
- // Ignore read errors for deleted/moved files
1193
- }
1194
- });
1195
- }
1196
- },
1197
-
1198
- // Build mode: create a temporary Vite dev server to access the RSC
1199
- // environment's module runner, then discover routers and generate manifests.
1200
- // The manifest data is stored for the virtual module's load hook.
1201
- async buildStart() {
1202
- if (!isBuildMode) return;
1203
- // Only run once across environment builds
1204
- if (mergedRouteManifest !== null) return;
1205
-
1206
- let tempServer: any = null;
1207
- try {
1208
- // Prevent the temp server's plugin instances from running discovery
1209
- (globalThis as any).__rscRouterDiscoveryActive = true;
1210
-
1211
- // Create a minimal Vite server with just the RSC plugin.
1212
- // We bypass the user's config file because:
1213
- // - Custom environments (e.g., CloudflareDevEnvironment) may not expose
1214
- // a module runner compatible with runner.import()
1215
- // - The temp server only needs RSC conditions to import the router
1216
- const { default: rsc } = await import("@vitejs/plugin-rsc");
1217
- tempServer = await createViteServer({
1218
- root: projectRoot,
1219
- configFile: false,
1220
- server: { middlewareMode: true },
1221
- appType: "custom",
1222
- logLevel: "silent",
1223
- // Use the resolved aliases from the real config (includes user's path aliases
1224
- // like @/ -> src/ AND package aliases from rsc-router)
1225
- resolve: { alias: userResolveAlias },
1226
- // Enable automatic JSX runtime so .tsx files don't need `import React`.
1227
- // Without this, esbuild defaults to classic mode (React.createElement)
1228
- // which fails when lazy host-router handlers load sub-app modules with JSX.
1229
- esbuild: { jsx: "automatic", jsxImportSource: "react" },
1230
- plugins: [
1231
- rsc({ entries: { client: "virtual:entry-client", ssr: "virtual:entry-ssr", rsc: entryPath } }),
1232
- createVersionPlugin(),
1233
- // Stub virtual modules that the RSC entry may import
1234
- // (e.g., virtual:rsc-router/routes-manifest, virtual:rsc-router/loader-manifest)
1235
- createVirtualStubPlugin(),
1236
- // Inject handle + router IDs so prerender-collected handle data uses
1237
- // the same hashed keys as the production client/SSR bundles, and
1238
- // build-time router IDs match runtime IDs across environments.
1239
- exposeInternalIds({ forceBuild: true }),
1240
- exposeRouterId(),
1241
- ],
1242
- });
1243
-
1244
- const rscEnv = (tempServer.environments as any)?.rsc;
1245
- if (!rscEnv?.runner) {
1246
- console.warn(
1247
- "[rsc-router] RSC environment runner not available during build, skipping manifest generation"
1248
- );
1249
- return;
1250
- }
1251
-
1252
- await discoverRouters(rscEnv);
1253
- // Update named-routes.gen.ts from runtime discovery.
1254
- // The runtime manifest includes dynamically generated routes
1255
- // that the static parser cannot extract from source code.
1256
- writeRouteTypesFiles();
1257
- } catch (err: any) {
1258
- // Clean up before re-throwing so the temp server doesn't leak
1259
- delete (globalThis as any).__rscRouterDiscoveryActive;
1260
- if (tempServer) {
1261
- await tempServer.close();
1262
- }
1263
- // Extract the user source file from the stack trace (skip internal frames)
1264
- const sourceFile = err.stack
1265
- ?.split("\n")
1266
- .find((line: string) => line.includes(projectRoot) && !line.includes("node_modules"))
1267
- ?.match(/\(([^)]+)\)/)?.[1];
1268
- // Extract the route name from "Unknown route: <name>" errors
1269
- const routeName = err.message?.match(/Unknown route: (.+)/)?.[1];
1270
- const details = [
1271
- routeName ? ` Route name: ${routeName}` : null,
1272
- sourceFile ? ` File: ${sourceFile}` : null,
1273
- err.stack ? ` Stack:\n${err.stack}` : null,
1274
- ].filter(Boolean).join("\n");
1275
- throw new Error(
1276
- `[rsc-router] Build-time router discovery failed:\n${details}`
1277
- );
1278
- } finally {
1279
- delete (globalThis as any).__rscRouterDiscoveryActive;
1280
- if (tempServer) {
1281
- await tempServer.close();
1282
- }
1283
- }
1284
- },
1285
-
1286
- // Virtual module: provides the pre-generated route manifest as a JS module
1287
- // that calls setCachedManifest() at import time.
1288
- resolveId(id) {
1289
- if (id === VIRTUAL_ROUTES_MANIFEST_ID) {
1290
- return "\0" + VIRTUAL_ROUTES_MANIFEST_ID;
1291
- }
1292
- // Per-router virtual modules: virtual:rsc-router/routes-manifest/<routerId>
1293
- if (id.startsWith(VIRTUAL_ROUTES_MANIFEST_ID + "/")) {
1294
- return "\0" + id;
1295
- }
1296
- // virtual:rsc-router/prerender-paths removed: prerender data is served through the worker
1297
- return null;
1298
- },
1299
-
1300
- async load(id) {
1301
- if (id === "\0" + VIRTUAL_ROUTES_MANIFEST_ID) {
1302
- // In dev mode, wait for discovery to complete before emitting module content.
1303
- // This is critical for Cloudflare dev where the worker runs in a separate
1304
- // Miniflare process and can only receive manifest data via the virtual module.
1305
- if (discoveryDone) {
1306
- await discoveryDone;
1307
- }
1308
- const hasManifest = mergedRouteManifest && Object.keys(mergedRouteManifest).length > 0;
1309
- if (hasManifest) {
1310
- const lines = [
1311
- `import { setCachedManifest, setPrecomputedEntries, setRouteTrie, registerRouterManifestLoader } from "@rangojs/router/server";`,
1312
- `setCachedManifest(${jsonParseExpression(mergedRouteManifest)});`,
1313
- ];
1314
- if (mergedPrecomputedEntries && mergedPrecomputedEntries.length > 0) {
1315
- lines.push(`setPrecomputedEntries(${jsonParseExpression(mergedPrecomputedEntries)});`);
1316
- }
1317
- if (mergedRouteTrie) {
1318
- lines.push(`setRouteTrie(${jsonParseExpression(mergedRouteTrie)});`);
1319
- }
1320
- // Register lazy loaders for per-router manifest modules.
1321
- // Each import() uses a static string literal so Rollup creates separate chunks.
1322
- for (const routerId of perRouterManifestDataMap.keys()) {
1323
- lines.push(
1324
- `registerRouterManifestLoader(${JSON.stringify(routerId)}, () => import(${JSON.stringify(VIRTUAL_ROUTES_MANIFEST_ID + "/" + routerId)}));`,
1325
- );
1326
- }
1327
- if (!isBuildMode && devServerOrigin) {
1328
- lines.push(`globalThis.__PRERENDER_DEV_URL = ${JSON.stringify(devServerOrigin)};`);
1329
- }
1330
- return lines.join("\n");
1331
- }
1332
- // No manifest: either discovery hasn't completed or no runner (Cloudflare dev).
1333
- // Still inject __PRERENDER_DEV_URL so the prerender store can fetch on-demand.
1334
- // Re-resolve origin now since the server is listening by module load time.
1335
- if (!isBuildMode) {
1336
- const origin = devServerOrigin
1337
- || devServer?.resolvedUrls?.local?.[0]?.replace(/\/$/, '')
1338
- || (devServer && `http://localhost:${devServer.config.server.port || 5173}`);
1339
- if (origin) {
1340
- devServerOrigin = origin;
1341
- return `globalThis.__PRERENDER_DEV_URL = ${JSON.stringify(origin)};`;
1342
- }
1343
- }
1344
- return `// Route manifest will be populated at runtime`;
1345
- }
1346
- // Per-router virtual modules: pure data exports (no side effects).
1347
- // ensureRouterManifest() imports the module and stores the data.
1348
- const perRouterPrefix = "\0" + VIRTUAL_ROUTES_MANIFEST_ID + "/";
1349
- if (id.startsWith(perRouterPrefix)) {
1350
- if (discoveryDone) {
1351
- await discoveryDone;
1352
- }
1353
- const routerId = id.slice(perRouterPrefix.length);
1354
- const manifest = perRouterManifestDataMap.get(routerId);
1355
- const trie = perRouterTrieMap.get(routerId);
1356
- const entries = perRouterPrecomputedMap.get(routerId);
1357
- const lines: string[] = [];
1358
- if (manifest) {
1359
- lines.push(`export const manifest = ${jsonParseExpression(manifest)};`);
1360
- }
1361
- if (trie) {
1362
- lines.push(`export const trie = ${jsonParseExpression(trie)};`);
1363
- }
1364
- if (entries && entries.length > 0) {
1365
- lines.push(`export const precomputedEntries = ${jsonParseExpression(entries)};`);
1366
- }
1367
- return lines.join("\n") || "// empty router manifest";
1368
- }
1369
- // virtual:rsc-router/prerender-paths load handler removed
1370
- return null;
1371
- },
1372
-
1373
- // Record handler chunk metadata and RSC entry filename during RSC build.
1374
- // Used by closeBundle for handler code eviction and prerender data injection.
1375
- generateBundle(_options: any, bundle: any) {
1376
- if (this.environment?.name !== "rsc") return;
1377
-
1378
- // Record RSC entry chunk filename for closeBundle injection
1379
- for (const [fileName, chunk] of Object.entries(bundle) as [string, any][]) {
1380
- if (chunk.type === "chunk" && chunk.isEntry) {
1381
- rscEntryFileName = fileName;
1382
- break;
1383
- }
1384
- }
1385
-
1386
- if (!resolvedPrerenderModules?.size) return;
1387
-
1388
- for (const [fileName, chunk] of Object.entries(bundle) as [string, any][]) {
1389
- if (chunk.type !== "chunk") continue;
1390
- if (!fileName.includes("__prerender-handlers")) continue;
1391
-
1392
- const handlers: Array<{ name: string; handlerId: string; passthrough: boolean }> = [];
1393
- for (const [, handlerNames] of resolvedPrerenderModules) {
1394
- for (const name of handlerNames) {
1395
- const idPattern = new RegExp(
1396
- `\\b${name}\\.\\$\\$id\\s*=\\s*"([^"]+)"`,
1397
- );
1398
- const match = chunk.code.match(idPattern);
1399
- if (match) {
1400
- // Detect passthrough option in the Prerender call.
1401
- const callStartRe = new RegExp(
1402
- `const\\s+${name}\\s*=\\s*Prerender\\s*(?:<[^>]*>)?\\s*\\(`,
1403
- );
1404
- const callStart = callStartRe.exec(chunk.code);
1405
- let isPassthrough = false;
1406
- if (callStart) {
1407
- const openPos = callStart.index + callStart[0].length;
1408
- let depth = 1;
1409
- let p = openPos;
1410
- while (p < chunk.code.length && depth > 0) {
1411
- const ch = chunk.code[p];
1412
- if (ch === '"' || ch === "'" || ch === "`") {
1413
- p++;
1414
- while (p < chunk.code.length && chunk.code[p] !== ch) {
1415
- if (chunk.code[p] === "\\") p++;
1416
- p++;
1417
- }
1418
- } else if (ch === "(") {
1419
- depth++;
1420
- } else if (ch === ")") {
1421
- depth--;
1422
- }
1423
- p++;
1424
- }
1425
- if (depth === 0) {
1426
- const callBody = chunk.code.slice(callStart.index, p);
1427
- isPassthrough = /passthrough\s*:\s*(!0|true)/.test(callBody);
1428
- }
1429
- }
1430
- handlers.push({ name, handlerId: match[1], passthrough: isPassthrough });
1431
- }
1432
- }
1433
- }
1434
-
1435
- if (handlers.length > 0) {
1436
- handlerChunkInfo = { fileName, exports: handlers };
1437
- }
1438
- break;
1439
- }
1440
-
1441
- },
1442
-
1443
- // Build-time pre-rendering: evict handler code and inject collected prerender data.
1444
- // Collection now happens in-process during discoverRouters() via RSC runner.
1445
- // closeBundle only needs to evict handlers and inject the in-memory data.
1446
- closeBundle: {
1447
- order: "post" as const,
1448
- sequential: true,
1449
- async handler() {
1450
- if (!isBuildMode) return;
1451
- if (!prerenderCollectedData || Object.keys(prerenderCollectedData).length === 0) return;
1452
-
1453
- // Find RSC entry (recorded in generateBundle, fallback to dist/rsc/index.js)
1454
- const rscEntryPath = resolve(projectRoot, "dist/rsc", rscEntryFileName ?? "index.js");
1455
-
1456
- // 1. Evict handler code from __prerender-handlers chunk.
1457
- // handlerChunkInfo is populated by generateBundle after the production RSC
1458
- // build completes. In Vite 6 multi-environment builds, the RSC build runs
1459
- // twice (analysis pass + production pass). handlerChunkInfo is only available
1460
- // after the production pass, so we run eviction whenever it becomes available.
1461
- if (handlerChunkInfo) {
1462
- const chunkPath = resolve(projectRoot, "dist/rsc", handlerChunkInfo.fileName);
1463
- try {
1464
- let code = readFileSync(chunkPath, "utf-8");
1465
- const originalSize = Buffer.byteLength(code);
1466
-
1467
- for (const { name, handlerId, passthrough } of handlerChunkInfo.exports) {
1468
- // Passthrough handlers stay in the bundle for live fallback
1469
- if (passthrough) continue;
1470
- const callStartRe = new RegExp(
1471
- `const\\s+${name}\\s*=\\s*Prerender\\s*(?:<[^>]*>)?\\s*\\(`,
1472
- );
1473
- const startMatch = callStartRe.exec(code);
1474
- if (!startMatch) continue;
1475
-
1476
- // Use paren-depth counting to find the matching close paren
1477
- const openParenPos = startMatch.index + startMatch[0].length;
1478
- let depth = 1;
1479
- let pos = openParenPos;
1480
- while (pos < code.length && depth > 0) {
1481
- const ch = code[pos];
1482
- if (ch === '"' || ch === "'" || ch === "`") {
1483
- pos++;
1484
- while (pos < code.length && code[pos] !== ch) {
1485
- if (code[pos] === "\\") pos++;
1486
- pos++;
1487
- }
1488
- } else if (ch === "(") {
1489
- depth++;
1490
- } else if (ch === ")") {
1491
- depth--;
1492
- }
1493
- pos++;
1494
- }
1495
- if (depth !== 0) continue;
1496
-
1497
- // pos is now after the closing paren. Skip trailing semicolon.
1498
- let rangeEnd = pos;
1499
- while (rangeEnd < code.length && /\s/.test(code[rangeEnd])) rangeEnd++;
1500
- if (code[rangeEnd] === ";") rangeEnd++;
1501
-
1502
- // Validate: the matched range should contain the expected handlerId
1503
- const matched = code.slice(startMatch.index, rangeEnd);
1504
- if (!matched.includes(handlerId)) continue;
1505
-
1506
- const stub = `const ${name} = { __brand: "prerenderHandler", $$id: "${handlerId}" };`;
1507
- code = code.slice(0, startMatch.index) + stub + code.slice(rangeEnd);
1508
-
1509
- // Remove the $$id assignment line (now redundant)
1510
- code = code.replace(
1511
- new RegExp(`\\n${name}\\.\\$\\$id\\s*=\\s*"[^"]+";`),
1512
- "",
1513
- );
1514
- }
1515
-
1516
- writeFileSync(chunkPath, code);
1517
- const newSize = Buffer.byteLength(code);
1518
- const savedKB = ((originalSize - newSize) / 1024).toFixed(1);
1519
- console.log(
1520
- `[rsc-router] Evicted handler code from RSC bundle (${savedKB} KB saved): ${handlerChunkInfo.fileName}`,
1521
- );
1522
- } catch (replaceErr: any) {
1523
- console.warn(
1524
- `[rsc-router] Failed to evict handler code: ${replaceErr.message}`,
1525
- );
1526
- }
1527
- // Clear after eviction to avoid re-running
1528
- handlerChunkInfo = null;
1529
- }
1530
-
1531
- // 2. Remap dev-mode client reference IDs in prerender data to production IDs.
1532
- // Prerender data is collected via a dev temp server whose RSC serializer
1533
- // uses dev URLs (e.g., /src/foo.tsx, /@fs/abs/path.tsx). Production uses
1534
- // SHA-256 hashes of root-relative paths. Rewrite the Flight I[] instructions.
1535
- for (const entry of Object.values(prerenderCollectedData)) {
1536
- for (const seg of (entry as any).segments) {
1537
- if (typeof seg.encoded !== "string") continue;
1538
- seg.encoded = seg.encoded.replace(
1539
- /I\["(\/[^"]+)"/g,
1540
- (_match: string, devId: string) => {
1541
- let rootRelative: string;
1542
- if (devId.startsWith("/@fs/")) {
1543
- // Absolute FS path via Vite dev server
1544
- const absPath = devId.slice(4); // strip /@fs
1545
- rootRelative = relative(projectRoot, absPath);
1546
- } else {
1547
- // Project-relative path with leading /
1548
- rootRelative = devId.slice(1);
1549
- }
1550
- const hash = createHash("sha256").update(rootRelative).digest("hex").slice(0, 12);
1551
- return `I["${hash}"`;
1552
- },
1553
- );
1554
- }
1555
- }
1556
-
1557
- // 3. Write prerender data as separate importable asset modules
1558
- // and inject a manifest import into the RSC entry.
1559
- if (existsSync(rscEntryPath)) {
1560
- const rscCode = readFileSync(rscEntryPath, "utf-8");
1561
- if (!rscCode.includes("__PRERENDER_MANIFEST")) {
1562
- try {
1563
- const assetsDir = resolve(projectRoot, "dist/rsc/assets");
1564
- mkdirSync(assetsDir, { recursive: true });
1565
-
1566
- const manifestEntries: string[] = [];
1567
- let totalBytes = 0;
1568
-
1569
- for (const [key, entry] of Object.entries(prerenderCollectedData)) {
1570
- const entryJson = JSON.stringify(entry);
1571
- const contentHash = createHash("sha256").update(entryJson).digest("hex").slice(0, 8);
1572
- const assetFileName = `__pr-${contentHash}.js`;
1573
- const assetPath = resolve(assetsDir, assetFileName);
1574
- const assetCode = `export default ${entryJson};\n`;
1575
- writeFileSync(assetPath, assetCode);
1576
- totalBytes += Buffer.byteLength(assetCode);
1577
- manifestEntries.push(`${JSON.stringify(key)}:()=>import("./assets/${assetFileName}")`);
1578
- }
1579
-
1580
- const manifestCode = `const m={${manifestEntries.join(",")}};export default m;\n`;
1581
- const manifestPath = resolve(projectRoot, "dist/rsc/__prerender-manifest.js");
1582
- writeFileSync(manifestPath, manifestCode);
1583
- totalBytes += Buffer.byteLength(manifestCode);
1584
-
1585
- const injection = `import __pm from "./__prerender-manifest.js";\nglobalThis.__PRERENDER_MANIFEST = __pm;\n`;
1586
- writeFileSync(rscEntryPath, injection + rscCode);
1587
-
1588
- const totalKB = (totalBytes / 1024).toFixed(1);
1589
- console.log(
1590
- `[rsc-router] Wrote prerender assets (${totalKB} KB total, ${Object.keys(prerenderCollectedData).length} entries)`,
1591
- );
1592
- } catch (err: any) {
1593
- throw new Error(`[rsc-router] Failed to write prerender assets: ${err.message}`);
1594
- }
1595
- }
1596
- }
1597
- },
1598
- },
1599
- };
1600
- }
1601
-
1602
- const VIRTUAL_ROUTES_MANIFEST_ID = "virtual:rsc-router/routes-manifest";
1603
- // VIRTUAL_PRERENDER_PATHS_ID removed: prerender data is served through the worker
1604
-
1605
- /**
1606
- * Resolve the entry path for build-time router discovery.
1607
- * - Node preset: uses the `router` option (may be undefined if auto-discovery failed).
1608
- * - Cloudflare preset: reads the `main` field from wrangler.json.
1609
- */
1610
- function resolveDiscoveryEntryPath(options: RangoOptions, routerPath?: string): string | undefined {
1611
- if (options.preset === "cloudflare") {
1612
- // Auto-detect from wrangler.json
1613
- const wranglerPaths = ["wrangler.json", "wrangler.jsonc"];
1614
- for (const filename of wranglerPaths) {
1615
- if (existsSync(filename)) {
1616
- try {
1617
- const raw = readFileSync(filename, "utf-8");
1618
- // Strip JSON comments for .jsonc
1619
- const cleaned = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
1620
- const config = JSON.parse(cleaned);
1621
- if (config.main) {
1622
- return config.main;
1623
- }
1624
- } catch {
1625
- // Ignore parse errors
1626
- }
1627
- }
1628
- }
1629
- return undefined;
1630
- }
1631
- // Node preset: use resolved routerPath (may be auto-discovered or explicit)
1632
- return routerPath;
1633
- }
1634
-
1635
- /**
1636
- * Stub plugin for virtual modules in the temp discovery server.
1637
- * The RSC entry may import virtual modules (routes-manifest, loader-manifest)
1638
- * that aren't available in the temp server. The RSC plugin also requires
1639
- * client/ssr entries which don't need real content for discovery.
1640
- */
1641
- function createVirtualStubPlugin(): Plugin {
1642
- const STUB_PREFIXES = [
1643
- "virtual:rsc-router/",
1644
- "virtual:entry-",
1645
- "virtual:vite-rsc/",
1646
- ];
1647
- return {
1648
- name: "@rangojs/router:virtual-stubs",
1649
- resolveId(id) {
1650
- if (STUB_PREFIXES.some((p) => id.startsWith(p))) {
1651
- return "\0stub:" + id;
1652
- }
1653
- return null;
1654
- },
1655
- load(id) {
1656
- if (id.startsWith("\0stub:")) {
1657
- return "export default {}";
1658
- }
1659
- return null;
1660
- },
1661
- };
1662
- }
1663
-
1664
- /**
1665
- * Generate a deterministic 12-char hex hash from a router id.
1666
- * Used to create collision-free directory names for per-router static output.
1667
- */
1668
- function hashRouterId(id: string): string {
1669
- return createHash("sha256").update(id).digest("hex").slice(0, 12);
1670
- }
1671
-
1672
- /**
1673
- * Wrap a value as `JSON.parse('...')` instead of a JS object literal.
1674
- * V8's JSON parser is significantly faster than its full JS parser for large
1675
- * objects, so this improves startup time for big route manifests.
1676
- */
1677
- function jsonParseExpression(value: unknown): string {
1678
- const json = JSON.stringify(value);
1679
- const escaped = json.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
1680
- return `JSON.parse('${escaped}')`;
1681
- }
1682
-
1683
- /**
1684
- * Plugin that auto-injects VERSION and routes-manifest into custom entry.rsc files.
1685
- * If a custom entry.rsc file uses createRSCHandler but doesn't pass version,
1686
- * this transform adds the import and property automatically.
1687
- * Also ensures the routes-manifest virtual module is always imported.
1688
- * @internal
1689
- */
1690
- function createVersionInjectorPlugin(rscEntryPath: string): Plugin {
1691
- let projectRoot = "";
1692
- let resolvedEntryPath = "";
1693
-
1694
- return {
1695
- name: "@rangojs/router:version-injector",
1696
- enforce: "pre",
1697
-
1698
- configResolved(config) {
1699
- projectRoot = config.root;
1700
- resolvedEntryPath = resolve(projectRoot, rscEntryPath);
1701
- },
1702
-
1703
- transform(code, id) {
1704
- // Only transform the RSC entry file
1705
- const normalizedId = Vite.normalizePath(id);
1706
- const normalizedEntry = Vite.normalizePath(resolvedEntryPath);
1707
-
1708
- if (normalizedId !== normalizedEntry) {
1709
- return null;
1710
- }
1711
-
1712
- // Prepend imports at the top of the file. ES imports are hoisted
1713
- // by the module system, so source position is irrelevant.
1714
- const prepend: string[] = [];
1715
- let newCode = code;
1716
-
1717
- if (!code.includes("virtual:rsc-router/routes-manifest")) {
1718
- prepend.push(`import "virtual:rsc-router/routes-manifest";`);
1719
- }
1720
-
1721
- // Auto-inject VERSION if file uses createRSCHandler without version
1722
- const needsVersion =
1723
- code.includes("createRSCHandler") &&
1724
- !code.includes("@rangojs/router:version") &&
1725
- /createRSCHandler\s*\(\s*\{/.test(code);
1726
-
1727
- if (needsVersion) {
1728
- prepend.push(`import { VERSION } from "@rangojs/router:version";`);
1729
- newCode = newCode.replace(
1730
- /createRSCHandler\s*\(\s*\{/,
1731
- "createRSCHandler({\n version: VERSION,"
1732
- );
1733
- }
1734
-
1735
- if (prepend.length === 0 && newCode === code) return null;
1736
-
1737
- newCode = prepend.join("\n") + (prepend.length > 0 ? "\n" : "") + newCode;
1738
-
1739
- return {
1740
- code: newCode,
1741
- map: null,
1742
- };
1743
- },
1744
- };
1745
- }
1746
-
1747
- const _require = createRequire(import.meta.url);
1748
- const _rangoVersion: string = _require("../../package.json").version;
1749
-
1750
- let _bannerPrinted = false;
1751
-
1752
- function printBanner(
1753
- mode: "dev" | "build" | "preview",
1754
- preset: string,
1755
- version: string
1756
- ): void {
1757
- if (_bannerPrinted) return;
1758
- _bannerPrinted = true;
1759
-
1760
- // ANSI codes
1761
- const dim = "\x1b[2m";
1762
- const bold = "\x1b[1m";
1763
- const reset = "\x1b[0m";
1764
-
1765
- const banner = `
1766
- ${dim} ✦ ✦ ✧. . .${reset}
1767
- ${dim} ╱${reset} ${bold}╔═╗${reset}${dim} * ╱ ✦ *${reset}
1768
- ${dim} ${reset}${bold}║ ║${reset} ${bold}╔═╗${reset}${dim} * ✧. ╱${reset}
1769
- ${dim} ${reset}${bold}╔╗ ║ ║ ║ ║${reset}${dim} * ╱${reset}
1770
- ${dim} ${reset}${bold}║║ ║ ║ ║ ║ ╦═╗╔═╗╔╗╔╔═╗╔═╗${reset}${dim} ✧ ✦${reset}
1771
- ${dim} ${reset}${bold}═╣║ ║ ╠═╝ ║ ╠╦╝╠═╣║║║║ ╦║ ║${reset}${dim} * ✧${reset}
1772
- ${dim} ${reset}${bold}║╚═╝ ╔═══╝ ╩╚═╩ ╩╝╚╝╚═╝╚═╝${reset}${dim} ✦ . *${reset}
1773
- ${dim} ${reset}${bold}╚══╗ ║${reset}${dim} * RSC Wrangler ✧ ✦${reset}
1774
- ${dim} * ${reset}${bold}║ ╠═${reset}${dim} * ✧. ╱${reset}
1775
- ${bold}══════╝ ╚═════════╩═══${reset}${dim} ✦ *${reset}
1776
-
1777
- v${version} · ${preset} · ${mode}
1778
- `;
1779
-
1780
- console.log(banner);
1781
- }
1782
-
1783
- /**
1784
- * Vite plugin for @rangojs/router.
1785
- *
1786
- * Includes @vitejs/plugin-rsc and all necessary transforms for the router
1787
- * to function correctly with React Server Components.
1788
- *
1789
- * @example Node.js (default)
1790
- * ```ts
1791
- * export default defineConfig({
1792
- * plugins: [react(), rango({ router: './src/router.tsx' })],
1793
- * });
1794
- * ```
1795
- *
1796
- * @example Cloudflare Workers
1797
- * ```ts
1798
- * export default defineConfig({
1799
- * plugins: [
1800
- * react(),
1801
- * rango({ preset: 'cloudflare' }),
1802
- * cloudflare({ viteEnvironment: { name: 'rsc' } }),
1803
- * ],
1804
- * });
1805
- * ```
1806
- */
1807
- export async function rango(
1808
- options?: RangoOptions
1809
- ): Promise<PluginOption[]> {
1810
- const resolvedOptions: RangoOptions = options ?? { preset: "node" };
1811
- const preset = resolvedOptions.preset ?? "node";
1812
- const showBanner = resolvedOptions.banner ?? true;
1813
-
1814
- const plugins: PluginOption[] = [];
1815
-
1816
- // Get package resolution info (workspace vs npm install)
1817
- const rangoAliases = getPackageAliases();
1818
- const excludeDeps = getExcludeDeps();
1819
-
1820
- // Track RSC entry path for version injection
1821
- let rscEntryPath: string | null = null;
1822
-
1823
- // Resolved router path (node preset only, may be auto-discovered)
1824
- let routerPath: string | undefined;
1825
-
1826
- // Build-time prerendering is enabled for both presets.
1827
- // Collection runs in-process via the RSC dev environment runner during discoverRouters().
1828
- const prerenderEnabled = true;
1829
-
1830
- if (preset === "cloudflare") {
1831
- // Cloudflare preset: configure entries for cloudflare worker setup
1832
- // Router is not needed here - worker.rsc.tsx imports it directly
1833
-
1834
- // Dynamically import @vitejs/plugin-rsc
1835
- const { default: rsc } = await import("@vitejs/plugin-rsc");
1836
-
1837
- // Only client and ssr entries - rsc entry is handled by cloudflare plugin
1838
- // Always use virtual modules for cloudflare preset
1839
- const finalEntries: { client: string; ssr: string } = {
1840
- client: VIRTUAL_IDS.browser,
1841
- ssr: VIRTUAL_IDS.ssr,
1842
- };
1843
-
1844
- plugins.push({
1845
- name: "@rangojs/router:cloudflare-integration",
1846
- enforce: "pre",
1847
-
1848
- config() {
1849
- // Configure environments for cloudflare deployment
1850
- return {
1851
- // Exclude rsc-router modules from optimization to prevent module duplication
1852
- // This ensures the same Context instance is used by both browser entry and RSC proxy modules
1853
- optimizeDeps: {
1854
- exclude: excludeDeps,
1855
- esbuildOptions: sharedEsbuildOptions,
1856
- },
1857
- resolve: {
1858
- alias: rangoAliases,
1859
- },
1860
- build: {
1861
- rollupOptions: { onwarn },
1862
- },
1863
- environments: {
1864
- client: {
1865
- build: {
1866
- rollupOptions: {
1867
- output: {
1868
- manualChunks: getManualChunks,
1869
- },
1870
- },
1871
- },
1872
- // Pre-bundle rsc-html-stream to prevent discovery during first request
1873
- // Exclude rsc-router modules to ensure same Context instance
1874
- optimizeDeps: {
1875
- include: ["rsc-html-stream/client"],
1876
- exclude: excludeDeps,
1877
- esbuildOptions: sharedEsbuildOptions,
1878
- },
1879
- },
1880
- ssr: {
1881
- // Build SSR inside RSC directory so wrangler can deploy self-contained dist/rsc
1882
- build: {
1883
- outDir: "./dist/rsc/ssr",
1884
- },
1885
- resolve: {
1886
- // Ensure single React instance in SSR child environment
1887
- dedupe: ["react", "react-dom"],
1888
- },
1889
- // Pre-bundle SSR entry and React for proper module linking with childEnvironments
1890
- // All deps must be listed to avoid late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
1891
- optimizeDeps: {
1892
- entries: [finalEntries.ssr],
1893
- include: [
1894
- "react",
1895
- "react-dom",
1896
- "react-dom/server.edge",
1897
- "react-dom/static.edge",
1898
- "react/jsx-runtime",
1899
- "react/jsx-dev-runtime",
1900
- "rsc-html-stream/server",
1901
- "@vitejs/plugin-rsc/vendor/react-server-dom/client.edge",
1902
- ],
1903
- exclude: excludeDeps,
1904
- esbuildOptions: sharedEsbuildOptions,
1905
- },
1906
- },
1907
- rsc: {
1908
- // RSC environment needs exclude list and esbuild options
1909
- // Exclude rsc-router modules to prevent createContext in RSC environment
1910
- optimizeDeps: {
1911
- // Pre-bundle all RSC deps to prevent late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
1912
- include: [
1913
- "react",
1914
- "react/jsx-runtime",
1915
- "react/jsx-dev-runtime",
1916
- "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge",
1917
- ],
1918
- exclude: excludeDeps,
1919
- esbuildOptions: sharedEsbuildOptions,
1920
- },
1921
- },
1922
- },
1923
- };
1924
- },
1925
-
1926
- configResolved(config) {
1927
- if (showBanner) {
1928
- const mode = config.command === "serve" ? (process.argv.includes("preview") ? "preview" : "dev") : "build";
1929
- printBanner(mode, "cloudflare", _rangoVersion);
1930
- }
1931
- },
1932
-
1933
- });
1934
-
1935
- plugins.push(createVirtualEntriesPlugin(finalEntries));
1936
-
1937
- // Add RSC plugin with cloudflare-specific options
1938
- // Note: loadModuleDevProxy should NOT be used with childEnvironments
1939
- // since SSR runs in workerd alongside RSC
1940
- plugins.push(
1941
- rsc({
1942
- get entries() {
1943
- return finalEntries;
1944
- },
1945
- serverHandler: false,
1946
- }) as PluginOption
1947
- );
1948
- } else {
1949
- // Node preset: full RSC plugin integration
1950
- const nodeOptions = resolvedOptions as RangoNodeOptions;
1951
- routerPath = nodeOptions.router;
1952
-
1953
- // Auto-discover router when not specified
1954
- if (!routerPath) {
1955
- const earlyFilter = createScanFilter(process.cwd(), {
1956
- include: resolvedOptions.include,
1957
- exclude: resolvedOptions.exclude,
1958
- });
1959
- const candidates = findRouterFiles(process.cwd(), earlyFilter);
1960
- if (candidates.length === 1) {
1961
- // Convert absolute path to relative ./path
1962
- const abs = candidates[0];
1963
- const rel = abs.startsWith(process.cwd())
1964
- ? "./" + abs.slice(process.cwd().length + 1)
1965
- : abs;
1966
- routerPath = rel;
1967
- } else if (candidates.length > 1) {
1968
- const cwd = process.cwd();
1969
- const list = candidates
1970
- .map((f) => " - " + (f.startsWith(cwd) ? f.slice(cwd.length + 1) : f))
1971
- .join("\n");
1972
- throw new Error(
1973
- `[rsc-router] Multiple routers found. Specify \`router\` to choose one:\n${list}`
1974
- );
1975
- }
1976
- // 0 found: routerPath stays undefined, warn at startup via discovery plugin
1977
- }
1978
-
1979
- const rscOption = nodeOptions.rsc ?? true;
1980
-
1981
- // Add RSC plugin by default (can be disabled with rsc: false)
1982
- if (rscOption !== false) {
1983
- // Dynamically import @vitejs/plugin-rsc
1984
- const { default: rsc } = await import("@vitejs/plugin-rsc");
1985
-
1986
- // Resolve entry paths: use explicit config or virtual modules
1987
- const userEntries =
1988
- typeof rscOption === "boolean" ? {} : rscOption.entries || {};
1989
- const finalEntries = {
1990
- client: userEntries.client ?? VIRTUAL_IDS.browser,
1991
- ssr: userEntries.ssr ?? VIRTUAL_IDS.ssr,
1992
- rsc: userEntries.rsc ?? VIRTUAL_IDS.rsc,
1993
- };
1994
-
1995
- // Track RSC entry for version injection (only if custom entry provided)
1996
- rscEntryPath = userEntries.rsc ?? null;
1997
-
1998
- // Create wrapper plugin that checks for duplicates
1999
- let hasWarnedDuplicate = false;
2000
-
2001
- plugins.push({
2002
- name: "@rangojs/router:rsc-integration",
2003
- enforce: "pre",
2004
-
2005
- config() {
2006
- // Configure environments for RSC
2007
- // When using virtual entries, we need to explicitly configure optimizeDeps
2008
- // so Vite pre-bundles React before processing the virtual modules.
2009
- // Without this, the dep optimizer may run multiple times with different hashes,
2010
- // causing React instance mismatches.
2011
- const useVirtualClient = finalEntries.client === VIRTUAL_IDS.browser;
2012
- const useVirtualSSR = finalEntries.ssr === VIRTUAL_IDS.ssr;
2013
- const useVirtualRSC = finalEntries.rsc === VIRTUAL_IDS.rsc;
2014
-
2015
- return {
2016
- // Exclude rsc-router modules from optimization to prevent module duplication
2017
- // This ensures the same Context instance is used by both browser entry and RSC proxy modules
2018
- optimizeDeps: {
2019
- exclude: excludeDeps,
2020
- esbuildOptions: sharedEsbuildOptions,
2021
- },
2022
- build: {
2023
- rollupOptions: { onwarn },
2024
- },
2025
- resolve: {
2026
- alias: rangoAliases,
2027
- },
2028
- environments: {
2029
- client: {
2030
- build: {
2031
- rollupOptions: {
2032
- output: {
2033
- manualChunks: getManualChunks,
2034
- },
2035
- },
2036
- },
2037
- // Always exclude rsc-router modules, conditionally add virtual entry
2038
- optimizeDeps: {
2039
- exclude: excludeDeps,
2040
- esbuildOptions: sharedEsbuildOptions,
2041
- ...(useVirtualClient && {
2042
- // Tell Vite to scan the virtual entry for dependencies
2043
- entries: [VIRTUAL_IDS.browser],
2044
- }),
2045
- },
2046
- },
2047
- ...(useVirtualSSR && {
2048
- ssr: {
2049
- optimizeDeps: {
2050
- entries: [VIRTUAL_IDS.ssr],
2051
- // Pre-bundle all SSR deps to prevent late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
2052
- include: [
2053
- "react",
2054
- "react-dom",
2055
- "react-dom/server.edge",
2056
- "react-dom/static.edge",
2057
- "react/jsx-runtime",
2058
- "react/jsx-dev-runtime",
2059
- "@vitejs/plugin-rsc/vendor/react-server-dom/client.edge",
2060
- ],
2061
- exclude: excludeDeps,
2062
- esbuildOptions: sharedEsbuildOptions,
2063
- },
2064
- },
2065
- }),
2066
- ...(useVirtualRSC && {
2067
- rsc: {
2068
- optimizeDeps: {
2069
- entries: [VIRTUAL_IDS.rsc],
2070
- // Pre-bundle all RSC deps to prevent late discovery triggering ERR_OUTDATED_OPTIMIZED_DEP
2071
- include: [
2072
- "react",
2073
- "react/jsx-runtime",
2074
- "react/jsx-dev-runtime",
2075
- "@vitejs/plugin-rsc/vendor/react-server-dom/server.edge",
2076
- ],
2077
- esbuildOptions: sharedEsbuildOptions,
2078
- },
2079
- },
2080
- }),
2081
- },
2082
- };
2083
- },
2084
-
2085
- configResolved(config) {
2086
- if (showBanner) {
2087
- const mode = config.command === "serve" ? (process.argv.includes("preview") ? "preview" : "dev") : "build";
2088
- printBanner(mode, "node", _rangoVersion);
2089
- }
2090
-
2091
- // Count how many RSC base plugins there are (rsc:minimal is the main one)
2092
- const rscMinimalCount = config.plugins.filter(
2093
- (p) => p.name === "rsc:minimal"
2094
- ).length;
2095
-
2096
- if (rscMinimalCount > 1 && !hasWarnedDuplicate) {
2097
- hasWarnedDuplicate = true;
2098
- console.warn(
2099
- "[rsc-router] Duplicate @vitejs/plugin-rsc detected. " +
2100
- "Remove rsc() from your config or use rango({ rsc: false }) for manual configuration."
2101
- );
2102
- }
2103
- },
2104
- });
2105
-
2106
- // Add virtual entries plugin
2107
- plugins.push(createVirtualEntriesPlugin(finalEntries, routerPath));
2108
-
2109
- // Add the RSC plugin directly
2110
- // Cast to PluginOption to handle type differences between bundled vite types
2111
- plugins.push(
2112
- rsc({
2113
- entries: finalEntries,
2114
- }) as PluginOption
2115
- );
2116
- }
2117
- }
2118
-
2119
- plugins.push(exposeActionId());
2120
-
2121
- // Consolidated plugin for create* ID injection (enforce: "post"):
2122
- // loaders, handles, location state, and prerender handlers.
2123
- plugins.push(exposeInternalIds());
2124
-
2125
- // Router ID injection runs at normal priority (no enforce) to avoid
2126
- // changing Vite's dep optimization timing.
2127
- plugins.push(exposeRouterId());
2128
-
2129
- // Add version virtual module plugin for cache invalidation
2130
- plugins.push(createVersionPlugin());
2131
-
2132
- // Resolve discovery entry path (used for both discovery and version injection).
2133
- // Node preset: uses the (possibly auto-discovered) router path.
2134
- // Cloudflare preset: auto-detects RSC entry from wrangler.json main field.
2135
- const discoveryEntryPath = resolveDiscoveryEntryPath(
2136
- resolvedOptions,
2137
- preset !== "cloudflare" ? routerPath : undefined,
2138
- );
2139
-
2140
- // Add version injector for custom entry.rsc files.
2141
- // For Cloudflare preset, the RSC entry is the worker file (from wrangler.json).
2142
- const injectorEntryPath = rscEntryPath ?? (preset === "cloudflare" ? discoveryEntryPath : null);
2143
- if (injectorEntryPath) {
2144
- plugins.push(createVersionInjectorPlugin(injectorEntryPath));
2145
- }
2146
-
2147
- // Transform CJS vendor files to ESM for browser compatibility
2148
- // optimizeDeps.include doesn't work because the file is loaded after initial optimization
2149
- plugins.push(createCjsToEsmPlugin());
2150
-
2151
- // Add router discovery plugin for build-time manifest generation.
2152
- if (discoveryEntryPath) {
2153
- plugins.push(createRouterDiscoveryPlugin(discoveryEntryPath, {
2154
- enableBuildPrerender: prerenderEnabled,
2155
- staticRouteTypesGeneration: resolvedOptions.staticRouteTypesGeneration,
2156
- include: resolvedOptions.include,
2157
- exclude: resolvedOptions.exclude,
2158
- }));
2159
- }
2160
-
2161
- return plugins;
2162
- }
2163
-
2164
-
2165
-
2166
- /**
2167
- * Transform CJS vendor files from @vitejs/plugin-rsc to ESM for browser compatibility.
2168
- * The react-server-dom vendor files are shipped as CJS which doesn't work in browsers.
2169
- */
2170
- function createCjsToEsmPlugin(): Plugin {
2171
- return {
2172
- name: "@rangojs/router:cjs-to-esm",
2173
- enforce: "pre",
2174
- transform(code, id) {
2175
- const cleanId = id.split("?")[0];
2176
-
2177
- // Transform the client.browser.js entry point to re-export from CJS
2178
- if (
2179
- cleanId.includes("vendor/react-server-dom/client.browser.js") ||
2180
- cleanId.includes("vendor\\react-server-dom\\client.browser.js")
2181
- ) {
2182
- const isProd = process.env.NODE_ENV === "production";
2183
- const cjsFile = isProd
2184
- ? "./cjs/react-server-dom-webpack-client.browser.production.js"
2185
- : "./cjs/react-server-dom-webpack-client.browser.development.js";
2186
-
2187
- return {
2188
- code: `export * from "${cjsFile}";`,
2189
- map: null,
2190
- };
2191
- }
2192
-
2193
- // Transform the actual CJS files to ESM
2194
- if (
2195
- (cleanId.includes("vendor/react-server-dom/cjs/") ||
2196
- cleanId.includes("vendor\\react-server-dom\\cjs\\")) &&
2197
- cleanId.includes("client.browser")
2198
- ) {
2199
- let transformed = code;
2200
-
2201
- // Extract the license comment to preserve it
2202
- const licenseMatch = transformed.match(/^\/\*\*[\s\S]*?\*\//);
2203
- const license = licenseMatch ? licenseMatch[0] : "";
2204
- if (license) {
2205
- transformed = transformed.slice(license.length);
2206
- }
2207
-
2208
- // Remove "use strict" (both dev and prod have this)
2209
- transformed = transformed.replace(/^\s*["']use strict["'];\s*/, "");
2210
-
2211
- // Remove the conditional IIFE wrapper (development only)
2212
- transformed = transformed.replace(
2213
- /^\s*["']production["']\s*!==\s*process\.env\.NODE_ENV\s*&&\s*\(function\s*\(\)\s*\{/,
2214
- ""
2215
- );
2216
-
2217
- // Remove the closing of the conditional IIFE at the end (development only)
2218
- transformed = transformed.replace(/\}\)\(\);?\s*$/, "");
2219
-
2220
- // Replace require('react') and require('react-dom') with imports (development)
2221
- transformed = transformed.replace(
2222
- /var\s+React\s*=\s*require\s*\(\s*["']react["']\s*\)\s*,[\s\n]+ReactDOM\s*=\s*require\s*\(\s*["']react-dom["']\s*\)\s*,/g,
2223
- 'import React from "react";\nimport ReactDOM from "react-dom";\nvar '
2224
- );
2225
-
2226
- // Replace require('react-dom') only (production - doesn't import React)
2227
- transformed = transformed.replace(
2228
- /var\s+ReactDOM\s*=\s*require\s*\(\s*["']react-dom["']\s*\)\s*,/g,
2229
- 'import ReactDOM from "react-dom";\nvar '
2230
- );
2231
-
2232
- // Transform exports.xyz = function() to export function xyz()
2233
- transformed = transformed.replace(
2234
- /exports\.(\w+)\s*=\s*function\s*\(/g,
2235
- "export function $1("
2236
- );
2237
-
2238
- // Transform exports.xyz = value to export const xyz = value
2239
- transformed = transformed.replace(
2240
- /exports\.(\w+)\s*=/g,
2241
- "export const $1 ="
2242
- );
2243
-
2244
- // Reconstruct with license at the top
2245
- transformed = license + "\n" + transformed;
2246
-
2247
- return {
2248
- code: transformed,
2249
- map: null,
2250
- };
2251
- }
2252
-
2253
- return null;
2254
- },
2255
- };
2256
- }
2
+ * Public API for @rangojs/router/vite
3
+ *
4
+ * Exports: rango() plugin factory, poke() dev utility plugin,
5
+ * and related option types. All other utilities are internal implementation
6
+ * details consumed via direct imports within the package.
7
+ */
8
+
9
+ export { rango } from "./rango.js";
10
+ export { poke } from "./plugins/refresh-cmd.js";
11
+
12
+ export type {
13
+ RangoNodeOptions,
14
+ RangoCloudflareOptions,
15
+ RangoVercelOptions,
16
+ VercelPresetOptions,
17
+ RangoOptions,
18
+ ClientChunks,
19
+ ClientChunkMeta,
20
+ BuildEnvOption,
21
+ BuildEnvFactory,
22
+ BuildEnvFactoryContext,
23
+ BuildEnvResult,
24
+ } from "./plugin-types.js";