@rangojs/router 0.0.0-experimental.fb4fdc18 → 0.0.0-experimental.fce7fbd1

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 (214) hide show
  1. package/README.md +9 -9
  2. package/dist/bin/rango.js +147 -57
  3. package/dist/testing/vitest.js +48 -0
  4. package/dist/vite/index.js +914 -485
  5. package/package.json +55 -11
  6. package/skills/bundle-analysis/SKILL.md +159 -0
  7. package/skills/cache-guide/SKILL.md +220 -30
  8. package/skills/caching/SKILL.md +116 -8
  9. package/skills/composability/SKILL.md +27 -2
  10. package/skills/document-cache/SKILL.md +78 -55
  11. package/skills/handler-use/SKILL.md +3 -1
  12. package/skills/hooks/SKILL.md +214 -18
  13. package/skills/host-router/SKILL.md +45 -20
  14. package/skills/intercept/SKILL.md +26 -4
  15. package/skills/layout/SKILL.md +6 -7
  16. package/skills/links/SKILL.md +173 -17
  17. package/skills/loader/SKILL.md +149 -6
  18. package/skills/middleware/SKILL.md +13 -9
  19. package/skills/migrate-nextjs/SKILL.md +1 -1
  20. package/skills/mime-routes/SKILL.md +27 -0
  21. package/skills/observability/SKILL.md +137 -0
  22. package/skills/parallel/SKILL.md +5 -6
  23. package/skills/prerender/SKILL.md +14 -33
  24. package/skills/rango/SKILL.md +242 -26
  25. package/skills/react-compiler/SKILL.md +168 -0
  26. package/skills/response-routes/SKILL.md +58 -9
  27. package/skills/route/SKILL.md +13 -4
  28. package/skills/router-setup/SKILL.md +3 -3
  29. package/skills/server-actions/SKILL.md +53 -41
  30. package/skills/testing/SKILL.md +599 -0
  31. package/skills/typesafety/SKILL.md +310 -26
  32. package/skills/use-cache/SKILL.md +34 -5
  33. package/skills/view-transitions/SKILL.md +294 -0
  34. package/src/__augment-tests__/augment.ts +81 -0
  35. package/src/__augment-tests__/augmented.check.ts +117 -0
  36. package/src/browser/action-coordinator.ts +53 -36
  37. package/src/browser/event-controller.ts +42 -66
  38. package/src/browser/history-state.ts +21 -0
  39. package/src/browser/index.ts +3 -3
  40. package/src/browser/navigation-bridge.ts +6 -6
  41. package/src/browser/navigation-client.ts +12 -15
  42. package/src/browser/navigation-store.ts +7 -8
  43. package/src/browser/navigation-transaction.ts +10 -28
  44. package/src/browser/partial-update.ts +9 -19
  45. package/src/browser/react/NavigationProvider.tsx +29 -40
  46. package/src/browser/react/index.ts +3 -0
  47. package/src/browser/react/location-state-shared.ts +175 -4
  48. package/src/browser/react/location-state.ts +39 -13
  49. package/src/browser/react/use-handle.ts +17 -9
  50. package/src/browser/react/use-params.ts +3 -4
  51. package/src/browser/react/use-reverse.ts +106 -0
  52. package/src/browser/react/use-router.ts +14 -1
  53. package/src/browser/response-adapter.ts +25 -0
  54. package/src/browser/rsc-router.tsx +30 -16
  55. package/src/browser/scroll-restoration.ts +22 -14
  56. package/src/browser/segment-structure-assert.ts +2 -2
  57. package/src/browser/server-action-bridge.ts +23 -30
  58. package/src/browser/types.ts +2 -0
  59. package/src/build/collect-fallback-refs.ts +107 -0
  60. package/src/build/generate-manifest.ts +60 -35
  61. package/src/build/generate-route-types.ts +2 -0
  62. package/src/build/index.ts +2 -0
  63. package/src/build/route-types/codegen.ts +4 -4
  64. package/src/build/route-types/include-resolution.ts +1 -1
  65. package/src/build/route-types/per-module-writer.ts +7 -4
  66. package/src/build/route-types/router-processing.ts +55 -14
  67. package/src/build/route-types/scan-filter.ts +1 -1
  68. package/src/build/route-types/source-scan.ts +118 -0
  69. package/src/build/runtime-discovery.ts +9 -20
  70. package/src/cache/cache-scope.ts +28 -42
  71. package/src/cache/cf/cf-cache-store.ts +49 -6
  72. package/src/client.rsc.tsx +3 -0
  73. package/src/client.tsx +10 -8
  74. package/src/context-var.ts +5 -5
  75. package/src/decode-loader-results.ts +36 -0
  76. package/src/errors.ts +30 -1
  77. package/src/handle.ts +26 -13
  78. package/src/host/index.ts +2 -2
  79. package/src/host/router.ts +129 -57
  80. package/src/host/types.ts +31 -2
  81. package/src/host/utils.ts +1 -1
  82. package/src/href-client.ts +140 -20
  83. package/src/index.rsc.ts +6 -4
  84. package/src/index.ts +13 -6
  85. package/src/loader-store.ts +500 -0
  86. package/src/loader.rsc.ts +2 -5
  87. package/src/loader.ts +3 -10
  88. package/src/missing-id-error.ts +68 -0
  89. package/src/prerender.ts +4 -4
  90. package/src/response-utils.ts +9 -0
  91. package/src/reverse.ts +65 -41
  92. package/src/route-content-wrapper.tsx +6 -28
  93. package/src/route-definition/dsl-helpers.ts +238 -263
  94. package/src/route-definition/helper-factories.ts +29 -139
  95. package/src/route-definition/helpers-types.ts +37 -14
  96. package/src/route-definition/use-item-types.ts +32 -0
  97. package/src/route-types.ts +19 -41
  98. package/src/router/basename.ts +14 -0
  99. package/src/router/content-negotiation.ts +15 -2
  100. package/src/router/error-handling.ts +1 -1
  101. package/src/router/handler-context.ts +4 -42
  102. package/src/router/intercept-resolution.ts +4 -18
  103. package/src/router/lazy-includes.ts +2 -2
  104. package/src/router/loader-resolution.ts +16 -2
  105. package/src/router/match-handlers.ts +62 -20
  106. package/src/router/match-middleware/cache-lookup.ts +44 -91
  107. package/src/router/match-middleware/cache-store.ts +3 -2
  108. package/src/router/match-result.ts +32 -30
  109. package/src/router/metrics.ts +1 -1
  110. package/src/router/middleware-types.ts +1 -1
  111. package/src/router/middleware.ts +46 -78
  112. package/src/router/prerender-match.ts +1 -1
  113. package/src/router/preview-match.ts +3 -1
  114. package/src/router/request-classification.ts +4 -28
  115. package/src/router/revalidation.ts +43 -1
  116. package/src/router/router-interfaces.ts +45 -28
  117. package/src/router/router-options.ts +40 -1
  118. package/src/router/router-registry.ts +2 -5
  119. package/src/router/segment-resolution/fresh.ts +19 -6
  120. package/src/router/segment-resolution/revalidation.ts +19 -6
  121. package/src/router/segment-resolution/view-transition-default.ts +36 -0
  122. package/src/router/substitute-pattern-params.ts +56 -0
  123. package/src/router/telemetry.ts +99 -0
  124. package/src/router/types.ts +8 -0
  125. package/src/router.ts +37 -21
  126. package/src/rsc/handler-context.ts +2 -2
  127. package/src/rsc/handler.ts +20 -65
  128. package/src/rsc/helpers.ts +22 -2
  129. package/src/rsc/index.ts +1 -1
  130. package/src/rsc/origin-guard.ts +28 -10
  131. package/src/rsc/response-route-handler.ts +32 -52
  132. package/src/rsc/rsc-rendering.ts +27 -53
  133. package/src/rsc/runtime-warnings.ts +9 -10
  134. package/src/rsc/server-action.ts +13 -37
  135. package/src/rsc/ssr-setup.ts +16 -0
  136. package/src/rsc/types.ts +2 -2
  137. package/src/search-params.ts +4 -4
  138. package/src/segment-system.tsx +121 -65
  139. package/src/serialize.ts +243 -0
  140. package/src/server/context.ts +118 -51
  141. package/src/server/cookie-store.ts +28 -4
  142. package/src/server/request-context.ts +10 -0
  143. package/src/static-handler.ts +1 -1
  144. package/src/testing/cache-status.ts +166 -0
  145. package/src/testing/collect-handle.ts +63 -0
  146. package/src/testing/dispatch.ts +440 -0
  147. package/src/testing/dom.entry.ts +22 -0
  148. package/src/testing/e2e/fixture.ts +154 -0
  149. package/src/testing/e2e/index.ts +149 -0
  150. package/src/testing/e2e/matchers.ts +51 -0
  151. package/src/testing/e2e/page-helpers.ts +272 -0
  152. package/src/testing/e2e/parity.ts +306 -0
  153. package/src/testing/e2e/server.ts +183 -0
  154. package/src/testing/flight-matchers.ts +104 -0
  155. package/src/testing/flight-runtime.d.ts +21 -0
  156. package/src/testing/flight.entry.ts +22 -0
  157. package/src/testing/flight.ts +182 -0
  158. package/src/testing/generated-routes.ts +223 -0
  159. package/src/testing/index.ts +105 -0
  160. package/src/testing/internal/context.ts +193 -0
  161. package/src/testing/render-route.tsx +536 -0
  162. package/src/testing/run-loader.ts +296 -0
  163. package/src/testing/run-middleware.ts +170 -0
  164. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  165. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  166. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  167. package/src/testing/vitest-stubs/version.ts +5 -0
  168. package/src/testing/vitest.ts +183 -0
  169. package/src/types/global-namespace.ts +39 -26
  170. package/src/types/handler-context.ts +56 -11
  171. package/src/types/index.ts +1 -0
  172. package/src/types/segments.ts +18 -1
  173. package/src/urls/include-helper.ts +10 -53
  174. package/src/urls/index.ts +0 -3
  175. package/src/urls/path-helper-types.ts +11 -3
  176. package/src/urls/path-helper.ts +17 -52
  177. package/src/urls/pattern-types.ts +36 -19
  178. package/src/urls/response-types.ts +20 -19
  179. package/src/urls/type-extraction.ts +26 -116
  180. package/src/urls/urls-function.ts +1 -5
  181. package/src/use-loader.tsx +413 -42
  182. package/src/vite/debug.ts +1 -0
  183. package/src/vite/discovery/bundle-postprocess.ts +6 -6
  184. package/src/vite/discovery/discover-routers.ts +70 -48
  185. package/src/vite/discovery/discovery-errors.ts +194 -0
  186. package/src/vite/discovery/prerender-collection.ts +19 -25
  187. package/src/vite/discovery/route-types-writer.ts +40 -84
  188. package/src/vite/discovery/state.ts +33 -0
  189. package/src/vite/discovery/virtual-module-codegen.ts +13 -23
  190. package/src/vite/index.ts +2 -0
  191. package/src/vite/plugin-types.ts +67 -0
  192. package/src/vite/plugins/cjs-to-esm.ts +3 -7
  193. package/src/vite/plugins/client-ref-hashing.ts +12 -1
  194. package/src/vite/plugins/cloudflare-protocol-stub.ts +1 -1
  195. package/src/vite/plugins/expose-action-id.ts +2 -2
  196. package/src/vite/plugins/expose-id-utils.ts +12 -8
  197. package/src/vite/plugins/expose-ids/export-analysis.ts +100 -20
  198. package/src/vite/plugins/expose-ids/handler-transform.ts +8 -61
  199. package/src/vite/plugins/expose-ids/loader-transform.ts +3 -5
  200. package/src/vite/plugins/expose-internal-ids.ts +47 -67
  201. package/src/vite/plugins/performance-tracks.ts +12 -16
  202. package/src/vite/plugins/use-cache-transform.ts +13 -11
  203. package/src/vite/plugins/version-injector.ts +2 -12
  204. package/src/vite/plugins/version-plugin.ts +59 -2
  205. package/src/vite/plugins/virtual-entries.ts +2 -2
  206. package/src/vite/rango.ts +67 -15
  207. package/src/vite/router-discovery.ts +208 -63
  208. package/src/vite/utils/ast-handler-extract.ts +15 -15
  209. package/src/vite/utils/bundle-analysis.ts +4 -2
  210. package/src/vite/utils/client-chunks.ts +190 -0
  211. package/src/vite/utils/forward-user-plugins.ts +193 -0
  212. package/src/vite/utils/manifest-utils.ts +21 -5
  213. package/src/vite/utils/shared-utils.ts +107 -26
  214. package/src/browser/action-response-classifier.ts +0 -99
