@rangojs/router 0.0.0-experimental.20 → 0.0.0-experimental.204030a9

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 (293) hide show
  1. package/AGENTS.md +4 -0
  2. package/README.md +242 -55
  3. package/dist/bin/rango.js +277 -99
  4. package/dist/vite/index.js +2929 -1132
  5. package/dist/vite/index.js.bak +5448 -0
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +68 -21
  8. package/skills/breadcrumbs/SKILL.md +252 -0
  9. package/skills/bundle-analysis/SKILL.md +159 -0
  10. package/skills/cache-guide/SKILL.md +243 -21
  11. package/skills/caching/SKILL.md +159 -10
  12. package/skills/composability/SKILL.md +27 -2
  13. package/skills/document-cache/SKILL.md +78 -55
  14. package/skills/handler-use/SKILL.md +364 -0
  15. package/skills/hooks/SKILL.md +262 -51
  16. package/skills/host-router/SKILL.md +243 -0
  17. package/skills/i18n/SKILL.md +276 -0
  18. package/skills/intercept/SKILL.md +46 -4
  19. package/skills/layout/SKILL.md +28 -7
  20. package/skills/links/SKILL.md +249 -17
  21. package/skills/loader/SKILL.md +291 -31
  22. package/skills/middleware/SKILL.md +49 -12
  23. package/skills/migrate-nextjs/SKILL.md +562 -0
  24. package/skills/migrate-react-router/SKILL.md +769 -0
  25. package/skills/mime-routes/SKILL.md +27 -0
  26. package/skills/observability/SKILL.md +137 -0
  27. package/skills/parallel/SKILL.md +197 -6
  28. package/skills/prerender/SKILL.md +125 -102
  29. package/skills/rango/SKILL.md +242 -23
  30. package/skills/react-compiler/SKILL.md +168 -0
  31. package/skills/response-routes/SKILL.md +66 -9
  32. package/skills/route/SKILL.md +91 -8
  33. package/skills/router-setup/SKILL.md +98 -8
  34. package/skills/server-actions/SKILL.md +751 -0
  35. package/skills/streams-and-websockets/SKILL.md +283 -0
  36. package/skills/testing/SKILL.md +511 -188
  37. package/skills/typesafety/SKILL.md +354 -50
  38. package/skills/use-cache/SKILL.md +34 -5
  39. package/skills/view-transitions/SKILL.md +294 -0
  40. package/src/__augment-tests__/augment.ts +81 -0
  41. package/src/__augment-tests__/augmented.check.ts +117 -0
  42. package/src/__internal.ts +92 -0
  43. package/src/browser/action-coordinator.ts +53 -36
  44. package/src/browser/app-shell.ts +52 -0
  45. package/src/browser/app-version.ts +14 -0
  46. package/src/browser/event-controller.ts +91 -70
  47. package/src/browser/history-state.ts +21 -0
  48. package/src/browser/index.ts +3 -3
  49. package/src/browser/link-interceptor.ts +4 -0
  50. package/src/browser/navigation-bridge.ts +183 -18
  51. package/src/browser/navigation-client.ts +187 -57
  52. package/src/browser/navigation-store.ts +75 -17
  53. package/src/browser/navigation-transaction.ts +21 -37
  54. package/src/browser/partial-update.ts +143 -40
  55. package/src/browser/prefetch/cache.ts +275 -28
  56. package/src/browser/prefetch/fetch.ts +191 -46
  57. package/src/browser/prefetch/policy.ts +6 -0
  58. package/src/browser/prefetch/queue.ts +123 -20
  59. package/src/browser/prefetch/resource-ready.ts +77 -0
  60. package/src/browser/rango-state.ts +53 -13
  61. package/src/browser/react/Link.tsx +98 -14
  62. package/src/browser/react/NavigationProvider.tsx +110 -33
  63. package/src/browser/react/context.ts +7 -2
  64. package/src/browser/react/filter-segment-order.ts +51 -7
  65. package/src/browser/react/index.ts +3 -0
  66. package/src/browser/react/location-state-shared.ts +175 -4
  67. package/src/browser/react/location-state.ts +39 -13
  68. package/src/browser/react/use-handle.ts +23 -64
  69. package/src/browser/react/use-navigation.ts +22 -2
  70. package/src/browser/react/use-params.ts +20 -8
  71. package/src/browser/react/use-reverse.ts +106 -0
  72. package/src/browser/react/use-router.ts +43 -10
  73. package/src/browser/react/use-segments.ts +11 -8
  74. package/src/browser/response-adapter.ts +25 -0
  75. package/src/browser/rsc-router.tsx +200 -75
  76. package/src/browser/scroll-restoration.ts +46 -39
  77. package/src/browser/segment-reconciler.ts +36 -9
  78. package/src/browser/segment-structure-assert.ts +2 -2
  79. package/src/browser/server-action-bridge.ts +31 -36
  80. package/src/browser/types.ts +81 -5
  81. package/src/build/collect-fallback-refs.ts +107 -0
  82. package/src/build/generate-manifest.ts +65 -40
  83. package/src/build/generate-route-types.ts +5 -0
  84. package/src/build/index.ts +2 -0
  85. package/src/build/route-trie.ts +69 -26
  86. package/src/build/route-types/codegen.ts +4 -4
  87. package/src/build/route-types/include-resolution.ts +9 -2
  88. package/src/build/route-types/per-module-writer.ts +7 -4
  89. package/src/build/route-types/router-processing.ts +278 -88
  90. package/src/build/route-types/scan-filter.ts +9 -2
  91. package/src/build/route-types/source-scan.ts +118 -0
  92. package/src/build/runtime-discovery.ts +9 -20
  93. package/src/cache/cache-runtime.ts +15 -11
  94. package/src/cache/cache-scope.ts +76 -49
  95. package/src/cache/cf/cf-cache-store.ts +501 -18
  96. package/src/cache/cf/index.ts +5 -1
  97. package/src/cache/document-cache.ts +17 -7
  98. package/src/cache/index.ts +1 -0
  99. package/src/cache/taint.ts +55 -0
  100. package/src/client.rsc.tsx +5 -1
  101. package/src/client.tsx +95 -284
  102. package/src/context-var.ts +72 -2
  103. package/src/debug.ts +2 -2
  104. package/src/decode-loader-results.ts +36 -0
  105. package/src/errors.ts +30 -1
  106. package/src/handle.ts +65 -12
  107. package/src/handles/breadcrumbs.ts +66 -0
  108. package/src/handles/index.ts +1 -0
  109. package/src/host/index.ts +2 -5
  110. package/src/host/router.ts +129 -57
  111. package/src/host/types.ts +31 -2
  112. package/src/host/utils.ts +1 -1
  113. package/src/href-client.ts +140 -20
  114. package/src/index.rsc.ts +15 -40
  115. package/src/index.ts +92 -76
  116. package/src/loader-store.ts +500 -0
  117. package/src/loader.rsc.ts +2 -5
  118. package/src/loader.ts +3 -10
  119. package/src/missing-id-error.ts +68 -0
  120. package/src/outlet-context.ts +1 -1
  121. package/src/prerender/store.ts +57 -15
  122. package/src/prerender.ts +141 -80
  123. package/src/response-utils.ts +37 -0
  124. package/src/reverse.ts +65 -15
  125. package/src/route-content-wrapper.tsx +6 -28
  126. package/src/route-definition/dsl-helpers.ts +435 -260
  127. package/src/route-definition/helper-factories.ts +29 -139
  128. package/src/route-definition/helpers-types.ts +110 -34
  129. package/src/route-definition/index.ts +3 -3
  130. package/src/route-definition/redirect.ts +11 -3
  131. package/src/route-definition/resolve-handler-use.ts +155 -0
  132. package/src/route-definition/use-item-types.ts +32 -0
  133. package/src/route-map-builder.ts +7 -1
  134. package/src/route-types.ts +37 -41
  135. package/src/router/basename.ts +14 -0
  136. package/src/router/content-negotiation.ts +113 -1
  137. package/src/router/error-handling.ts +1 -1
  138. package/src/router/find-match.ts +4 -2
  139. package/src/router/handler-context.ts +105 -39
  140. package/src/router/intercept-resolution.ts +15 -22
  141. package/src/router/lazy-includes.ts +12 -9
  142. package/src/router/loader-resolution.ts +175 -23
  143. package/src/router/logging.ts +5 -2
  144. package/src/router/manifest.ts +31 -16
  145. package/src/router/match-api.ts +129 -193
  146. package/src/router/match-handlers.ts +63 -20
  147. package/src/router/match-middleware/background-revalidation.ts +30 -2
  148. package/src/router/match-middleware/cache-lookup.ts +136 -106
  149. package/src/router/match-middleware/cache-store.ts +54 -10
  150. package/src/router/match-middleware/intercept-resolution.ts +9 -7
  151. package/src/router/match-middleware/segment-resolution.ts +61 -5
  152. package/src/router/match-result.ts +124 -18
  153. package/src/router/metrics.ts +239 -14
  154. package/src/router/middleware-types.ts +61 -31
  155. package/src/router/middleware.ts +226 -124
  156. package/src/router/navigation-snapshot.ts +182 -0
  157. package/src/router/pattern-matching.ts +118 -19
  158. package/src/router/prerender-match.ts +114 -10
  159. package/src/router/preview-match.ts +32 -102
  160. package/src/router/request-classification.ts +286 -0
  161. package/src/router/revalidation.ts +85 -9
  162. package/src/router/route-snapshot.ts +245 -0
  163. package/src/router/router-context.ts +6 -1
  164. package/src/router/router-interfaces.ts +91 -29
  165. package/src/router/router-options.ts +89 -19
  166. package/src/router/router-registry.ts +2 -5
  167. package/src/router/segment-resolution/fresh.ts +240 -23
  168. package/src/router/segment-resolution/helpers.ts +30 -25
  169. package/src/router/segment-resolution/loader-cache.ts +1 -0
  170. package/src/router/segment-resolution/revalidation.ts +483 -289
  171. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  172. package/src/router/segment-wrappers.ts +2 -0
  173. package/src/router/substitute-pattern-params.ts +56 -0
  174. package/src/router/telemetry.ts +99 -0
  175. package/src/router/trie-matching.ts +38 -15
  176. package/src/router/types.ts +9 -0
  177. package/src/router/url-params.ts +49 -0
  178. package/src/router.ts +120 -32
  179. package/src/rsc/handler-context.ts +2 -2
  180. package/src/rsc/handler.ts +524 -370
  181. package/src/rsc/helpers.ts +91 -43
  182. package/src/rsc/index.ts +1 -21
  183. package/src/rsc/loader-fetch.ts +23 -3
  184. package/src/rsc/manifest-init.ts +5 -1
  185. package/src/rsc/origin-guard.ts +28 -10
  186. package/src/rsc/progressive-enhancement.ts +39 -10
  187. package/src/rsc/response-route-handler.ts +46 -53
  188. package/src/rsc/rsc-rendering.ts +69 -89
  189. package/src/rsc/runtime-warnings.ts +9 -10
  190. package/src/rsc/server-action.ts +39 -47
  191. package/src/rsc/ssr-setup.ts +144 -0
  192. package/src/rsc/types.ts +19 -3
  193. package/src/search-params.ts +20 -17
  194. package/src/segment-content-promise.ts +67 -0
  195. package/src/segment-loader-promise.ts +122 -0
  196. package/src/segment-system.tsx +219 -67
  197. package/src/serialize.ts +243 -0
  198. package/src/server/context.ts +285 -63
  199. package/src/server/cookie-store.ts +28 -4
  200. package/src/server/handle-store.ts +19 -0
  201. package/src/server/loader-registry.ts +9 -8
  202. package/src/server/request-context.ts +228 -65
  203. package/src/server.ts +6 -0
  204. package/src/ssr/index.tsx +9 -1
  205. package/src/static-handler.ts +19 -7
  206. package/src/testing/cache-status.ts +166 -0
  207. package/src/testing/collect-handle.ts +63 -0
  208. package/src/testing/dispatch.ts +440 -0
  209. package/src/testing/dom.entry.ts +22 -0
  210. package/src/testing/e2e/fixture.ts +154 -0
  211. package/src/testing/e2e/index.ts +149 -0
  212. package/src/testing/e2e/matchers.ts +51 -0
  213. package/src/testing/e2e/page-helpers.ts +272 -0
  214. package/src/testing/e2e/parity.ts +306 -0
  215. package/src/testing/e2e/server.ts +183 -0
  216. package/src/testing/flight-matchers.ts +104 -0
  217. package/src/testing/flight-runtime.d.ts +21 -0
  218. package/src/testing/flight.entry.ts +22 -0
  219. package/src/testing/flight.ts +182 -0
  220. package/src/testing/generated-routes.ts +223 -0
  221. package/src/testing/index.ts +98 -0
  222. package/src/testing/internal/context.ts +151 -0
  223. package/src/testing/render-route.tsx +536 -0
  224. package/src/testing/run-loader.ts +296 -0
  225. package/src/testing/run-middleware.ts +170 -0
  226. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  227. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  228. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  229. package/src/testing/vitest-stubs/version.ts +5 -0
  230. package/src/testing/vitest.ts +112 -0
  231. package/src/theme/index.ts +4 -13
  232. package/src/types/cache-types.ts +4 -4
  233. package/src/types/global-namespace.ts +39 -26
  234. package/src/types/handler-context.ts +197 -79
  235. package/src/types/index.ts +1 -0
  236. package/src/types/loader-types.ts +41 -15
  237. package/src/types/request-scope.ts +126 -0
  238. package/src/types/route-config.ts +17 -8
  239. package/src/types/route-entry.ts +19 -1
  240. package/src/types/segments.ts +37 -6
  241. package/src/urls/include-helper.ts +34 -67
  242. package/src/urls/index.ts +0 -3
  243. package/src/urls/path-helper-types.ts +50 -9
  244. package/src/urls/path-helper.ts +63 -63
  245. package/src/urls/pattern-types.ts +48 -19
  246. package/src/urls/response-types.ts +25 -22
  247. package/src/urls/type-extraction.ts +26 -116
  248. package/src/urls/urls-function.ts +1 -5
  249. package/src/use-loader.tsx +487 -44
  250. package/src/vite/debug.ts +185 -0
  251. package/src/vite/discovery/bundle-postprocess.ts +63 -91
  252. package/src/vite/discovery/discover-routers.ts +106 -53
  253. package/src/vite/discovery/discovery-errors.ts +194 -0
  254. package/src/vite/discovery/gate-state.ts +171 -0
  255. package/src/vite/discovery/prerender-collection.ts +222 -107
  256. package/src/vite/discovery/route-types-writer.ts +40 -84
  257. package/src/vite/discovery/self-gen-tracking.ts +27 -1
  258. package/src/vite/discovery/state.ts +50 -13
  259. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  260. package/src/vite/index.ts +10 -3
  261. package/src/vite/plugin-types.ts +111 -72
  262. package/src/vite/plugins/cjs-to-esm.ts +8 -7
  263. package/src/vite/plugins/client-ref-dedup.ts +16 -0
  264. package/src/vite/plugins/client-ref-hashing.ts +28 -5
  265. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  266. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  267. package/src/vite/plugins/cloudflare-protocol-stub.ts +214 -0
  268. package/src/vite/plugins/expose-action-id.ts +55 -33
  269. package/src/vite/plugins/expose-id-utils.ts +24 -8
  270. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  271. package/src/vite/plugins/expose-ids/handler-transform.ts +12 -35
  272. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  273. package/src/vite/plugins/expose-ids/router-transform.ts +20 -3
  274. package/src/vite/plugins/expose-internal-ids.ts +544 -317
  275. package/src/vite/plugins/performance-tracks.ts +92 -0
  276. package/src/vite/plugins/refresh-cmd.ts +127 -0
  277. package/src/vite/plugins/use-cache-transform.ts +65 -50
  278. package/src/vite/plugins/version-injector.ts +39 -23
  279. package/src/vite/plugins/version-plugin.ts +72 -3
  280. package/src/vite/plugins/virtual-entries.ts +2 -2
  281. package/src/vite/rango.ts +265 -226
  282. package/src/vite/router-discovery.ts +924 -137
  283. package/src/vite/utils/ast-handler-extract.ts +15 -15
  284. package/src/vite/utils/banner.ts +4 -4
  285. package/src/vite/utils/bundle-analysis.ts +4 -2
  286. package/src/vite/utils/client-chunks.ts +190 -0
  287. package/src/vite/utils/forward-user-plugins.ts +193 -0
  288. package/src/vite/utils/manifest-utils.ts +21 -5
  289. package/src/vite/utils/package-resolution.ts +41 -1
  290. package/src/vite/utils/prerender-utils.ts +98 -5
  291. package/src/vite/utils/shared-utils.ts +109 -27
  292. package/src/browser/action-response-classifier.ts +0 -99
  293. package/src/route-definition/route-function.ts +0 -119
