@rangojs/router 0.0.0-experimental.10

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