@@ -0,0 +1,190 @@
1
+ // Resolution of the public `clientChunks` option into the callback shape that
2
+ // @vitejs/plugin-rsc expects. See plugin-types.ts (ClientChunks) and
3
+ // docs/client-chunking.md for the contract. The mechanism: a distinct returned
4
+ // name yields a distinct, dynamically-imported client chunk, independent of how
5
+ // the RSC/server build chunked the importing modules.
6
+
7
+ import type { ClientChunkMeta, ClientChunks } from "../plugin-types.js";
8
+ import { createRangoDebugger, NS } from "../debug.js";
9
+ import { hashRefKey } from "../plugins/client-ref-hashing.js";
10
+
11
+ /** The callback shape @vitejs/plugin-rsc's `clientChunks` option accepts. */
12
+ export type RscClientChunksFn = (meta: ClientChunkMeta) => string | undefined;
13
+
14
+ /**
15
+ * Build-time context the discovery pass populates and the built-in strategy
16
+ * reads. It refines how the catch-all (no route-root marker) modules are grouped
17
+ * without touching marker splits or the shared runtime:
18
+ *
19
+ * - `fallbackRefs`: production hashes of the `"use client"` modules a consumer
20
+ * registered as `errorBoundary`/`notFoundBoundary` fallbacks. Pulled into a
21
+ * dedicated `app-fallback` chunk so the error UI is not co-bundled with the
22
+ * very route code it exists to catch failures for (resilience), and so the
23
+ * chunk it would otherwise sit in gets named after a real module rather than
24
+ * the boundary. Populated by reading each fallback element's client-reference
25
+ * `$$id` during discovery (see discover-routers).
26
+ */
27
+ export interface ClientChunkContext {
28
+ fallbackRefs: Set<string>;
29
+ }
30
+
31
+ /**
32
+ * Opt-in observability for the built-in strategy. The route-root marker list is
33
+ * intentionally finite (see {@link ROUTE_ROOT_DIRS}); a consumer whose layout
34
+ * has no recognized marker (e.g. `src/parts/<feature>/…`) silently inherits the
35
+ * default grouping (no per-route split). That silence is the only real downside
36
+ * of a convention-based default, so we make the decision observable: run a build
37
+ * with `DEBUG=rango:chunks` to see, per client module, which route group it was
38
+ * assigned to or why it fell back to the shared grouping. Zero cost when off
39
+ * (the debugger is `undefined` unless the namespace is enabled). For full control
40
+ * over any layout, pass a `clientChunks` function instead of relying on the
41
+ * convention — that is the supported configurability path, not widening the list.
42
+ */
43
+ const debugChunks = createRangoDebugger(NS.chunks);
44
+
45
+ /**
46
+ * Modules that must stay on the default (shared) grouping regardless of strategy:
47
+ * React, the router client runtime, and anything in node_modules. Splitting these
48
+ * out per route would fragment the shared baseline and regress cache reuse — they
49
+ * are loaded on every route, so they belong in shared chunks.
50
+ *
51
+ * The Rango runtime is matched by package root only: `@rangojs/router` (the
52
+ * installed/aliased name) and the workspace `packages/(rangojs-router|rsc-router)/(src|dist)/`.
53
+ * The `(src|dist)` anchor matches the package's own source/build output but NOT
54
+ * consumer apps that merely live under a `packages/rangojs-router/` ancestor (the
55
+ * in-repo e2e apps), so their app components remain splittable. We deliberately do
56
+ * NOT match a bare `/src/browser/`: that is a consumer-owned path (a consumer's own
57
+ * `src/browser/Foo.tsx` must still split).
58
+ *
59
+ * We test BOTH `meta.id` (absolute) and `meta.normalizedId`. `normalizedId` is the
60
+ * project-root-relative form plugin-rsc derives (e.g. `../../src/browser/react/Link.tsx`
61
+ * for the in-repo runtime), which the package-root patterns miss; the absolute `id`
62
+ * always contains the package's real location, so it reliably catches the runtime.
63
+ */
64
+ function isSharedRuntime(meta: ClientChunkMeta): boolean {
65
+ return [meta.id, meta.normalizedId].some(
66
+ (path) =>
67
+ path.includes("/node_modules/") ||
68
+ /\/@rangojs\/router\//.test(path) ||
69
+ /\/packages\/(rangojs-router|rsc-router)\/(src|dist)\//.test(path),
70
+ );
71
+ }
72
+
73
+ /** Sanitize a raw group name into a filesystem/Rollup-safe chunk name fragment. */
74
+ function sanitizeGroup(name: string): string {
75
+ return name.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "app";
76
+ }
77
+
78
+ /**
79
+ * Directory names that conventionally hold one sub-directory per route/feature.
80
+ * When a `"use client"` module lives under one of these, the built-in strategy
81
+ * keys the chunk on the segment IMMEDIATELY AFTER the marker (the route id),
82
+ * rather than the module's immediate parent directory. This is what keeps
83
+ * `routes/foo/components/Button.tsx` and `routes/bar/components/Button.tsx` in
84
+ * `app-foo` / `app-bar` instead of colliding in a single `app-components`.
85
+ *
86
+ * Route identity lives in the path PREFIX; the immediate parent (a suffix) is
87
+ * only a reliable proxy for the un-nested `routes/<route>/Widget.tsx` layout.
88
+ */
89
+ const ROUTE_ROOT_DIRS = new Set([
90
+ "routes",
91
+ "route",
92
+ "pages",
93
+ "page",
94
+ "app",
95
+ "features",
96
+ "feature",
97
+ "views",
98
+ "view",
99
+ "handlers",
100
+ "urls",
101
+ "modules",
102
+ "screens",
103
+ "sections",
104
+ ]);
105
+
106
+ /**
107
+ * Built-in strategy used when `clientChunks: true` (also the default). Splits app
108
+ * client components by route/feature identity ONLY where it can recognize a route
109
+ * structure; everywhere else it inherits the default grouping (returns undefined).
110
+ * This conservatism is what makes it safe as a default:
111
+ *
112
+ * - A recognized route structure (`routes/<id>/…`, `app/<id>/…`, `handlers/<id>/…`
113
+ * etc.) splits into a per-route chunk `app-<id>`, at any nesting depth.
114
+ * - A flat `src/components/Button.tsx`, or host sub-apps already split by a dynamic
115
+ * `import()` boundary (each app's `serverChunk` differs), get `undefined` and so
116
+ * keep `@vitejs/plugin-rsc`'s default `serverChunk` grouping — i.e. NO change
117
+ * versus not enabling the option. Returning a parent-dir name here would instead
118
+ * merge unrelated modules (e.g. every host app's `components/Layout.tsx` into one
119
+ * `app-components`), re-introducing cross-app leakage.
120
+ *
121
+ * Resolution order:
122
+ * 1. Shared runtime (React / router / node_modules) -> `undefined` (never split).
123
+ * 2. A registered error/notFound fallback (`ctx.fallbackRefs`) -> `app-fallback`,
124
+ * regardless of location, so the error UI is decoupled from the happy path.
125
+ * 3. A {@link ROUTE_ROOT_DIRS} marker with a directory after it -> key on that
126
+ * next segment (the route id), robust to any nesting depth.
127
+ * 4. Otherwise `undefined` (inherit the default `serverChunk` grouping).
128
+ */
129
+ export function directoryClientChunks(
130
+ meta: ClientChunkMeta,
131
+ ctx?: ClientChunkContext,
132
+ ): string | undefined {
133
+ if (isSharedRuntime(meta)) {
134
+ // React / router runtime / node_modules: always shared, expected, uninteresting.
135
+ return undefined;
136
+ }
137
+ // Registered error/notFound fallbacks -> a dedicated chunk. The error UI must
138
+ // not co-bundle with the code it catches failures for, and removing it lets the
139
+ // chunk it would otherwise anchor be named after a real module, not the boundary.
140
+ if (
141
+ ctx?.fallbackRefs.size &&
142
+ ctx.fallbackRefs.has(hashRefKey(meta.normalizedId))
143
+ ) {
144
+ debugChunks?.("fallback %s -> app-fallback", meta.normalizedId);
145
+ return "app-fallback";
146
+ }
147
+ const segments = meta.normalizedId.split("/").filter(Boolean);
148
+ const dirCount = segments.length - 1; // exclude the filename
149
+ if (dirCount >= 1) {
150
+ // Route-root marker -> the segment after it is the route id. First marker
151
+ // wins, so a top-level route owns its whole subtree. The `< dirCount - 1`
152
+ // bound guarantees the segment after the marker is a directory, not the file.
153
+ for (let i = 0; i < dirCount - 1; i++) {
154
+ if (ROUTE_ROOT_DIRS.has(segments[i].toLowerCase())) {
155
+ const group = `app-${sanitizeGroup(segments[i + 1])}`;
156
+ debugChunks?.("split %s -> %s", meta.normalizedId, group);
157
+ return group;
158
+ }
159
+ }
160
+ }
161
+ // No recognized route structure -> inherit the default serverChunk grouping.
162
+ // This is the actionable "silent" case: app code that did NOT split by route.
163
+ // Surface it (under DEBUG=rango:chunks) so a consumer can see their layout
164
+ // missed the convention and either colocate under a marker dir or pass a fn.
165
+ debugChunks?.(
166
+ "shared %s (no route-root marker; inherits default grouping)",
167
+ meta.normalizedId,
168
+ );
169
+ return undefined;
170
+ }
171
+
172
+ /**
173
+ * Resolve a Rango `clientChunks` option into a @vitejs/plugin-rsc `clientChunks`
174
+ * callback, or `undefined` to leave plugin-rsc on its default (serverChunk)
175
+ * grouping.
176
+ *
177
+ * - `false` / `undefined` -> `undefined` (no override).
178
+ * - `true` -> the built-in {@link directoryClientChunks} strategy,
179
+ * bound to the discovery-populated {@link ClientChunkContext} (fallback chunk).
180
+ * - function -> the user's function, used verbatim (full control; the
181
+ * fallback refinement does not apply — the consumer owns the grouping).
182
+ */
183
+ export function resolveClientChunks(
184
+ option: ClientChunks | undefined,
185
+ ctx?: ClientChunkContext,
186
+ ): RscClientChunksFn | undefined {
187
+ if (!option) return undefined;
188
+ if (option === true) return (meta) => directoryClientChunks(meta, ctx);
189
+ return option;
190
+ }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Discovery Runner Config Parity
3
+ *
4
+ * The discovery temp server (createTempRscServer) runs the user's handler
5
+ * graph through a throwaway Node Vite server built with `configFile: false`.
6
+ * Without help, that server only sees a fixed Rango-owned plugin set, so any
7
+ * user resolution is absent during discovery, prerender, and static handler
8
+ * rendering — even though it applies at request time. Two flavors of user
9
+ * resolution must be carried across:
10
+ *
11
+ * - Third-party resolveId plugins (e.g. vite-tsconfig-paths) — forwarded as
12
+ * plugin instances, see selectForwardableResolvePlugins.
13
+ * - Native config-driven resolution, including Vite 8's built-in
14
+ * `resolve.tsconfigPaths` (which supersedes vite-tsconfig-paths) — forwarded
15
+ * as the data slice, see pickForwardedRunnerConfig.
16
+ *
17
+ * These helpers extract the resolution-relevant slice of the user's resolved
18
+ * config (resolve.*, define, oxc) and forward the user's resolution plugins
19
+ * into the temp server so discovery resolves modules the same way the real
20
+ * environment does.
21
+ */
22
+
23
+ import type { Plugin, ResolvedConfig, UserConfig } from "vite";
24
+
25
+ /**
26
+ * Whether a user plugin must NOT be forwarded into the discovery temp server.
27
+ *
28
+ * Framework-owned plugins are matched precisely -- by exact name or a
29
+ * namespaced prefix -- rather than by a loose substring/word prefix, so an
30
+ * unrelated user resolver named e.g. `rsc-paths` or `cloudflare-kv-alias` is
31
+ * still forwarded (it would otherwise reproduce issue #500).
32
+ *
33
+ * - `vite:*` Vite core + official plugins (incl.
34
+ * @vitejs/plugin-react's `vite:react-*`). The temp
35
+ * server already provides its own core; forwarding
36
+ * these would duplicate or conflict with it.
37
+ * - `rsc` / `rsc:*` @vitejs/plugin-rsc. createTempRscServer instantiates
38
+ * its own rsc() plugin; forwarding would duplicate it.
39
+ * Matched exactly (`rsc`) or by the `rsc:` namespace --
40
+ * NOT every `rsc`-prefixed name.
41
+ * - `@rangojs/router*` Our own plugins. The discovery plugin spawns the
42
+ * temp server, so forwarding would recurse infinitely.
43
+ * - `@cloudflare/vite-plugin*` / @cloudflare/vite-plugin (emits the scoped
44
+ * `vite-plugin-cloudflare*` `@cloudflare/vite-plugin` and unscoped
45
+ * `vite-plugin-cloudflare` / `vite-plugin-cloudflare:*`).
46
+ * Forwarding re-inits workerd, defeating the Node temp
47
+ * server. Matched specifically so a scoped user resolver
48
+ * like `@cloudflare/kv-alias` is still forwarded.
49
+ */
50
+ function isDenied(name: string): boolean {
51
+ return (
52
+ name.startsWith("vite:") ||
53
+ name === "rsc" ||
54
+ name.startsWith("rsc:") ||
55
+ name.startsWith("@rangojs/router") ||
56
+ name.startsWith("@cloudflare/vite-plugin") ||
57
+ name.startsWith("vite-plugin-cloudflare")
58
+ );
59
+ }
60
+
61
+ /**
62
+ * A plugin participates in resolution if it exposes `resolveId` or `load`.
63
+ * Plugins that only transform, configure the server, or hook into the build
64
+ * lifecycle do not affect how bare specifiers resolve, so we skip them to keep
65
+ * the forwarded surface minimal.
66
+ */
67
+ function hasResolutionHooks(p: Plugin): boolean {
68
+ return Boolean((p as any).resolveId || (p as any).load);
69
+ }
70
+
71
+ /**
72
+ * Strip a resolved plugin instance down to its resolution hooks plus the
73
+ * gating fields that decide whether/where it runs.
74
+ *
75
+ * We reuse the SAME instance objects captured from `config.plugins`. By the
76
+ * time `configResolved` fires on the discovery plugin, every plugin's own
77
+ * `config`/`configResolved` has already run on the main server, so any state
78
+ * a `resolveId` hook depends on (e.g. vite-tsconfig-paths' compiled path
79
+ * matcher, held in closure) is already populated. Forwarding only the
80
+ * resolution hooks therefore preserves correct resolution while avoiding a
81
+ * second `buildStart`/`configureServer`/`config` lifecycle in the temp server.
82
+ *
83
+ * `enforce` and `applyToEnvironment` are preserved so ordering and per-environment
84
+ * gating match the real pipeline.
85
+ *
86
+ * `apply` is intentionally dropped. Vite filters plugins by `apply` against the
87
+ * command during config resolution, so the `config.plugins` we read here is
88
+ * already command-filtered by the main server (build: `apply: "build"` +
89
+ * unconditional; dev: `apply: "serve"` + unconditional). The discovery temp
90
+ * server is always created with `createServer` (`command === "serve"`), so a
91
+ * forwarded `apply: "build"` plugin would be filtered straight back out -- even
92
+ * during a production build, where build-only resolvers are exactly what
93
+ * static/prerender rendering needs. Since the source list is already correct for
94
+ * the current command, the forwarded copy must carry no `apply` gate.
95
+ */
96
+ function stripToResolutionHooks(p: Plugin): Plugin {
97
+ const stripped: Plugin = { name: p.name };
98
+ if ((p as any).enforce) (stripped as any).enforce = (p as any).enforce;
99
+ if ((p as any).applyToEnvironment)
100
+ (stripped as any).applyToEnvironment = (p as any).applyToEnvironment;
101
+ if ((p as any).resolveId) (stripped as any).resolveId = (p as any).resolveId;
102
+ if ((p as any).load) (stripped as any).load = (p as any).load;
103
+ return stripped;
104
+ }
105
+
106
+ /**
107
+ * Pick the user's resolution plugins from the resolved plugin list, denylist
108
+ * framework-owned plugins, keep only those with resolution hooks, and strip
109
+ * each to its resolution surface. Returns plugin objects safe to drop into the
110
+ * discovery temp server's `plugins` array.
111
+ */
112
+ export function selectForwardableResolvePlugins(
113
+ plugins: readonly Plugin[] | undefined,
114
+ ): Plugin[] {
115
+ if (!plugins) return [];
116
+ const forwarded: Plugin[] = [];
117
+ for (const p of plugins) {
118
+ const name = p?.name;
119
+ if (!name || isDenied(name)) continue;
120
+ if (!hasResolutionHooks(p)) continue;
121
+ forwarded.push(stripToResolutionHooks(p));
122
+ }
123
+ return forwarded;
124
+ }
125
+
126
+ /**
127
+ * The resolution-relevant slice of the user's resolved config that is plain
128
+ * data (no plugin re-execution): everything under `resolve` that influences
129
+ * how specifiers map to files, plus `define` and `oxc` so transforms and
130
+ * compile-time constants match request time.
131
+ */
132
+ export interface ForwardedRunnerConfig {
133
+ resolve: UserConfig["resolve"];
134
+ define: UserConfig["define"];
135
+ oxc: UserConfig["oxc"];
136
+ }
137
+
138
+ /**
139
+ * Extract the data-only config slice to mirror into the discovery temp server.
140
+ * `alias` is included here so callers no longer need to thread it separately.
141
+ *
142
+ * `tsconfigPaths` is forwarded so Vite 8's native tsconfig `paths` resolution
143
+ * (a top-level `resolve` flag, off by default) reaches the temp server. The
144
+ * server is created with `configFile: false` and an explicit, allowlisted
145
+ * resolve slice, so a flag that is not copied here is simply absent during
146
+ * discovery — which would make path-aliased imports fail at prerender/static
147
+ * time the same way unforwarded resolveId plugins did (issue #500).
148
+ *
149
+ * `oxc` keeps the user's options but always pins the RSC-required JSX runtime
150
+ * (automatic, react), since the temp server compiles the handler graph as
151
+ * React server components regardless of the user's app-level JSX config. Vite 8
152
+ * replaced the deprecated `esbuild` transform option with `oxc`, so we read and
153
+ * forward `oxc` exclusively — no `esbuild` field is touched.
154
+ */
155
+ export function pickForwardedRunnerConfig(
156
+ config: ResolvedConfig,
157
+ ): ForwardedRunnerConfig {
158
+ const r = config.resolve ?? ({} as ResolvedConfig["resolve"]);
159
+ const resolve: NonNullable<UserConfig["resolve"]> = {};
160
+ if (r.alias !== undefined) resolve.alias = r.alias as any;
161
+ if (r.dedupe !== undefined) resolve.dedupe = r.dedupe;
162
+ if (r.conditions !== undefined) resolve.conditions = r.conditions;
163
+ if (r.mainFields !== undefined) resolve.mainFields = r.mainFields;
164
+ if (r.extensions !== undefined) resolve.extensions = r.extensions;
165
+ if (r.preserveSymlinks !== undefined)
166
+ resolve.preserveSymlinks = r.preserveSymlinks;
167
+ if (r.tsconfigPaths !== undefined) resolve.tsconfigPaths = r.tsconfigPaths;
168
+
169
+ // Pin the RSC JSX runtime on top of the user's oxc options. The user's
170
+ // jsx sub-options (e.g. `development`) are preserved when present; only
171
+ // `runtime`/`importSource` are forced to the values the RSC compile needs.
172
+ const userOxc = config.oxc;
173
+ const userJsx =
174
+ userOxc &&
175
+ typeof userOxc === "object" &&
176
+ typeof userOxc.jsx === "object" &&
177
+ userOxc.jsx !== null
178
+ ? userOxc.jsx
179
+ : {};
180
+ const oxc: UserConfig["oxc"] =
181
+ userOxc && typeof userOxc === "object"
182
+ ? {
183
+ ...userOxc,
184
+ jsx: { ...userJsx, runtime: "automatic", importSource: "react" },
185
+ }
186
+ : { jsx: { runtime: "automatic", importSource: "react" } };
187
+
188
+ return {
189
+ resolve,
190
+ define: config.define,
191
+ oxc,
192
+ };
193
+ }
@@ -4,20 +4,33 @@
4
4
  * used directly by evaluateLazyEntry() without running the handler.