@@ -5,13 +5,15 @@
5
5
  * from discovered router manifests and static source parsing.
6
6
  */
7
7
 
8
- import { dirname, basename, join, resolve } from "node:path";
8
+ import { dirname, join, resolve } from "node:path";
9
9
  import { readFileSync, writeFileSync, existsSync, unlinkSync } from "node:fs";
10
10
  import {
11
11
  generateRouteTypesSource,
12
12
  writeCombinedRouteTypes,
13
13
  findRouterFiles,
14
14
  buildCombinedRouteMapForRouterFile,
15
+ genFileTsPath,
16
+ resolveSearchSchemas,
15
17
  } from "../../build/generate-route-types.js";
16
18
  import type { DiscoveryState } from "./state.js";
17
19
  import { markSelfGenWrite } from "./self-gen-tracking.js";
@@ -35,6 +37,22 @@ function filterUserNamedRoutes(
35
37
  return filtered;
36
38
  }
37
39
 
40
+ // Write a gen file only when content changed, marking the write as
41
+ // self-generated BEFORE writeFileSync so the watcher distinguishes it from a
42
+ // manual edit (the HMR self-gen-loop guard).
43
+ function writeGenFileIfChanged(
44
+ state: DiscoveryState,
45
+ outPath: string,
46
+ source: string,
47
+ opts?: { log?: boolean },
48
+ ): void {
49
+ const existing = existsSync(outPath) ? readFileSync(outPath, "utf-8") : null;
50
+ if (existing === source) return;
51
+ markSelfGenWrite(state, outPath, source);
52
+ writeFileSync(outPath, source);
53
+ if (opts?.log) console.log(`[rango] Generated route types -> ${outPath}`);
54
+ }
55
+
38
56
  /**
39
57
  * Write combined route types for all router files.
40
58
  * Only writes when content has changed to avoid triggering HMR loops.
@@ -48,45 +66,16 @@ export function writeCombinedRouteTypesWithTracking(
48
66
  findRouterFiles(state.projectRoot, state.scanFilter);
49
67
  state.cachedRouterFiles = routerFiles;
50
68
 
51
- // Snapshot pre-write content to detect which files actually change.
52
- const preContent = new Map<string, string>();
53
- for (const routerFilePath of routerFiles) {
54
- const routerDir = dirname(routerFilePath);
55
- const routerBasename = basename(routerFilePath).replace(
56
- /\.(tsx?|jsx?)$/,
57
- "",
58
- );
59
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
60
- try {
61
- preContent.set(outPath, readFileSync(outPath, "utf-8"));
62
- } catch {
63
- // File doesn't exist yet — any write is a real change.
64
- }
65
- }
66
-
67
- writeCombinedRouteTypes(state.projectRoot, routerFiles, opts);
68
-
69
- // Mark only files that were actually written so the watcher can
70
- // distinguish self-triggered change events from manual edits.
71
- // Marking unchanged files creates stale entries that interfere with
72
- // multi-server setups (e.g. shared webServer + isolated HMR server).
73
- for (const routerFilePath of routerFiles) {
74
- const routerDir = dirname(routerFilePath);
75
- const routerBasename = basename(routerFilePath).replace(
76
- /\.(tsx?|jsx?)$/,
77
- "",
78
- );
79
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
80
- if (!existsSync(outPath)) continue;
81
- try {
82
- const content = readFileSync(outPath, "utf-8");
83
- if (content !== preContent.get(outPath)) {
84
- markSelfGenWrite(state, outPath, content);
85
- }
86
- } catch {
87
- // Ignore transient fs errors while files are being rewritten.
88
- }
89
- }
69
+ // Mark each gen file as self-generated BEFORE it is written, via the onWrite
70
+ // callback fired at every writeFileSync site, so the watcher distinguishes
71
+ // self-triggered change events from manual edits. The callback fires only
72
+ // for files actually written, so unchanged files are never marked (stale
73
+ // entries interfere with multi-server setups such as a shared webServer plus
74
+ // an isolated HMR server).
75
+ writeCombinedRouteTypes(state.projectRoot, routerFiles, {
76
+ ...opts,
77
+ onWrite: (outPath, content) => markSelfGenWrite(state, outPath, content),
78
+ });
90
79
  }
91
80
 
92
81
  /**
@@ -104,7 +93,7 @@ export function writeRouteTypesFiles(state: DiscoveryState): void {
104
93
  if (existsSync(oldCombinedPath)) {
105
94
  unlinkSync(oldCombinedPath);
106
95
  console.log(
107
- `[rsc-router] Removed stale combined route types: ${oldCombinedPath}`,
96
+ `[rango] Removed stale combined route types: ${oldCombinedPath}`,
108
97
  );
109
98
  }
110
99
  } catch {}
@@ -122,40 +111,22 @@ export function writeRouteTypesFiles(state: DiscoveryState): void {
122
111
  // the wrong location, causing non-deterministic type resolution.
123
112
  if (sourceFile.includes("node_modules")) {
124
113
  throw new Error(
125
- `[rsc-router] Router "${id}" has sourceFile inside node_modules: ${sourceFile}\n` +
114
+ `[rango] Router "${id}" has sourceFile inside node_modules: ${sourceFile}\n` +
126
115
  `This means createRouter() stack trace parsing matched a Vite internal frame.\n` +
127
116
  `Set an explicit \`id\` on createRouter() or check the call site.`,
128
117
  );
129
118
  }
130
119
 
131
- const routerDir = dirname(sourceFile);
132
- const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
133
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
120
+ const outPath = genFileTsPath(sourceFile);
134
121
 
135
122
  // Filter out auto-generated route names (e.g. "$path____debug_reverse-test")
136
123
  // to match the static parser's output and prevent HMR oscillation.
137
124
  const userRoutes = filterUserNamedRoutes(routeManifest);
138
- let effectiveSearchSchemas = routeSearchSchemas;
139
-
140
- // Runtime manifest may omit search schema metadata in some module-runner
141
- // flows. Fall back to static source parsing from the router file.
142
- if (
143
- (!effectiveSearchSchemas ||
144
- Object.keys(effectiveSearchSchemas).length === 0) &&
145
- sourceFile
146
- ) {
147
- const staticParsed = buildCombinedRouteMapForRouterFile(sourceFile);
148
- if (Object.keys(staticParsed.searchSchemas).length > 0) {
149
- const filtered: Record<string, Record<string, string>> = {};
150
- for (const name of Object.keys(userRoutes)) {
151
- const schema = staticParsed.searchSchemas[name];
152
- if (schema) filtered[name] = schema;
153
- }
154
- if (Object.keys(filtered).length > 0) {
155
- effectiveSearchSchemas = filtered;
156
- }
157
- }
158
- }
125
+ const effectiveSearchSchemas = resolveSearchSchemas(
126
+ Object.keys(userRoutes),
127
+ routeSearchSchemas,
128
+ sourceFile,
129
+ );
159
130
 
160
131
  const source = generateRouteTypesSource(
161
132
  userRoutes,
@@ -163,14 +134,7 @@ export function writeRouteTypesFiles(state: DiscoveryState): void {
163
134
  ? effectiveSearchSchemas
164
135
  : undefined,
165
136
  );
166
- const existing = existsSync(outPath)
167
- ? readFileSync(outPath, "utf-8")
168
- : null;
169
- if (existing !== source) {
170
- markSelfGenWrite(state, outPath, source);
171
- writeFileSync(outPath, source);
172
- console.log(`[rsc-router] Generated route types -> ${outPath}`);
173
- }
137
+ writeGenFileIfChanged(state, outPath, source, { log: true });
174
138
  }
175
139
  }
176
140
 
@@ -236,22 +200,14 @@ export function supplementGenFilesWithRuntimeRoutes(
236
200
  }
237
201
  }
238
202
 
239
- const routerDir = dirname(sourceFile);
240
- const routerBasename = basename(sourceFile).replace(/\.(tsx?|jsx?)$/, "");
241
- const outPath = join(routerDir, `${routerBasename}.named-routes.gen.ts`);
203
+ const outPath = genFileTsPath(sourceFile);
242
204
  const source = generateRouteTypesSource(
243
205
  mergedRoutes,
244
206
  Object.keys(mergedSearchSchemas).length > 0
245
207
  ? mergedSearchSchemas
246
208
  : undefined,
247
209
  );
248
- const existing = existsSync(outPath)
249
- ? readFileSync(outPath, "utf-8")
250
- : null;
251
- if (existing !== source) {
252
- markSelfGenWrite(state, outPath, source);
253
- writeFileSync(outPath, source);
254
- }
210
+ writeGenFileIfChanged(state, outPath, source);
255
211
  }
256
212
  // No manual manifest update needed: the virtual module imports the gen
257
213
  // file, so Vite's HMR automatically re-evaluates it with fresh data.
@@ -22,6 +22,32 @@ export function markSelfGenWrite(
22
22
  export function consumeSelfGenWrite(
23
23
  state: DiscoveryState,
24
24
  filePath: string,
25
+ ): boolean {
26
+ return checkSelfGenWrite(state, filePath, true);
27
+ }
28
+
29
+ /**
30
+ * Non-consuming variant. Used by the `handleHotUpdate` plugin hook to
31
+ * suppress vite's HMR cascade for our own gen-file writes WITHOUT
32
+ * consuming the entry — `consumeSelfGenWrite` (called later from the
33
+ * chokidar `change` handler in `handleRouteFileChange`) still needs to
34
+ * see and consume the same entry to short-circuit our regen path.
35
+ *
36
+ * Both hooks fire for the same file change event:
37
+ * - `handleHotUpdate` runs first (vite's HMR pipeline).
38
+ * - chokidar `change` callback runs after (filesystem watcher).
39
+ */
40
+ export function peekSelfGenWrite(
41
+ state: DiscoveryState,
42
+ filePath: string,
43
+ ): boolean {
44
+ return checkSelfGenWrite(state, filePath, false);
45
+ }
46
+
47
+ function checkSelfGenWrite(
48
+ state: DiscoveryState,
49
+ filePath: string,
50
+ consume: boolean,
25
51
  ): boolean {
26
52
  const info = state.selfWrittenGenFiles.get(filePath);
27
53
  if (!info) return false;
@@ -33,7 +59,7 @@ export function consumeSelfGenWrite(
33
59
  const current = readFileSync(filePath, "utf-8");
34
60
  const currentHash = createHash("sha256").update(current).digest("hex");
35
61
  if (currentHash === info.hash) {
36
- state.selfWrittenGenFiles.delete(filePath);
62
+ if (consume) state.selfWrittenGenFiles.delete(filePath);
37
63
  return true;
38
64
  }
39
65
  // Hash mismatch: file was changed externally. Keep the entry so a
@@ -13,11 +13,20 @@ export const VIRTUAL_ROUTES_MANIFEST_ID = "virtual:rsc-router/routes-manifest";
13
13
  export interface PluginOptions {
14
14
  enableBuildPrerender?: boolean;
15
15
  staticRouteTypesGeneration?: boolean;
16
- include?: string[];
17
- exclude?: string[];
18
16
  // Mutable ref for deferred auto-discovery (node preset).
19
17
  // The auto-discover config() hook populates this before configResolved.
20
18
  routerPathRef?: { path?: string };
19
+ /** Build-time env option from rango() config. */
20
+ buildEnv?: import("../plugin-types.js").BuildEnvOption;
21
+ /** Deployment preset (needed for buildEnv "auto" resolution). */
22
+ preset?: "node" | "cloudflare";
23
+ /**
24
+ * Shared context the built-in clientChunks strategy reads. Discovery populates
25
+ * it (registered fallback hashes + single-router name) before the client build
26
+ * invokes the strategy. Present only when the built-in strategy is active
27
+ * (`clientChunks: true`/default); undefined for `false` or a custom function.
28
+ */
29
+ clientChunkCtx?: import("../utils/client-chunks.js").ClientChunkContext;
21
30
  }
22
31
 
23
32
  export interface PrecomputedEntry {
@@ -43,6 +52,21 @@ export interface DiscoveryState {
43
52
  projectRoot: string;
44
53
  isBuildMode: boolean;
45
54
  userResolveAlias: any;
55
+ /**
56
+ * Data-only slice of the user's resolved config (resolve.* incl. native
57
+ * tsconfigPaths, define, oxc) mirrored into the discovery temp server so it
58
+ * resolves and transforms modules the same way the real environment does.
59
+ * See `utils/forward-user-plugins.ts`.
60
+ */
61
+ userRunnerConfig:
62
+ | import("../utils/forward-user-plugins.js").ForwardedRunnerConfig
63
+ | undefined;
64
+ /**
65
+ * User resolution plugins (resolveId/load), stripped to their resolution
66
+ * surface, forwarded into the discovery temp server. Lets third-party
67
+ * resolvers such as vite-tsconfig-paths participate in discovery.
68
+ */
69
+ userResolvePlugins: import("vite").Plugin[];
46
70
  scanFilter: ScanFilter | undefined;
47
71
  cachedRouterFiles: string[] | undefined;
48
72
  opts: PluginOptions | undefined;
@@ -56,13 +80,10 @@ export interface DiscoveryState {
56
80
  perRouterPrecomputedMap: Map<string, PrecomputedEntry[]>;
57
81
  perRouterManifestDataMap: Map<string, Record<string, string>>;
58
82
 
59
- prerenderCollectedData: Record<string, any> | null;
60
- staticCollectedData: Record<
61
- string,
62
- { encoded: string; handles: Record<string, unknown[]> }
63
- > | null;
64
- handlerChunkInfo: ChunkInfo | null;
65
- staticHandlerChunkInfo: ChunkInfo | null;
83
+ prerenderManifestEntries: Record<string, string> | null;
84
+ staticManifestEntries: Record<string, string> | null;
85
+ handlerChunkInfoMap: Map<string, ChunkInfo>;
86
+ staticHandlerChunkInfoMap: Map<string, ChunkInfo>;
66
87
  rscEntryFileName: string | null;
67
88
  resolvedPrerenderModules: Map<string, string[]> | undefined;
68
89
  resolvedStaticModules: Map<string, string[]> | undefined;
@@ -72,6 +93,19 @@ export interface DiscoveryState {
72
93
  devServer: any;
73
94
  selfWrittenGenFiles: Map<string, { at: number; hash: string }>;
74
95
  SELF_WRITE_WINDOW_MS: number;
96
+
97
+ /** Resolved build-time env bindings (set during buildStart/configureServer). */
98
+ resolvedBuildEnv?: Record<string, unknown>;
99
+ /** Cleanup function for build-time env resources (e.g., miniflare). */
100
+ buildEnvDispose?: (() => Promise<void> | void) | null;
101
+
102
+ /**
103
+ * Set when the most recent HMR re-discovery threw. Cleared on the next
104
+ * successful discovery. Surfaced via debug logs so we can detect "manifest
105
+ * frozen at last-good after error → user fix in non-route file → no
106
+ * rediscovery trigger" scenarios.
107
+ */
108
+ lastDiscoveryError?: { message: string; at: number } | null;
75
109
  }
76
110
 
77
111
  export function createDiscoveryState(
@@ -83,6 +117,8 @@ export function createDiscoveryState(
83
117
  projectRoot: "",
84
118
  isBuildMode: false,
85
119
  userResolveAlias: undefined,
120
+ userRunnerConfig: undefined,
121
+ userResolvePlugins: [],
86
122
  scanFilter: undefined,
87
123
  cachedRouterFiles: undefined,
88
124
  opts,
@@ -96,10 +132,10 @@ export function createDiscoveryState(
96
132
  perRouterPrecomputedMap: new Map(),
97
133
  perRouterManifestDataMap: new Map(),
98
134
 
99
- prerenderCollectedData: null,
100
- staticCollectedData: null,
101
- handlerChunkInfo: null,
102
- staticHandlerChunkInfo: null,
135
+ prerenderManifestEntries: null,
136
+ staticManifestEntries: null,
137
+ handlerChunkInfoMap: new Map(),
138
+ staticHandlerChunkInfoMap: new Map(),
103
139
  rscEntryFileName: null,
104
140
  resolvedPrerenderModules: undefined,
105
141
  resolvedStaticModules: undefined,
@@ -109,5 +145,6 @@ export function createDiscoveryState(
109
145
  devServer: null,
110
146
  selfWrittenGenFiles: new Map(),
111
147
  SELF_WRITE_WINDOW_MS: 5_000,
148
+ lastDiscoveryError: null,
112
149
  };
113
150
  }
@@ -58,7 +58,7 @@ export function generateRoutesManifestModule(state: DiscoveryState): string {
58
58
  }
59
59
 
60
60
  const lines = [
61
- `import { setCachedManifest, setPrecomputedEntries, setRouteTrie, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
61
+ `import { setCachedManifest, setRouterManifest, registerRouterManifestLoader, clearAllRouterData } from "@rangojs/router/server";`,
62
62
  ...genFileImports,
63
63
  // Clear stale per-router cached data (manifest, trie, precomputed entries)
64
64
  // before re-populating. In Cloudflare dev mode, program reloads re-evaluate
@@ -101,28 +101,18 @@ export function generateRoutesManifestModule(state: DiscoveryState): string {
101
101
  }
102
102
  }
103
103
 
104
- // In dev mode, skip trie and precomputed entries injection. These are
105
- // computed once during initial discovery and become stale after route
106
- // changes. A stale trie would incorrectly match removed routes. The
107
- // handler falls back to Phase 2 regex matching against the live
108
- // router.urlpatterns, which is always correct after a program reload.
109
- // In build mode, the trie is always fresh (built from the final route
110
- // tree) so it's safe to inject.
111
- if (state.isBuildMode) {
112
- if (
113
- state.mergedPrecomputedEntries &&
114
- state.mergedPrecomputedEntries.length > 0
115
- ) {
116
- lines.push(
117
- `setPrecomputedEntries(${jsonParseExpression(state.mergedPrecomputedEntries)});`,
118
- );
119
- }
120
- if (state.mergedRouteTrie) {
121
- lines.push(
122
- `setRouteTrie(${jsonParseExpression(state.mergedRouteTrie)});`,
123
- );
124
- }
125
- }
104
+ // Per-router trie and precomputedEntries are NOT inlined eagerly.
105
+ // They live in the per-router lazy chunks (generatePerRouterModule) and
106
+ // are loaded via ensureRouterManifest(routerId), which is awaited before
107
+ // every request in router.fetch() and before findMatch is reached.
108
+ // Inlining the merged versions here would duplicate the per-router data
109
+ // (the merged trie/precomputedEntries equal the per-router data for
110
+ // single-router apps; for multi-router, the merged trie is dead code
111
+ // because find-match.ts only consumes per-router tries).
112
+ //
113
+ // In dev mode, the handler also falls back to Phase 2 regex matching
114
+ // against live router.urlpatterns, which is always correct after a
115
+ // program reload.
126
116
 
127
117
  // Register lazy loaders for per-router manifest modules.
128
118
  // Each import() uses a static string literal so Rollup creates separate chunks.
package/src/vite/index.ts CHANGED
@@ -1,15 +1,22 @@
1
1
  /**
2
2
  * Public API for @rangojs/router/vite
3
3
  *
4
- * Only the rango() plugin factory and its option types are part of the
5
- * public API. All other utilities are internal implementation details
6
- * consumed via direct imports within the package.
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
7
  */
8
8
 
9
9
  export { rango } from "./rango.js";
10
+ export { poke } from "./plugins/refresh-cmd.js";
10
11
 
11
12
  export type {
12
13
  RangoNodeOptions,
13
14
  RangoCloudflareOptions,
14
15
  RangoOptions,
16
+ ClientChunks,
17
+ ClientChunkMeta,
18
+ BuildEnvOption,
19
+ BuildEnvFactory,
20
+ BuildEnvFactoryContext,
21
+ BuildEnvResult,
15
22
  } from "./plugin-types.js";
@@ -1,39 +1,112 @@
1
+ // -- Build-time environment types -------------------------------------------
2
+
1
3
  /**
2
- * RSC plugin entry points configuration.
3
- * All entries use virtual modules by default. Specify a path to use a custom entry file.
4
+ * Context passed to a buildEnv factory function.
5
+ * Provides Vite config details for conditional env setup.
4
6
  */
5
- export interface RscEntries {
6
- /**
7
- * Path to a custom browser/client entry file.
8
- * If not specified, a default virtual entry is used.
9
- */
10
- client?: string;
7
+ export interface BuildEnvFactoryContext {
8
+ /** Vite project root directory. */
9
+ root: string;
10
+ /** Vite mode (e.g. "development", "production"). */
11
+ mode: string;
12
+ /** Vite command ("serve" for dev, "build" for production). */
13
+ command: "serve" | "build";
14
+ /** Router deployment preset. */
15
+ preset: "node" | "cloudflare";
16
+ }
11
17
 
12
- /**
13
- * Path to a custom SSR entry file.
14
- * If not specified, a default virtual entry is used.
15
- */
16
- ssr?: string;
18
+ /**
19
+ * Factory function that creates build-time environment bindings.
20
+ * Called once at plugin startup. Return `dispose` to clean up resources.
21
+ */
22
+ export type BuildEnvFactory = (
23
+ ctx: BuildEnvFactoryContext,
24
+ ) => Promise<BuildEnvResult> | BuildEnvResult;
17
25
 
18
- /**
19
- * Path to a custom RSC entry file.
20
- * If not specified, a default virtual entry is used that imports the router from the `entry` option.
21
- */
22
- rsc?: string;
26
+ /**
27
+ * Result of resolving build-time environment bindings.
28
+ */
29
+ export interface BuildEnvResult {
30
+ /** Environment bindings available to Prerender/Static handlers via ctx.env. */
31
+ env: Record<string, unknown>;
32
+ /** Called after build completes to clean up resources (e.g., miniflare). */
33
+ dispose?: () => Promise<void> | void;
23
34
  }
24
35
 
25
36
  /**
26
- * Options for @vitejs/plugin-rsc integration
37
+ * Build-time environment configuration for Prerender and Static handlers.
38
+ *
39
+ * - `false` (default): no build-time env, `ctx.env` throws.
40
+ * - `"auto"`: calls `wrangler.getPlatformProxy()` (cloudflare preset only).
41
+ * - Object: used directly as `ctx.env` during build.
42
+ * - Factory: called once at startup, must return `{ env, dispose? }`.
27
43
  */
28
- export interface RscPluginOptions {
44
+ export type BuildEnvOption =
45
+ | false
46
+ | "auto"
47
+ | Record<string, unknown>
48
+ | BuildEnvFactory;
49
+
50
+ // -- Client chunking --------------------------------------------------------
51
+
52
+ /**
53
+ * Metadata for one client ("use client") module, passed to a {@link ClientChunks}
54
+ * function. Mirrors the shape `@vitejs/plugin-rsc` passes to its own
55
+ * `clientChunks` option.
56
+ */
57
+ export interface ClientChunkMeta {
58
+ /** Absolute module id of the "use client" file. */
59
+ id: string;
60
+ /** Normalized (posix) module id — convenient for path-based matching. */
61
+ normalizedId: string;
29
62
  /**
30
- * Entry points for client, ssr, and rsc environments.
31
- * All entries use virtual modules by default.
32
- * Specify paths only when you need custom entry files.
63
+ * The RSC/server chunk that statically imports this client reference. This is
64
+ * the key used for the default grouping when no override is supplied: a single
65
+ * router that statically imports every route yields ONE `serverChunk`, hence
66
+ * one client chunk for all routes.
33
67
  */
34
- entries?: RscEntries;
68
+ serverChunk: string;
35
69
  }
36
70
 
71
+ /**
72
+ * Controls how client ("use client") components are grouped into browser
73
+ * chunks, i.e. per-route / per-feature code splitting of the client bundle.
74
+ *
75
+ * Without splitting, a single router ships ONE client chunk containing every
76
+ * route's client components (and their CSS) — navigating to one route downloads
77
+ * every other route's client code. (Host sub-apps loaded via a dynamic `import()`
78
+ * are the exception: each forms its own chunk.) This option controls how that
79
+ * monolith is split.
80
+ *
81
+ * Behavior branches:
82
+ * - `true` / omitted (**default**, pre-1.0): Rango's built-in **directory
83
+ * strategy**. It splits app `"use client"` modules by **route id** — the segment
84
+ * after a route-root directory (`routes`, `app`, `pages`, `features`, `handlers`,
85
+ * …) — so `routes/dashboard/**` becomes `app-dashboard` at any nesting depth.
86
+ * Where it finds NO route structure (a flat `src/components/`, or host sub-apps
87
+ * already split by a dynamic `import()`), it inherits the default grouping
88
+ * unchanged — so the shared `src/components` chunk stays shared and host apps do
89
+ * not leak across each other. Shared runtime (React, the router, `node_modules`)
90
+ * is never split.
91
+ * - `false`: opt out — inherit `@vitejs/plugin-rsc`'s default grouping everywhere
92
+ * (one chunk per router / per host sub-app).
93
+ * - function: full override. Return a chunk group name, or `undefined` to fall
94
+ * back to the default grouping for that one module. Forwarded directly to
95
+ * `@vitejs/plugin-rsc`'s `clientChunks`.
96
+ *
97
+ * Every module maps to exactly one group, so there is no byte duplication: a
98
+ * component used by two routes lives in one group and is fetched whenever it
99
+ * renders. Put genuinely shared client components OUTSIDE route directories so
100
+ * they land in the shared group rather than one route's chunk.
101
+ *
102
+ * @default true
103
+ */
104
+ export type ClientChunks =
105
+ | boolean
106
+ | ((meta: ClientChunkMeta) => string | undefined);
107
+
108
+ // -- Plugin options ---------------------------------------------------------
109
+
37
110
  /**
38
111
  * Base options shared by all presets
39
112
  */
@@ -45,27 +118,25 @@ interface RangoBaseOptions {
45
118
  banner?: boolean;
46
119
 
47
120
  /**
48
- * Generate named-routes.gen.ts by parsing url modules at startup.
49
- * Provides type-safe Handler<"name"> and href() without executing router code.
50
- * Set to `false` to disable (run `npx rango extract-names` manually instead).
121
+ * Group client ("use client") components into browser chunks for per-route /
122
+ * per-feature code splitting. On by default (pre-1.0); pass `false` to opt out.
123
+ * See {@link ClientChunks}.
124
+ *
51
125
  * @default true
52
126
  */
53
- staticRouteTypesGeneration?: boolean;
54
-
55
- /**
56
- * Glob patterns for files to include in route type scanning.
57
- * Only files matching at least one pattern will be scanned.
58
- * Patterns are relative to the project root.
59
- * When unset, all .ts/.tsx files are scanned.
60
- */
61
- include?: string[];
127
+ clientChunks?: ClientChunks;
62
128
 
63
129
  /**
64
- * Glob patterns for files to exclude from route type scanning.
65
- * Takes precedence over `include`. Patterns are relative to the project root.
66
- * Defaults to common test/build directories.
130
+ * Environment bindings available to Prerender and Static handlers at build
131
+ * time via `ctx.env`. Applies to both production build and dev on-demand
132
+ * prerender (`/__rsc_prerender`).
133
+ *
134
+ * This is the build-time env supplied by the Vite plugin, not the live
135
+ * request env. It is shared across all prerender invocations for the build.
136
+ *
137
+ * @default false
67
138
  */
68
- exclude?: string[];
139
+ buildEnv?: BuildEnvOption;
69
140
  }
70
141
 
71
142
  /**
@@ -76,38 +147,6 @@ export interface RangoNodeOptions extends RangoBaseOptions {
76
147
  * Deployment preset. Defaults to 'node' when not specified.
77
148
  */
78
149
  preset?: "node";
79
-
80
- /**
81
- * Path to your router configuration file that exports the route tree.
82
- * This file must export a `router` object created with `createRouter()`.
83
- *
84
- * When omitted, auto-discovers the router by scanning for files containing
85
- * `createRouter`. If exactly one is found, it is used automatically.
86
- * If multiple are found, an error is thrown with the list of candidates.
87
- *
88
- * @example
89
- * ```ts
90
- * rango({ router: './src/router.tsx' })
91
- * // or simply:
92
- * rango()
93
- * ```
94
- */
95
- router?: string;
96
-
97
- /**
98
- * RSC plugin configuration. By default, rsc-router includes @vitejs/plugin-rsc
99
- * with sensible defaults.
100
- *
101
- * Entry files (browser, ssr, rsc) are optional - if they don't exist,
102
- * virtual defaults are used.
103
- *
104
- * - Omit or pass `true`/`{}` to use defaults (recommended)
105
- * - Pass `{ entries: {...} }` to customize entry paths
106
- * - Pass `false` to disable (for manual @vitejs/plugin-rsc configuration)
107
- *
108
- * @default true
109
- */
110
- rsc?: boolean | RscPluginOptions;
111
150
  }
112
151
 
113
152
  /**