5
5
  * Non-leaf nodes are skipped because they have nested lazy includes that
6
6
  * require the handler to run for discovery.
7
+ *
8
+ * A leaf is also skipped when its staticPrefix collides with an ancestor
9
+ * include node's staticPrefix. That happens when a dynamic param collapses the
10
+ * staticPrefix of nested includes onto the parent's (e.g. `/m/:id/edit` -> sp
11
+ * `/m`): precomputing such a leaf under the collapsed prefix would let the
12
+ * ancestor's lazy entry claim a route it cannot register (the route is behind
13
+ * further nested lazy includes), producing a RouteNotFoundError at request time
14
+ * (issue #506). Those routes are resolved via the handler chain instead.
7
15
  */
8
16
  export function flattenLeafEntries(
9
17
  prefixTree: Record<string, any>,
10
18
  routeManifest: Record<string, string>,
11
19
  result: Array<{ staticPrefix: string; routes: Record<string, string> }>,
12
20
  ): void {
13
- function visit(node: any): void {
21
+ function visit(node: any, ancestorStaticPrefixes: Set<string>): void {
14
22
  const children = node.children || {};
15
23
  if (
16
24
  Object.keys(children).length === 0 &&
17
25
  node.routes &&
18
26
  node.routes.length > 0
19
27
  ) {
20
- // Leaf node: collect its routes from the manifest
28
+ // Leaf node. Skip if its staticPrefix collides with an ancestor include
29
+ // node's staticPrefix (dynamic-param collapse) — see doc comment above.
30
+ if (ancestorStaticPrefixes.has(node.staticPrefix)) {
31
+ return;
32
+ }
33
+ // Collect its routes from the manifest
21
34
  const routes: Record<string, string> = {};
22
35
  for (const name of node.routes) {
23
36
  if (name in routeManifest) {
@@ -26,14 +39,17 @@ export function flattenLeafEntries(
26
39
  }
27
40
  result.push({ staticPrefix: node.staticPrefix, routes });
28
41
  } else {
29
- // Non-leaf: recurse into children
42
+ // Non-leaf: recurse into children, tracking this node's staticPrefix as
43
+ // an ancestor so a collapsed nested leaf below it is not over-claimed.
44
+ const nextAncestors = new Set(ancestorStaticPrefixes);
45
+ nextAncestors.add(node.staticPrefix);
30
46
  for (const child of Object.values(children)) {
31
- visit(child);
47
+ visit(child, nextAncestors);
32
48
  }
33
49
  }
34
50
  }
35
51
  for (const node of Object.values(prefixTree)) {
36
- visit(node);
52
+ visit(node, new Set());
37
53
  }
38
54
  }
39
55
 
@@ -1,4 +1,4 @@
1
- import type { Plugin } from "vite";
1
+ import type { Plugin, ResolvedConfig } from "vite";
2
2
  import * as Vite from "vite";
3
3
  import { getPublishedPackageName } from "./package-resolution.js";
4
4
  import { performanceTracksOptimizeDepsPlugin } from "../plugins/performance-tracks.js";
@@ -6,39 +6,52 @@ import {
6
6
  VIRTUAL_ENTRY_BROWSER,
7
7
  VIRTUAL_ENTRY_SSR,
8
8
  getVirtualEntryRSC,
9
+ getVirtualVersionContent,
9
10
  VIRTUAL_IDS,
10
11
  } from "../plugins/virtual-entries.js";
11
12
 
13
+ // Cloudflare preset: @cloudflare/vite-plugin sets optimizeDeps.entries (string
14
+ // or array) on the rsc environment. Single source for both the discovery plugin
15
+ // and the version injector so they target the same entry.
16
+ export function resolveRscEntryFromConfig(
17
+ config: ResolvedConfig,
18
+ ): string | undefined {
19
+ const entries = (config.environments as any)?.["rsc"]?.optimizeDeps?.entries;
20
+ if (typeof entries === "string") return entries;
21
+ if (Array.isArray(entries) && entries.length > 0) return entries[0];
22
+ return undefined;
23
+ }
24
+
12
25
  /**
13
- * esbuild plugin to provide rsc-router:version virtual module during optimization.
14
- * This is needed because esbuild runs during Vite's dependency optimization phase,
15
- * before Vite's plugin system can handle virtual modules.
26
+ * Rolldown plugin to provide the version virtual module during dependency
27
+ * optimization. Vite 8 optimizes deps with Rolldown (a Rollup-style plugin
28
+ * pipeline that is separate from the main plugin set), so this is a
29
+ * resolveId/load plugin under optimizeDeps.rolldownOptions. Any dep pulled into
30
+ * optimization that imports the version virtual module gets a "dev" stub here;
31
+ * the real VERSION is injected into runtime modules by the version plugin.
16
32
  */
17
- const versionEsbuildPlugin = {
33
+ const versionRolldownPlugin = {
18
34
  name: "@rangojs/router-version",
19
- setup(build: any): void {
20
- build.onResolve({ filter: /^rsc-router:version$/ }, (args: any) => ({
21
- path: args.path,
22
- namespace: "@rangojs/router-virtual",
23
- }));
24
- build.onLoad(
25
- { filter: /.*/, namespace: "@rangojs/router-virtual" },
26
- () => ({
27
- contents: `export const VERSION = "dev";`,
28
- loader: "js",
29
- }),
30
- );
35
+ resolveId(id: string): string | undefined {
36
+ if (id === VIRTUAL_IDS.version) return "\0" + VIRTUAL_IDS.version;
37
+ return undefined;
38
+ },
39
+ load(id: string): string | undefined {
40
+ if (id === "\0" + VIRTUAL_IDS.version) {
41
+ return getVirtualVersionContent("dev");
42
+ }
43
+ return undefined;
31
44
  },
32
45
  };
33
46
 
34
47
  /**
35
- * Shared esbuild options for dependency optimization.
36
- * Includes the version stub plugin for all environments.
48
+ * Shared Rolldown options for dependency optimization (Vite 8).
49
+ * Includes the version stub plugin and the performance-tracks RSDW patch.
37
50
  */
38
- export const sharedEsbuildOptions: {
51
+ export const sharedRolldownOptions: {
39
52
  plugins: any[];
40
53
  } = {
41
- plugins: [versionEsbuildPlugin, performanceTracksOptimizeDepsPlugin()],
54
+ plugins: [versionRolldownPlugin, performanceTracksOptimizeDepsPlugin()],
42
55
  };
43
56
 
44
57
  /**
@@ -103,14 +116,68 @@ export function createVirtualEntriesPlugin(
103
116
  };
104
117
  }
105
118
 
119
+ // Matches rollup's FILE_NAME_CONFLICT message and reports whether the colliding
120
+ // file is a content-hashed asset, e.g.
121
+ // The emitted file "assets/index-DlGNrvnU.css" overwrites a previously ...
122
+ // The emitted file "assets/inter-latin-Dx4kXJAl.woff2" overwrites a ...
123
+ // The match is UNANCHORED on purpose: by the time the warning reaches this user
124
+ // onwarn handler, Vite's logger has wrapped rollup's raw message with an ANSI
125
+ // color sequence and a "[CODE] " label, e.g.
126
+ // "[FILE_NAME_CONFLICT] The emitted file \"...\" overwrites ..."
127
+ // A "^The emitted file" anchor sits behind that prefix and never matches; and
128
+ // Vite also strips the JSON.stringify quotes rollup puts around the filename, so
129
+ // the match is UNANCHORED and quote-OPTIONAL ("?...?"?). The non-whitespace
130
+ // capture stops at the space before "overwrites" (Vite's unquoted display form)
131
+ // or the closing quote (raw rollup form); either way it carries no ANSI.
132
+ // A content-hashed name ends with a "-" separator + a Vite content hash. The
133
+ // hash is a FIXED-LENGTH base64url run ([A-Za-z0-9_-], default 8), so it can
134
+ // itself contain "-"/"_": it CANNOT be located by splitting on the last "-"
135
+ // (that lands inside the hash whenever it carries a dash, e.g. "...-Cabi7G8-" ->
136
+ // "" or "...-CkhJZR-_" -> "_", which let those conflicts leak). Instead take the
137
+ // trailing HASH_LEN chars and require the "-" separator right before them. The
138
+ // hash must hold an uppercase letter or digit (a real hash is never an
139
+ // all-lowercase word), so stable names like "assets/manifest.json" or
140
+ // "assets/loading-skeleton.css" still surface as potential genuine overwrites.
141
+ function isContentHashedAssetConflict(message: string | undefined): boolean {
142
+ if (!message) return false;
143
+ const match =
144
+ /The emitted file "?([^"\s]+)"? overwrites a previously emitted file/.exec(
145
+ message,
146
+ );
147
+ if (!match) return false;
148
+ const fileName = match[1];
149
+ const base = fileName.slice(fileName.lastIndexOf("/") + 1);
150
+ const dot = base.lastIndexOf(".");
151
+ if (dot <= 0) return false;
152
+ const stem = base.slice(0, dot);
153
+ // HASH_LEN tracks Vite's default [hash] width; bump it if an app sets a custom
154
+ // assetFileNames hash length.
155
+ const HASH_LEN = 8;
156
+ if (stem.length < HASH_LEN + 1 || stem[stem.length - HASH_LEN - 1] !== "-") {
157
+ return false;
158
+ }
159
+ const hash = stem.slice(-HASH_LEN);
160
+ return /^[A-Za-z0-9_-]+$/.test(hash) && /[A-Z0-9]/.test(hash);
161
+ }
162
+
106
163
  /**
107
164
  * Rollup onwarn handler that suppresses known harmless warnings:
108
165
  * - "use client" directives: handled by the RSC plugin, not relevant to Rollup
109
166
  * - sourcemap errors: caused by "use client" directive at line 1:0 confusing sourcemap resolution
110
167
  * - sourcemap incomplete: plugins that transform without generating sourcemaps (router + RSC plugin)
111
- * - dynamic/static mixed imports: expected for router internals (e.g. request-context, cache-scope)
168
+ * - dynamic/static mixed imports: expected for router internals (e.g. request-context, cache-scope).
169
+ * Under Rolldown (Vite 8) this surfaces as the INEFFECTIVE_DYNAMIC_IMPORT code emitted directly
170
+ * by the bundler, rather than the vite:reporter message handled below (Rollup/Vite 7 shape).
112
171
  * - empty bundle: @vitejs/plugin-rsc scan build (step 1/5) produces an empty "index" chunk
113
172
  * because the RSC entry is fully externalized during client-reference analysis
173
+ * - file name conflicts on content-hashed assets: @vitejs/plugin-rsc copies the rsc
174
+ * environment's imported CSS/assets into the client bundle (its assets-manifest
175
+ * generateBundle re-emits each via emitFile with an explicit content-hashed
176
+ * fileName). When the client bundle already produced that identical asset,
177
+ * rollup raises FILE_NAME_CONFLICT even though the bytes are identical (a
178
+ * content hash collision IS a content match). Only these are suppressed; a
179
+ * collision on a stable name still surfaces. No upstream fix as of
180
+ * @vitejs/plugin-rsc@0.5.27; remove when it skips the redundant emit.
114
181
  */
115
182
  export function onwarn(
116
183
  warning: Vite.Rollup.RollupLog,
@@ -119,7 +186,14 @@ export function onwarn(
119
186
  if (
120
187
  warning.code === "MODULE_LEVEL_DIRECTIVE" ||
121
188
  warning.code === "SOURCEMAP_ERROR" ||
122
- warning.code === "EMPTY_BUNDLE"
189
+ warning.code === "EMPTY_BUNDLE" ||
190
+ warning.code === "INEFFECTIVE_DYNAMIC_IMPORT"
191
+ ) {
192
+ return;
193
+ }
194
+ if (
195
+ warning.code === "FILE_NAME_CONFLICT" &&
196
+ isContentHashedAssetConflict(warning.message)
123
197
  ) {
124
198
  return;
125
199
  }
@@ -157,12 +231,19 @@ export function getManualChunks(id: string): string | undefined {
157
231
  return "react";
158
232
  }
159
233
  // Use dynamic package name from package.json
160
- // Check both npm install path and workspace symlink resolved path
234
+ // Check both npm install path and workspace symlink resolved path.
235
+ //
236
+ // The workspace patterns are anchored to the package's own `src`/`dist` so
237
+ // they match the router runtime but NOT consumer apps that merely live under a
238
+ // `packages/rangojs-router/` ancestor (the in-repo e2e apps at
239
+ // `packages/rangojs-router/e2e/<app>/src/...`). Without the anchor those apps'
240
+ // own client components were force-merged into the shared "router" chunk,
241
+ // which both misrepresented real-consumer bundles and blocked `clientChunks`
242
+ // splitting from relocating them.
161
243
  const packageName = getPublishedPackageName();
162
244
  if (
163
245
  normalized.includes(`node_modules/${packageName}/`) ||
164
- normalized.includes("packages/rsc-router/") ||
165
- normalized.includes("packages/rangojs-router/")
246
+ /\/packages\/(rsc-router|rangojs-router)\/(src|dist)\//.test(normalized)
166
247
  ) {
167
248
  return "router";
168
249
  }