@rangojs/router 0.27.0 → 0.28.0

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 (212) hide show
  1. package/dist/bin/rango.js +1 -1
  2. package/dist/types/__internal.d.ts +7 -1
  3. package/dist/types/browser/event-controller.d.ts +2 -1
  4. package/dist/types/browser/history-state.d.ts +3 -9
  5. package/dist/types/browser/navigation-store.d.ts +8 -6
  6. package/dist/types/browser/react/filter-segment-order.d.ts +2 -2
  7. package/dist/types/browser/segment-reconciler.d.ts +6 -4
  8. package/dist/types/browser/types.d.ts +2 -1
  9. package/dist/types/browser/wire-protocol.d.ts +25 -0
  10. package/dist/types/cache/cache-key-utils.d.ts +11 -5
  11. package/dist/types/cache/cache-scope.d.ts +34 -22
  12. package/dist/types/cache/cf/cf-cache-constants.d.ts +2 -2
  13. package/dist/types/cache/cf/cf-cache-store.d.ts +47 -65
  14. package/dist/types/cache/cf/cf-kv-utils.d.ts +1 -1
  15. package/dist/types/cache/handle-snapshot.d.ts +9 -4
  16. package/dist/types/cache/segment-codec.d.ts +14 -0
  17. package/dist/types/cache/shell-snapshot.d.ts +1 -1
  18. package/dist/types/cache/tag-invalidation.d.ts +10 -0
  19. package/dist/types/cache/taint.d.ts +5 -3
  20. package/dist/types/cache/types.d.ts +7 -3
  21. package/dist/types/cache/vercel/vercel-cache-store.d.ts +8 -6
  22. package/dist/types/prefetch-markers.d.ts +5 -14
  23. package/dist/types/prerender/store.d.ts +31 -0
  24. package/dist/types/prerender/warm-request.d.ts +3 -3
  25. package/dist/types/prerender.d.ts +2 -2
  26. package/dist/types/route-name.d.ts +5 -0
  27. package/dist/types/router/error-handling.d.ts +4 -4
  28. package/dist/types/router/instrument.d.ts +4 -3
  29. package/dist/types/router/intercept-resolution.d.ts +25 -9
  30. package/dist/types/router/match-context.d.ts +4 -11
  31. package/dist/types/router/match-handlers.d.ts +2 -6
  32. package/dist/types/router/match-middleware/background-revalidation.d.ts +10 -20
  33. package/dist/types/router/match-middleware/cache-lookup.d.ts +34 -86
  34. package/dist/types/router/match-middleware/segment-resolution.d.ts +8 -6
  35. package/dist/types/router/prerender-match.d.ts +21 -6
  36. package/dist/types/router/preview-match.d.ts +2 -7
  37. package/dist/types/router/request-classification.d.ts +5 -0
  38. package/dist/types/router/router-context.d.ts +7 -46
  39. package/dist/types/router/router-interfaces.d.ts +8 -14
  40. package/dist/types/router/segment-resolution/loader-cache.d.ts +3 -3
  41. package/dist/types/router/segment-resolution/loader-mask.d.ts +4 -4
  42. package/dist/types/router/segment-resolution/prefetch-deferral.d.ts +20 -18
  43. package/dist/types/router/segment-resolution/resolution-pass.d.ts +93 -0
  44. package/dist/types/router/segment-resolution/revalidation.d.ts +82 -31
  45. package/dist/types/router/segment-resolution.d.ts +1 -2
  46. package/dist/types/router/segment-wrappers.d.ts +11 -48
  47. package/dist/types/router/telemetry.d.ts +2 -0
  48. package/dist/types/router/types.d.ts +10 -0
  49. package/dist/types/rsc/full-payload.d.ts +2 -2
  50. package/dist/types/rsc/handler-context.d.ts +6 -6
  51. package/dist/types/rsc/json-route-result.d.ts +5 -9
  52. package/dist/types/rsc/request-stages.d.ts +203 -0
  53. package/dist/types/rsc/response-cache-serve.d.ts +7 -12
  54. package/dist/types/rsc/response-route-handler.d.ts +2 -2
  55. package/dist/types/rsc/routine-plan.d.ts +1 -1
  56. package/dist/types/rsc/server-action.d.ts +2 -2
  57. package/dist/types/rsc/shell-capture-constants.d.ts +1 -1
  58. package/dist/types/rsc/shell-capture.d.ts +132 -15
  59. package/dist/types/rsc/shell-serve.d.ts +37 -12
  60. package/dist/types/server/context.d.ts +9 -8
  61. package/dist/types/server/handle-store.d.ts +16 -0
  62. package/dist/types/server/render-pass.d.ts +72 -0
  63. package/dist/types/server/request-context.d.ts +24 -104
  64. package/dist/types/server/rewrite-trail.d.ts +2 -2
  65. package/dist/types/testing/dispatch.d.ts +35 -18
  66. package/dist/types/types/cache-types.d.ts +6 -3
  67. package/dist/types/types/error-types.d.ts +9 -1
  68. package/dist/types/types/handler-context.d.ts +9 -1
  69. package/dist/types/types/segments.d.ts +1 -1
  70. package/dist/types/vite/discovery/build-discovery-phase.d.ts +40 -0
  71. package/dist/types/vite/discovery/build-env.d.ts +22 -0
  72. package/dist/types/vite/discovery/bundle-scan-phase.d.ts +12 -0
  73. package/dist/types/vite/discovery/dev-prerender-cache.d.ts +3 -2
  74. package/dist/types/vite/discovery/dev-server-phase.d.ts +26 -0
  75. package/dist/types/vite/discovery/discovery-errors.d.ts +1 -1
  76. package/dist/types/vite/discovery/state.d.ts +12 -0
  77. package/dist/types/vite/plugins/version-plugin.d.ts +1 -1
  78. package/dist/types/vite/plugins/virtual-entries.d.ts +1 -1
  79. package/dist/types/vite/router-discovery.d.ts +8 -47
  80. package/dist/types/vite/temp-rsc-server.d.ts +39 -0
  81. package/dist/types/vite/utils/prerender-utils.d.ts +9 -0
  82. package/dist/types/wire-params.d.ts +34 -0
  83. package/dist/vite/index.js +3809 -3710
  84. package/package.json +1 -1
  85. package/skills/cache-guide/SKILL.md +8 -5
  86. package/skills/caching/SKILL.md +37 -18
  87. package/skills/document-cache/SKILL.md +13 -1
  88. package/skills/handler-use/SKILL.md +1 -1
  89. package/skills/intercept/SKILL.md +17 -7
  90. package/skills/middleware/SKILL.md +18 -0
  91. package/skills/ppr/SKILL.md +18 -3
  92. package/skills/prerender/SKILL.md +39 -15
  93. package/skills/rango/SKILL.md +5 -1
  94. package/skills/server-actions/SKILL.md +8 -1
  95. package/skills/testing/response-routes.md +6 -4
  96. package/skills/use-cache/SKILL.md +46 -8
  97. package/src/__internal.ts +7 -1
  98. package/src/browser/connection-warmup.ts +3 -1
  99. package/src/browser/event-controller.ts +5 -3
  100. package/src/browser/history-state.ts +6 -12
  101. package/src/browser/navigation-bridge.ts +14 -13
  102. package/src/browser/navigation-client.ts +18 -25
  103. package/src/browser/navigation-store.ts +25 -27
  104. package/src/browser/navigation-transaction.ts +4 -1
  105. package/src/browser/prefetch/cache.ts +2 -1
  106. package/src/browser/prefetch/fetch.ts +8 -16
  107. package/src/browser/prefetch/queue.ts +4 -4
  108. package/src/browser/react/NavigationProvider.tsx +2 -1
  109. package/src/browser/react/filter-segment-order.ts +2 -2
  110. package/src/browser/rsc-router.tsx +1 -0
  111. package/src/browser/segment-reconciler.ts +66 -53
  112. package/src/browser/server-action-bridge.ts +50 -57
  113. package/src/browser/types.ts +2 -1
  114. package/src/browser/wire-protocol.ts +41 -0
  115. package/src/cache/cache-key-utils.ts +11 -5
  116. package/src/cache/cache-runtime.ts +110 -50
  117. package/src/cache/cache-scope.ts +110 -64
  118. package/src/cache/cf/cf-cache-constants.ts +2 -2
  119. package/src/cache/cf/cf-cache-store.ts +486 -874
  120. package/src/cache/cf/cf-kv-utils.ts +1 -1
  121. package/src/cache/document-cache.ts +34 -13
  122. package/src/cache/handle-snapshot.ts +19 -7
  123. package/src/cache/segment-codec.ts +55 -0
  124. package/src/cache/shell-snapshot.ts +2 -2
  125. package/src/cache/tag-invalidation.ts +21 -2
  126. package/src/cache/taint.ts +5 -3
  127. package/src/cache/types.ts +7 -3
  128. package/src/cache/vercel/vercel-cache-store.ts +243 -310
  129. package/src/handles/pushed-by.ts +1 -1
  130. package/src/prefetch-markers.ts +5 -16
  131. package/src/prerender/store.ts +76 -0
  132. package/src/prerender/warm-request.ts +8 -4
  133. package/src/prerender.ts +2 -2
  134. package/src/route-name.ts +8 -0
  135. package/src/router/error-handling.ts +4 -4
  136. package/src/router/instrument.ts +4 -3
  137. package/src/router/intercept-resolution.ts +77 -75
  138. package/src/router/loader-resolution.ts +5 -4
  139. package/src/router/match-api.ts +4 -5
  140. package/src/router/match-context.ts +20 -12
  141. package/src/router/match-handlers.ts +8 -20
  142. package/src/router/match-middleware/background-revalidation.ts +41 -53
  143. package/src/router/match-middleware/cache-lookup.ts +675 -726
  144. package/src/router/match-middleware/cache-store.ts +4 -8
  145. package/src/router/match-middleware/intercept-resolution.ts +3 -23
  146. package/src/router/match-middleware/segment-resolution.ts +34 -61
  147. package/src/router/middleware.ts +69 -11
  148. package/src/router/navigation-snapshot.ts +4 -4
  149. package/src/router/prerender-match.ts +100 -44
  150. package/src/router/preview-match.ts +6 -41
  151. package/src/router/request-classification.ts +13 -7
  152. package/src/router/route-snapshot.ts +2 -5
  153. package/src/router/router-context.ts +10 -95
  154. package/src/router/router-interfaces.ts +8 -14
  155. package/src/router/segment-resolution/loader-cache.ts +14 -9
  156. package/src/router/segment-resolution/loader-mask.ts +5 -5
  157. package/src/router/segment-resolution/prefetch-deferral.ts +30 -27
  158. package/src/router/segment-resolution/resolution-pass.ts +137 -0
  159. package/src/router/segment-resolution/revalidation.ts +897 -776
  160. package/src/router/segment-resolution.ts +4 -13
  161. package/src/router/segment-wrappers.ts +51 -269
  162. package/src/router/telemetry.ts +5 -0
  163. package/src/router/types.ts +10 -0
  164. package/src/router.ts +12 -13
  165. package/src/rsc/full-payload.ts +6 -5
  166. package/src/rsc/handler-context.ts +8 -14
  167. package/src/rsc/handler.ts +126 -507
  168. package/src/rsc/json-route-result.ts +5 -9
  169. package/src/rsc/loader-fetch.ts +6 -5
  170. package/src/rsc/progressive-enhancement.ts +5 -0
  171. package/src/rsc/request-stages.ts +757 -0
  172. package/src/rsc/response-cache-serve.ts +10 -14
  173. package/src/rsc/response-route-handler.ts +13 -5
  174. package/src/rsc/rewrite-passes.ts +2 -1
  175. package/src/rsc/routine-plan.ts +1 -1
  176. package/src/rsc/rsc-rendering.ts +164 -349
  177. package/src/rsc/server-action.ts +87 -113
  178. package/src/rsc/shell-capture-constants.ts +1 -1
  179. package/src/rsc/shell-capture.ts +212 -169
  180. package/src/rsc/shell-serve.ts +121 -18
  181. package/src/rsc/ssr-setup.ts +5 -4
  182. package/src/segment-system.tsx +3 -3
  183. package/src/server/context.ts +22 -25
  184. package/src/server/handle-store.ts +55 -0
  185. package/src/server/render-pass.ts +291 -0
  186. package/src/server/request-context.ts +26 -115
  187. package/src/server/rewrite-trail.ts +6 -4
  188. package/src/ssr/index.tsx +1 -1
  189. package/src/testing/dispatch.ts +223 -710
  190. package/src/testing/e2e/page-helpers.ts +2 -2
  191. package/src/testing/serve-shell-request.ts +23 -36
  192. package/src/types/cache-types.ts +6 -3
  193. package/src/types/error-types.ts +9 -1
  194. package/src/types/handler-context.ts +12 -1
  195. package/src/types/segments.ts +1 -1
  196. package/src/vite/discovery/build-discovery-phase.ts +204 -0
  197. package/src/vite/discovery/build-env.ts +148 -0
  198. package/src/vite/discovery/bundle-scan-phase.ts +128 -0
  199. package/src/vite/discovery/dev-prerender-cache.ts +8 -3
  200. package/src/vite/discovery/dev-server-phase.ts +1776 -0
  201. package/src/vite/discovery/discover-routers.ts +1 -1
  202. package/src/vite/discovery/discovery-errors.ts +1 -1
  203. package/src/vite/discovery/prerender-collection.ts +24 -39
  204. package/src/vite/discovery/state.ts +15 -0
  205. package/src/vite/plugins/version-plugin.ts +1 -1
  206. package/src/vite/plugins/virtual-entries.ts +1 -1
  207. package/src/vite/router-discovery.ts +29 -2428
  208. package/src/vite/temp-rsc-server.ts +223 -0
  209. package/src/vite/utils/prerender-utils.ts +47 -0
  210. package/src/wire-params.ts +35 -0
  211. package/dist/types/router/segment-resolution/fresh.d.ts +0 -72
  212. package/src/router/segment-resolution/fresh.ts +0 -945
@@ -0,0 +1,1776 @@
1
+ /**
2
+ * Dev server phase: the discovery plugin's configureServer hook.
3
+ *
4
+ * Runs dev discovery (the Node RSC runner, or a temp Node server under
5
+ * Cloudflare, whose RSC env has no runner), serves the dev /__rsc_prerender
6
+ * and /__rsc_shell endpoints, and watches route files to regenerate the
7
+ * generated route types and re-run runtime discovery on HMR.
8
+ */
9
+
10
+ import type { ViteDevServer } from "vite";
11
+ import { normalizePath } from "vite";
12
+ import { resolve } from "node:path";
13
+ import { readFileSync } from "node:fs";
14
+ import {
15
+ formatNestedRouterConflictError,
16
+ findNestedRouterConflict,
17
+ isInSkippedScanDir,
18
+ } from "../../build/generate-route-types.js";
19
+ import { firstCodeMatchIndex } from "../../build/route-types/source-scan.js";
20
+ import {
21
+ DEV_DISCOVERY_EPOCH_HEADER,
22
+ DEV_DISCOVERY_PROBE_HEADER,
23
+ DEV_DISCOVERY_QUERY_EVENT,
24
+ DEV_DISCOVERY_READY_EVENT,
25
+ } from "../../dev-discovery-protocol.js";
26
+ import {
27
+ DEV_SHELL_PROBE_TIMEOUT_MS,
28
+ normalizeCaptureTimeout,
29
+ } from "../../rsc/shell-serve.js";
30
+ import { internalDebugNoCacheMiddleware } from "../inject-client-debug.js";
31
+ import { uniformVersions } from "../../router-versions.js";
32
+ import { VIRTUAL_IDS } from "../plugins/virtual-entries.js";
33
+ import {
34
+ canRefreshRuntimeDiscovery,
35
+ recordDiscoveryFailure,
36
+ VIRTUAL_ROUTES_MANIFEST_ID,
37
+ type DiscoveryState,
38
+ } from "./state.js";
39
+ import { consumeSelfGenWrite } from "./self-gen-tracking.js";
40
+ import { discoverRouters } from "./discover-routers.js";
41
+ import {
42
+ componentUseSignature,
43
+ refreshRecordedClientUrlProjections,
44
+ } from "./client-urls-projection.js";
45
+ import { describeDiscoveryFailure } from "./discovery-errors.js";
46
+ import { findTransitionWhenError } from "../../transition-when-ref.js";
47
+ import {
48
+ createDevPrerenderCache,
49
+ devPrerenderCacheKey,
50
+ payloadBodiesFromResult,
51
+ } from "./dev-prerender-cache.js";
52
+ import {
53
+ writeCombinedRouteTypesWithTracking,
54
+ writeRouteTypesFiles,
55
+ supplementGenFilesWithRuntimeRoutes,
56
+ } from "./route-types-writer.js";
57
+ import { createDiscoveryGate } from "./gate-state.js";
58
+ import { acquireBuildEnv, releaseBuildEnv } from "./build-env.js";
59
+ import { createTempRscServer } from "../temp-rsc-server.js";
60
+ import { createRangoDebugger, timed, timedSync, NS } from "../debug.js";
61
+
62
+ const debugDiscovery = createRangoDebugger(NS.discovery);
63
+ const debugDev = createRangoDebugger(NS.dev);
64
+
65
+ /** The slice of a Vite environment module graph the route-file watcher reads. */
66
+ interface ModulesByFileGraph {
67
+ getModulesByFile(file: string): ReadonlySet<unknown> | undefined;
68
+ }
69
+
70
+ /** Modules a Vite graph holds for `file`; Vite keys its file index by normalized path. */
71
+ function modulesForFile(
72
+ graph: ModulesByFileGraph,
73
+ file: string,
74
+ ): ReadonlySet<unknown> | undefined {
75
+ return graph.getModulesByFile(normalizePath(file));
76
+ }
77
+
78
+ /**
79
+ * Whether the dev route-file watcher ignores `file`: it sits in a directory
80
+ * every discovery scan skips (isInSkippedScanDir) and the RSC graph has not
81
+ * loaded it. See docs/manifests.md, "A reload no file of the app asked for".
82
+ */
83
+ export function isFileOutsideApp(
84
+ root: string,
85
+ file: string,
86
+ rscGraph: ModulesByFileGraph | undefined,
87
+ ): boolean {
88
+ return (
89
+ isInSkippedScanDir(root, file) &&
90
+ !(rscGraph && modulesForFile(rscGraph, file)?.size)
91
+ );
92
+ }
93
+
94
+ /**
95
+ * Outcome of getOrCreateTempServer. `env` is the temp RSC environment on
96
+ * success, else null with `error` carrying WHY the create/import failed — or
97
+ * null when createServer resolved cleanly but attached no runner (terminal, but
98
+ * not an exception). The dev /__rsc_shell endpoint runs `error` through the
99
+ * SAME reoptimization classifier the import sites use: only a transient Vite
100
+ * re-optimization is signalled NOT-READY (client re-polls); every terminal
101
+ * failure fails fast so the read-through MISSes immediately instead of
102
+ * re-polling a permanently-broken realm for the full readiness deadline
103
+ * (issue #719 P2).
104
+ */
105
+ type TempServerResult = { env: any; error: unknown };
106
+
107
+ /**
108
+ * Test-only one-shot boot-race injection (issue #719 P3). When
109
+ * RANGO_E2E_INJECT_SHELL_NOTREADY=1, the dev /__rsc_shell endpoint emits a
110
+ * single reoptimization-class NOT-READY per pathname before serving, so an e2e
111
+ * can drive the REAL endpoint + real client re-poll deterministically — a
112
+ * natural cold race settles too fast on quick machines to guard the regression.
113
+ * Keyed per pathname so the read-through's re-poll finds it already fired and
114
+ * gets the HIT. Never engaged without the env flag.
115
+ */
116
+ const injectedShellNotReadyPaths = new Set<string>();
117
+
118
+ // Dev: an invalid transition({ when }) is a definition error the user must
119
+ // see in the browser too, as the Vite error overlay. The overlay does not
120
+ // survive on its own: a reload clears it, and plugin-rsc closes every
121
+ // overlay on each "rsc:update" (the edit's own, the gen-file write's), each
122
+ // followed by the client's RSC refetch. So until a discovery succeeds the
123
+ // pending error (s.transitionWhenOverlay) is re-sent to every client that
124
+ // connects and after every request the dev server answers (devServerPhase).
125
+ function sendTransitionWhenOverlay(s: DiscoveryState): void {
126
+ if (!s.transitionWhenOverlay) return;
127
+ (s.devServer?.environments as any)?.client?.hot?.send({
128
+ type: "error",
129
+ err: s.transitionWhenOverlay,
130
+ });
131
+ }
132
+
133
+ function showTransitionWhenError(
134
+ s: DiscoveryState,
135
+ err: unknown,
136
+ ): Error | undefined {
137
+ const whenError = findTransitionWhenError(err);
138
+ if (!whenError) return undefined;
139
+ s.transitionWhenOverlay = {
140
+ message: whenError.message,
141
+ stack: whenError.stack ?? "",
142
+ plugin: "@rangojs/router",
143
+ };
144
+ sendTransitionWhenOverlay(s);
145
+ return whenError;
146
+ }
147
+
148
+ /**
149
+ * configureServer. Dev mode: discover routers and populate manifest in
150
+ * memory. Skipped in build mode (buildDiscoveryPhase handles it).
151
+ */
152
+ export function devServerPhase(s: DiscoveryState, server: ViteDevServer): void {
153
+ if (s.isBuildMode) return;
154
+ // Skip if this is a temp server created by buildStart
155
+ if ((globalThis as any).__rscRouterDiscoveryActive) return;
156
+ s.devServer = server;
157
+
158
+ (server.environments as any)?.client?.hot?.on?.(
159
+ "vite:client:connect",
160
+ (_payload: unknown, client: any) => {
161
+ if (s.transitionWhenOverlay) {
162
+ client?.send?.({ type: "error", err: s.transitionWhenOverlay });
163
+ }
164
+ },
165
+ );
166
+ // The http server's "request" event, not a middleware: plugin-rsc
167
+ // answers page and RSC requests before a middleware added here runs.
168
+ let overlayResendQueued = false;
169
+ server.httpServer?.on("request", (req, res) => {
170
+ // Documents and RSC fetches only (the refetch that follows each
171
+ // "rsc:update"), one send per burst.
172
+ const isPage =
173
+ req.url?.includes("_rsc") === true ||
174
+ req.headers.accept?.includes("text/html") === true;
175
+ if (s.transitionWhenOverlay && isPage && !overlayResendQueued) {
176
+ overlayResendQueued = true;
177
+ res.once("close", () => {
178
+ overlayResendQueued = false;
179
+ sendTransitionWhenOverlay(s);
180
+ });
181
+ }
182
+ });
183
+
184
+ let workerReadyEpoch: number | undefined;
185
+ const publishDevDiscoveryReady = (epoch: number) => {
186
+ if (epoch <= (workerReadyEpoch ?? -1)) return;
187
+ workerReadyEpoch = epoch;
188
+ (server.environments as any)?.client?.hot?.send({
189
+ type: "custom",
190
+ event: DEV_DISCOVERY_READY_EVENT,
191
+ data: { epoch },
192
+ });
193
+ debugDiscovery?.("hmr: workerd ready at epoch %d", epoch);
194
+ };
195
+ if (s.opts?.preset === "cloudflare") {
196
+ const registeredClientHotChannels = new Set<any>();
197
+ const registerDevDiscoveryHotChannels = () => {
198
+ const clientHot = (server.environments as any)?.client?.hot;
199
+ if (clientHot && !registeredClientHotChannels.has(clientHot)) {
200
+ registeredClientHotChannels.add(clientHot);
201
+ clientHot.on(
202
+ DEV_DISCOVERY_QUERY_EVENT,
203
+ (_payload: unknown, client: any) => {
204
+ if (workerReadyEpoch === undefined) return;
205
+ client.send(DEV_DISCOVERY_READY_EVENT, {
206
+ epoch: workerReadyEpoch,
207
+ });
208
+ },
209
+ );
210
+ }
211
+ debugDiscovery?.(
212
+ "hmr: dev discovery browser channel registered (client=%s)",
213
+ !!clientHot,
214
+ );
215
+ };
216
+
217
+ registerDevDiscoveryHotChannels();
218
+ if (server.httpServer && !server.httpServer.listening) {
219
+ server.httpServer.once("listening", registerDevDiscoveryHotChannels);
220
+ }
221
+ }
222
+
223
+ // Serve the internal-debug module no-cache: consumers resolve it into
224
+ // node_modules, where dev's immutable `?v=` caching pinned browsers to a
225
+ // stale baked INTERNAL_RANGO_DEBUG. See internalDebugNoCacheMiddleware.
226
+ server.middlewares.use(internalDebugNoCacheMiddleware());
227
+
228
+ // Discovery promise that the handler can await if requests arrive
229
+ // before discovery completes
230
+ let resolveDiscovery: () => void;
231
+ const discoveryPromise = new Promise<void>((resolve) => {
232
+ resolveDiscovery = resolve;
233
+ });
234
+
235
+ // Manifest-readiness gate + rediscovery scheduler.
236
+ // The virtual:rsc-router/routes-manifest module's `load()` hook
237
+ // awaits `s.discoveryDone`; the gate is reset on each discovery
238
+ // cycle so workerd's HMR reloads block until the new gen file is
239
+ // written. State machine + transitions are extracted into
240
+ // ./gate-state.ts and unit-tested there — see the
241
+ // module's JSDoc for the four-flag contract.
242
+ const gate = createDiscoveryGate(s, debugDiscovery);
243
+ const beginDiscoveryGate = gate.beginGate;
244
+ const resolveDiscoveryGate = gate.resolveGate;
245
+
246
+ // Compute dev server origin from resolved URLs (preferred) or config port (fallback).
247
+ // Called after discovery (or in the load hook) when the server may be listening.
248
+ const getDevServerOrigin = () =>
249
+ server.resolvedUrls?.local?.[0]?.replace(/\/$/, "") ||
250
+ `http://localhost:${server.config.server.port || 5173}`;
251
+ let devServerClosed = false;
252
+
253
+ // Shared temp server for Cloudflare dev (no module runner in workerd).
254
+ // Used by both discover() (route type generation) and the prerender
255
+ // middleware (on-demand prerender evaluation). Created lazily, closed on
256
+ // server shutdown.
257
+ let prerenderTempServer: any = null;
258
+ let prerenderNodeRegistry: Map<string, any> | null = null;
259
+
260
+ // Clean up the temporary server and build env when the dev server shuts down
261
+ server.httpServer?.on("close", () => {
262
+ devServerClosed = true;
263
+ if (prerenderTempServer) {
264
+ prerenderTempServer.close().catch(() => {});
265
+ prerenderTempServer = null;
266
+ }
267
+ releaseBuildEnv(s).catch(() => {});
268
+ });
269
+
270
+ // Mirror the build-path contract (buildDiscoveryPhase in
271
+ // build-discovery-phase.ts, which sets
272
+ // __rscRouterDiscoveryActive before running user modules):
273
+ // set __rscRouterDiscoveryActive before running user modules so any
274
+ // module-level router.reverse() calls return a placeholder instead
275
+ // of throwing. The temp Vite server's module runner has its own
276
+ // module context; the flag must be on globalThis to cross that
277
+ // boundary. Cleared in finally so the dev request handlers run with
278
+ // strict reverse() semantics afterwards.
279
+ async function importEntryAndRegistry(tempRscEnv: any): Promise<void> {
280
+ const flagAlreadySet = !!(globalThis as any).__rscRouterDiscoveryActive;
281
+ if (!flagAlreadySet) {
282
+ (globalThis as any).__rscRouterDiscoveryActive = true;
283
+ }
284
+ try {
285
+ debugDiscovery?.(
286
+ "importEntryAndRegistry: importing entry (flag=%s)",
287
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
288
+ );
289
+ await tempRscEnv.runner.import(s.resolvedEntryPath!);
290
+ debugDiscovery?.(
291
+ "importEntryAndRegistry: entry import OK, fetching RouterRegistry",
292
+ );
293
+ const serverMod = await tempRscEnv.runner.import(
294
+ "@rangojs/router/server",
295
+ );
296
+ prerenderNodeRegistry = serverMod.RouterRegistry;
297
+ debugDiscovery?.(
298
+ "importEntryAndRegistry: registry size=%d",
299
+ prerenderNodeRegistry?.size ?? 0,
300
+ );
301
+ } finally {
302
+ if (!flagAlreadySet) {
303
+ delete (globalThis as any).__rscRouterDiscoveryActive;
304
+ debugDiscovery?.(
305
+ "importEntryAndRegistry: cleared __rscRouterDiscoveryActive",
306
+ );
307
+ }
308
+ }
309
+ }
310
+
311
+ async function getOrCreateTempServer(): Promise<TempServerResult> {
312
+ // Reuse path: if a temp server is already alive, prefer reusing
313
+ // it over orphaning the existing instance and spinning up a new
314
+ // one. This handles two cases:
315
+ //
316
+ // 1. Steady-state cache hit (cold-start completed, registry
317
+ // cached) — return the env immediately.
318
+ // 2. Recovery from a failed refresh: refreshTempRscEnv() may
319
+ // have invalidated and nulled the registry, then thrown
320
+ // during importEntryAndRegistry. Without reuse, the next
321
+ // call would `createTempRscServer` and overwrite the
322
+ // handle, leaking the previous server. Try to re-import on
323
+ // the existing runner first; only if THAT fails do we
324
+ // close the orphan and create new.
325
+ if (prerenderTempServer) {
326
+ const existingEnv = (prerenderTempServer.environments as any)?.rsc;
327
+ if (existingEnv?.runner) {
328
+ if (prerenderNodeRegistry) {
329
+ debugDiscovery?.("getOrCreateTempServer: cached temp runner reused");
330
+ return { env: existingEnv, error: null };
331
+ }
332
+ // Server alive but registry missing — likely after a prior
333
+ // refresh's invalidate + import threw. Try to re-import.
334
+ debugDiscovery?.(
335
+ "getOrCreateTempServer: server alive but registry missing — re-importing",
336
+ );
337
+ try {
338
+ await importEntryAndRegistry(existingEnv);
339
+ return { env: existingEnv, error: null };
340
+ } catch (err: any) {
341
+ debugDiscovery?.(
342
+ "getOrCreateTempServer: reuse import failed (%s) — closing orphan and creating fresh",
343
+ err?.message ?? String(err),
344
+ );
345
+ await prerenderTempServer.close().catch(() => {});
346
+ prerenderTempServer = null;
347
+ prerenderNodeRegistry = null;
348
+ // Fall through to create-new path below.
349
+ }
350
+ } else {
351
+ // Server reference exists but its rsc env is unhealthy
352
+ // (no runner). Close and recreate.
353
+ debugDiscovery?.(
354
+ "getOrCreateTempServer: existing server has no rsc.runner — closing and recreating",
355
+ );
356
+ await prerenderTempServer.close().catch(() => {});
357
+ prerenderTempServer = null;
358
+ prerenderNodeRegistry = null;
359
+ }
360
+ }
361
+
362
+ // Create path: no existing temp server (or just nullified above).
363
+ debugDiscovery?.(
364
+ "getOrCreateTempServer: creating new temp server, entry=%s",
365
+ s.resolvedEntryPath ?? "(unset)",
366
+ );
367
+ // Surface the create/import cause to the caller (issue #719 P2): a
368
+ // transient re-optimization is re-pollable, a terminal fault is not. A
369
+ // clean createServer that yields no runner leaves this null — terminal,
370
+ // but not an exception.
371
+ let createError: unknown = null;
372
+ try {
373
+ prerenderTempServer = await createTempRscServer(s, {
374
+ cacheDir: "node_modules/.vite_prerender",
375
+ // The dev /__rsc_shell endpoint drives captureShellHTML in this
376
+ // server's SSR realm; the entry is only imported when a shell
377
+ // capture runs, so discovery cost is unchanged.
378
+ realSsrEntry: true,
379
+ });
380
+
381
+ const tempRscEnv = (prerenderTempServer.environments as any)?.rsc;
382
+ if (tempRscEnv?.runner) {
383
+ await importEntryAndRegistry(tempRscEnv);
384
+ return { env: tempRscEnv, error: null };
385
+ }
386
+ debugDiscovery?.("getOrCreateTempServer: tempRscEnv.runner unavailable");
387
+ } catch (err: any) {
388
+ createError = err;
389
+ debugDiscovery?.("getOrCreateTempServer: FAILED message=%s", err.message);
390
+ console.warn(`[rango] Failed to create temp runner: ${err.message}`);
391
+ }
392
+ // Reached only on failure (runner unavailable, or create/import threw
393
+ // AFTER the server was created). Close the just-created server so a
394
+ // failed discovery does not leak it until the next call or dev shutdown,
395
+ // and null the refs so the reuse path above starts clean. Mirrors the
396
+ // close pattern used when an existing server is discarded (above).
397
+ await prerenderTempServer?.close().catch(() => {});
398
+ prerenderTempServer = null;
399
+ prerenderNodeRegistry = null;
400
+ return { env: null, error: createError };
401
+ }
402
+
403
+ // Clear the package-level singleton registries that survive a Vite
404
+ // moduleGraph.invalidateAll(). createRouter() / createHostRouter()
405
+ // call .set(id, ...) on these Maps; for "router removed" or
406
+ // "router id changed" edits, the OLD entry would persist after
407
+ // re-import without an explicit .clear(), leaving ghost routes
408
+ // in discoverRouters' output.
409
+ //
410
+ // We import the same module the runner imports, so the .clear()
411
+ // here mutates the same Map the freshly re-imported entry will
412
+ // populate.
413
+ async function clearTempRegistries(tempRscEnv: any): Promise<void> {
414
+ try {
415
+ const serverMod = await tempRscEnv.runner.import(
416
+ "@rangojs/router/server",
417
+ );
418
+ if (typeof serverMod?.RouterRegistry?.clear === "function") {
419
+ serverMod.RouterRegistry.clear();
420
+ }
421
+ if (typeof serverMod?.HostRouterRegistry?.clear === "function") {
422
+ serverMod.HostRouterRegistry.clear();
423
+ }
424
+ debugDiscovery?.(
425
+ "clearTempRegistries: cleared RouterRegistry + HostRouterRegistry",
426
+ );
427
+ } catch (err: any) {
428
+ // Non-fatal: if the import fails here, importEntryAndRegistry
429
+ // below will fail loudly with the same root cause and the
430
+ // caller will surface it.
431
+ debugDiscovery?.(
432
+ "clearTempRegistries: import @rangojs/router/server failed (%s)",
433
+ err?.message ?? String(err),
434
+ );
435
+ }
436
+ }
437
+
438
+ // HMR refresh: keep the temp Vite server alive across HMR cycles and
439
+ // invalidate its module graph instead of close+recreate. Closing the
440
+ // temp server during workerd's first post-cold-start module-fetch
441
+ // window disrupted the main dev server's transport — the user-visible
442
+ // symptom was a `transport was disconnected, cannot call "fetchModule"`
443
+ // error on the first urls.tsx edit (workerd's cache was cold, so its
444
+ // eval was still in flight when our close() ran). Module-graph
445
+ // invalidation is the architecturally cleaner refresh: same Vite
446
+ // instance, same transport, fresh source.
447
+ //
448
+ // Falls back to close+recreate when neither the env-level nor
449
+ // server-level moduleGraph exposes invalidateAll() (defensive — Vite
450
+ // versions / preset configurations may differ in which graph carries
451
+ // the module-runner cache).
452
+ async function refreshTempRscEnv(): Promise<any | null> {
453
+ const tempRscEnv = (await getOrCreateTempServer()).env;
454
+ if (!tempRscEnv) return null;
455
+
456
+ // Module-runner cache is on the per-environment graph in Vite 6+;
457
+ // older / non-environments setups carry it on the server graph.
458
+ // Try env first, server second.
459
+ const envGraph = (tempRscEnv as any).moduleGraph;
460
+ const serverGraph = (prerenderTempServer as any)?.moduleGraph;
461
+ const target = envGraph?.invalidateAll
462
+ ? envGraph
463
+ : serverGraph?.invalidateAll
464
+ ? serverGraph
465
+ : null;
466
+
467
+ if (!target) {
468
+ // No invalidate method available — fall back to close+recreate.
469
+ // This preserves the previous behavior in case a Vite version
470
+ // doesn't expose invalidateAll on either graph.
471
+ debugDiscovery?.(
472
+ "refreshTempRscEnv: invalidateAll unavailable on env+server graphs, falling back to close+recreate",
473
+ );
474
+ if (prerenderTempServer) {
475
+ await prerenderTempServer.close().catch(() => {});
476
+ prerenderTempServer = null;
477
+ prerenderNodeRegistry = null;
478
+ }
479
+ return (await getOrCreateTempServer()).env;
480
+ }
481
+
482
+ debugDiscovery?.(
483
+ "refreshTempRscEnv: invalidating module graph (%s)",
484
+ envGraph?.invalidateAll ? "env" : "server",
485
+ );
486
+ target.invalidateAll();
487
+ // Drop the cached registry so importEntryAndRegistry re-reads it
488
+ // through the now-invalidated module runner.
489
+ prerenderNodeRegistry = null;
490
+ // Clear singleton Maps that Vite's moduleGraph invalidation can't
491
+ // reach (RouterRegistry / HostRouterRegistry). Without this, an
492
+ // edit that REMOVES a createRouter() call or CHANGES a router id
493
+ // would leave the old entry in the registry, and discoverRouters
494
+ // would still emit its routes alongside whatever the new source
495
+ // declares.
496
+ await clearTempRegistries(tempRscEnv);
497
+ await importEntryAndRegistry(tempRscEnv);
498
+ return tempRscEnv;
499
+ }
500
+
501
+ // Surface a discovery failure on either dev path (Node RSC runner or the
502
+ // Cloudflare temp Node server). `hashBefore`/`hashAfter` are the discovering
503
+ // environment's dep-optimizer browserHash snapshots: a change across the
504
+ // attempt means a reload-causing re-optimization landed mid-flight, so an
505
+ // empty registry was the transient race (downgraded to a warning) rather
506
+ // than a genuine misconfig (loud, actionable error). Shared so both catch
507
+ // sites frame the same failure identically.
508
+ const emitDiscoveryFailure = (
509
+ err: unknown,
510
+ hashBefore: string | undefined,
511
+ hashAfter: string | undefined,
512
+ ): void => {
513
+ const reoptimizeObserved =
514
+ hashBefore !== undefined &&
515
+ hashAfter !== undefined &&
516
+ hashBefore !== hashAfter;
517
+ const report = describeDiscoveryFailure(err, { reoptimizeObserved });
518
+ if (report.level === "warn") {
519
+ console.warn(report.message);
520
+ } else {
521
+ console.error(report.message);
522
+ }
523
+ showTransitionWhenError(s, err);
524
+ };
525
+
526
+ const discover = async () => {
527
+ const discoverStart = performance.now();
528
+ const rscEnv = (server.environments as any)?.rsc;
529
+ if (!rscEnv?.runner) {
530
+ // Cloudflare dev: no module runner available (workerd-based RSC env).
531
+ // Set devServerOrigin so the virtual module can inject __PRERENDER_DEV_URL
532
+ // for on-demand prerender via the /__rsc_prerender endpoint.
533
+ debugDiscovery?.(
534
+ "dev: cloudflare path start, __rscRouterDiscoveryActive=%s",
535
+ (globalThis as any).__rscRouterDiscoveryActive ?? false,
536
+ );
537
+ s.devServerOrigin = getDevServerOrigin();
538
+ // The temp Node realm below shares this globalThis and runs the dev
539
+ // /__rsc_shell capture, which must replay the prerender store as
540
+ // the worker's HIT does: a capture that renders the Prerender
541
+ // handler live stores a doc record the HIT never reads, and the
542
+ // HIT loses the loader pushes its prelude rendered (#1057). That
543
+ // realm never evaluates the virtual module that sets this on the
544
+ // Node preset.
545
+ globalThis.__PRERENDER_DEV_URL = s.devServerOrigin;
546
+
547
+ // Create a temp Node.js server to run runtime discovery and generate
548
+ // named route types (static parser can't resolve factory calls).
549
+ // The temp server is a separate Vite instance with its own dep
550
+ // optimizer; snapshot ITS browserHash (hoisted so the catch can tell a
551
+ // transient re-optimization apart from a genuine empty registry, the
552
+ // same way the Node path below does).
553
+ let tempRscEnv: any;
554
+ let optimizerHashBefore: string | undefined;
555
+ try {
556
+ // Acquire build-time env bindings for dev prerender
557
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
558
+ acquireBuildEnv(s, s.viteCommand, s.viteMode),
559
+ );
560
+
561
+ const temp = await timed(debugDiscovery, "getOrCreateTempServer", () =>
562
+ getOrCreateTempServer(),
563
+ );
564
+ tempRscEnv = temp.env;
565
+ if (!tempRscEnv) {
566
+ // Recovery mode, as in the catch below. getOrCreateTempServer
567
+ // already logged why the temp runner failed.
568
+ recordDiscoveryFailure(
569
+ s,
570
+ temp.error ?? "temp runner unavailable for discovery",
571
+ );
572
+ } else {
573
+ optimizerHashBefore = tempRscEnv.depsOptimizer?.metadata?.browserHash;
574
+ await timed(debugDiscovery, "discoverRouters (cloudflare)", () =>
575
+ discoverRouters(
576
+ s,
577
+ tempRscEnv,
578
+ (prerenderTempServer?.environments as any)?.ssr,
579
+ ),
580
+ );
581
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
582
+ writeRouteTypesFiles(s),
583
+ );
584
+ }
585
+ } catch (err: any) {
586
+ recordDiscoveryFailure(s, err);
587
+ emitDiscoveryFailure(
588
+ err,
589
+ optimizerHashBefore,
590
+ tempRscEnv?.depsOptimizer?.metadata?.browserHash,
591
+ );
592
+ }
593
+
594
+ debugDiscovery?.(
595
+ "dev discovery done (%sms)",
596
+ (performance.now() - discoverStart).toFixed(1),
597
+ );
598
+ resolveDiscovery!();
599
+ return;
600
+ }
601
+
602
+ // Snapshot the dep-optimizer hash before discovery so the catch can tell
603
+ // a transient re-optimization race apart from a genuine empty registry.
604
+ // A reload-causing re-optimization regenerates browserHash; if it changed
605
+ // across the attempt, an empty read was almost certainly the race below.
606
+ const optimizerHashBefore: string | undefined =
607
+ rscEnv.depsOptimizer?.metadata?.browserHash;
608
+
609
+ try {
610
+ // Acquire build-time env bindings for dev prerender (Node.js path)
611
+ debugDiscovery?.("dev: node path start");
612
+ await timed(debugDiscovery, "acquireBuildEnv", () =>
613
+ acquireBuildEnv(s, s.viteCommand, s.viteMode),
614
+ );
615
+
616
+ // Discover routers FIRST, then arm the manifest-readiness gate on the
617
+ // server module discovery actually read the registry from.
618
+ //
619
+ // We deliberately do NOT pre-import "@rangojs/router/server" here to
620
+ // arm the gate early. During a Vite dependency re-optimization (dev
621
+ // boot after a lockfile change, or `vite dev --force`) or any runner
622
+ // full reload, a module imported before the entry can be a stale copy
623
+ // of the runner's module graph: createRouter() populates RouterRegistry
624
+ // on the fresh copy and the stale one reads an empty Map, a spurious
625
+ // "No routers found" (#637). discoverRouters returns the instance it
626
+ // read the registry from and verified the runner still serves (it
627
+ // redoes a pass that a reload split). The virtual manifest module's
628
+ // own gate (s.discoveryDone, armed by beginDiscoveryGate) already
629
+ // blocks early requests during discovery on the Node path, so arming
630
+ // manifestReadyPromise after discovery is sufficient here.
631
+ const serverMod = await timed(debugDiscovery, "discoverRouters", () =>
632
+ discoverRouters(s, rscEnv, (server.environments as any)?.ssr),
633
+ );
634
+ if (serverMod?.setManifestReadyPromise) {
635
+ serverMod.setManifestReadyPromise(discoveryPromise);
636
+ }
637
+
638
+ // Store server origin for dev prerender endpoint (virtual module injection)
639
+ s.devServerOrigin = getDevServerOrigin();
640
+
641
+ // Update named-routes.gen.ts from runtime discovery.
642
+ // The runtime manifest is the source of truth: it evaluates dynamic
643
+ // routes (e.g. Array.from loops) that the static parser cannot see.
644
+ // writeRouteTypesFiles() only writes when content changes, so this
645
+ // won't cause unnecessary HMR triggers.
646
+ timedSync(debugDiscovery, "writeRouteTypesFiles", () =>
647
+ writeRouteTypesFiles(s),
648
+ );
649
+
650
+ // Populate the route map and per-router data in the RSC env
651
+ await timed(debugDiscovery, "propagateDiscoveryState", () =>
652
+ propagateDiscoveryState(rscEnv),
653
+ );
654
+ } catch (err: any) {
655
+ // Recovery mode: the next in-scan source change re-runs discovery
656
+ // (canRefreshRuntimeDiscovery) instead of waiting for a restart.
657
+ recordDiscoveryFailure(s, err);
658
+ emitDiscoveryFailure(
659
+ err,
660
+ optimizerHashBefore,
661
+ rscEnv.depsOptimizer?.metadata?.browserHash,
662
+ );
663
+ } finally {
664
+ debugDiscovery?.(
665
+ "dev discovery done (%sms)",
666
+ (performance.now() - discoverStart).toFixed(1),
667
+ );
668
+ resolveDiscovery!();
669
+ }
670
+ };
671
+
672
+ // Schedule after all plugins have finished configureServer.
673
+ // The gate (s.discoveryDone) is reset via beginDiscoveryGate() and
674
+ // resolved when discover() finishes, so the virtual manifest module's
675
+ // load() awaits the populated state.
676
+ beginDiscoveryGate();
677
+ setTimeout(
678
+ () => discover().then(resolveDiscoveryGate, resolveDiscoveryGate),
679
+ 0,
680
+ );
681
+
682
+ // Dev-mode on-demand prerender endpoint.
683
+ // When workerd hits a prerender route, it fetches this endpoint instead of
684
+ // trying to run node:fs-dependent handlers in the Cloudflare environment.
685
+ //
686
+ // Node.js preset: uses the main server's RSC environment directly (router
687
+ // instances are already discovered and have matchForPrerender).
688
+ // Cloudflare preset: lazily creates a Node.js temp server because the main
689
+ // RSC environment uses workerd where node:fs can't access the host filesystem.
690
+
691
+ // Registry from the main server's RSC environment (populated by discoverRouters)
692
+ let mainRegistry: Map<string, any> | null = null;
693
+
694
+ // Memoized /__rsc_prerender render results, keyed by router-instance
695
+ // identity (#654). The per-request entry re-import below is what makes
696
+ // identity a valid freshness key: an HMR-invalidated chain re-runs
697
+ // createRouter() and replaces the registry instance, so cached bodies
698
+ // for the old instance become unreachable; an untouched chain returns
699
+ // the same instance and the cached body is byte-identical to a fresh
700
+ // render. See dev-prerender-cache.ts for the full invariant.
701
+ const devPrerenderCache = createDevPrerenderCache();
702
+
703
+ // Push discovery state (manifest, trie, precomputed entries) to the
704
+ // server module so runtime request handling uses the current routes.
705
+ // Shared by initial discovery and HMR-triggered re-discovery.
706
+ const propagateDiscoveryState = async (rscEnv: any) => {
707
+ const serverMod = await rscEnv.runner.import("@rangojs/router/server");
708
+ if (!serverMod) return;
709
+ // Clear stale per-router and global route data before repopulating.
710
+ // Without this, removed routers/routes survive in the per-router maps
711
+ // and shrunk precomputed entries or tries are never purged.
712
+ if (serverMod.clearAllRouterData) {
713
+ serverMod.clearAllRouterData();
714
+ }
715
+ mainRegistry = serverMod.RouterRegistry ?? null;
716
+ if (s.mergedRouteManifest && serverMod.setCachedManifest) {
717
+ serverMod.setCachedManifest(s.mergedRouteManifest);
718
+ }
719
+ const perRouterSetters: Array<[Map<string, any>, string]> = [
720
+ [s.perRouterManifestDataMap, "setRouterManifest"],
721
+ [s.perRouterTrieMap, "setRouterTrie"],
722
+ [s.perRouterPrecomputedMap, "setRouterPrecomputedEntries"],
723
+ ];
724
+ for (const [map, fn] of perRouterSetters) {
725
+ const setter = serverMod[fn];
726
+ if (typeof setter !== "function") continue;
727
+ for (const [routerId, value] of map) setter(routerId, value);
728
+ }
729
+ };
730
+
731
+ server.middlewares.use("/__rsc_prerender", async (req: any, res: any) => {
732
+ const reqStart = debugDev ? performance.now() : 0;
733
+ const logResult = (status: number, note: string) => {
734
+ debugDev?.(
735
+ "/__rsc_prerender %s -> %d %s (%sms)",
736
+ req.url,
737
+ status,
738
+ note,
739
+ (performance.now() - reqStart).toFixed(1),
740
+ );
741
+ };
742
+
743
+ if (s.discoveryDone) await s.discoveryDone;
744
+
745
+ const url = new URL(req.url || "/", "http://localhost");
746
+ const pathname = url.searchParams.get("pathname");
747
+ if (!pathname) {
748
+ res.statusCode = 400;
749
+ res.end("Missing pathname");
750
+ logResult(400, "missing pathname");
751
+ return;
752
+ }
753
+
754
+ // Import the user's entry module to force re-evaluation of any
755
+ // HMR-invalidated modules in the chain (entry → router → urls → handlers).
756
+ // This ensures createRouter() re-runs with updated handler code before
757
+ // we read RouterRegistry. Without this, edits to prerender handler files
758
+ // produce stale content because the old router instance remains registered.
759
+ const rscEnv = (server.environments as any)?.rsc;
760
+ let registry: Map<string, any> | null = null;
761
+ if (rscEnv?.runner && s.resolvedEntryPath) {
762
+ try {
763
+ await rscEnv.runner.import(s.resolvedEntryPath);
764
+ const serverMod = await rscEnv.runner.import("@rangojs/router/server");
765
+ registry = serverMod.RouterRegistry ?? null;
766
+ } catch (err: any) {
767
+ console.warn(
768
+ `[rango] Dev prerender module refresh failed: ${err.message}`,
769
+ );
770
+ res.statusCode = 500;
771
+ res.end(`Prerender handler error: ${err.message}`);
772
+ logResult(500, "module refresh failed");
773
+ return;
774
+ }
775
+ } else {
776
+ registry = mainRegistry;
777
+ }
778
+
779
+ if (!registry) {
780
+ // No main registry: the RSC env has no module runner (Cloudflare dev).
781
+ // Lazily create a Node.js temp server for prerender evaluation, and
782
+ // re-import the entry through it on EVERY request — the temp server
783
+ // has its own file watcher, so a handler-only edit (a file without
784
+ // urls()/createRouter() that the main watcher's route-file sniff
785
+ // ignores) invalidates its module graph; the re-import re-evaluates
786
+ // exactly the dirty subgraph and re-registers fresh router
787
+ // instances. Before #654 the cached registry was only refreshed on
788
+ // route-file edits, so handler-only edits served stale prerender
789
+ // content on this path. Warm-cache re-imports are module-cache hits.
790
+ const tempRscEnv = (await getOrCreateTempServer()).env;
791
+ if (tempRscEnv) {
792
+ try {
793
+ await importEntryAndRegistry(tempRscEnv);
794
+ } catch (err: any) {
795
+ console.warn(
796
+ `[rango] Dev prerender module refresh failed: ${err.message}`,
797
+ );
798
+ res.statusCode = 500;
799
+ res.end(`Prerender handler error: ${err.message}`);
800
+ logResult(500, "temp module refresh failed");
801
+ return;
802
+ }
803
+ }
804
+ registry = prerenderNodeRegistry;
805
+ }
806
+
807
+ if (!registry || registry.size === 0) {
808
+ res.statusCode = 503;
809
+ res.end("Prerender runner not available");
810
+ logResult(503, "no registry");
811
+ return;
812
+ }
813
+
814
+ const wantIntercept = url.searchParams.get("intercept") === "1";
815
+ const wantRouteName = url.searchParams.get("routeName");
816
+ const wantPassthrough = url.searchParams.get("passthrough") === "1";
817
+
818
+ // One render warms BOTH variant keys (matchForPrerender computes the
819
+ // intercept segments unconditionally), so a route's main and modal
820
+ // variants cost a single render per HMR generation.
821
+ const variantDims = {
822
+ passthrough: wantPassthrough,
823
+ routeName: wantRouteName,
824
+ };
825
+ const keyMain = devPrerenderCacheKey(pathname, {
826
+ intercept: false,
827
+ ...variantDims,
828
+ });
829
+ const keyIntercept = devPrerenderCacheKey(pathname, {
830
+ intercept: true,
831
+ ...variantDims,
832
+ });
833
+ const requestedKey = wantIntercept ? keyIntercept : keyMain;
834
+
835
+ for (const [, routerInstance] of registry) {
836
+ if (!routerInstance.matchForPrerender) continue;
837
+ // Cache is consulted per router IN LOOP ORDER so multi-router
838
+ // fall-through semantics are identical to the uncached path: a
839
+ // router that never produced a payload for this key still runs
840
+ // its matchForPrerender (cheap trie miss / intentionally-uncached
841
+ // error retry) before the next router is considered.
842
+ const cached = devPrerenderCache.get(routerInstance, requestedKey);
843
+ if (cached !== undefined) {
844
+ res.setHeader("content-type", "application/json");
845
+ res.setHeader("x-rango-prerender-cache", "HIT");
846
+ res.end(cached);
847
+ logResult(200, "cache hit");
848
+ return;
849
+ }
850
+ try {
851
+ const result = await routerInstance.matchForPrerender(
852
+ pathname,
853
+ {},
854
+ undefined,
855
+ wantPassthrough,
856
+ s.resolvedBuildEnv,
857
+ true, // devMode: check getParams for passthrough routes
858
+ );
859
+ if (!result) continue;
860
+ if (result.passthrough) continue;
861
+ // When routeName is specified, only accept a match for that route.
862
+ // This prevents returning the wrong entry when multiple routers
863
+ // have prerenderable routes sharing the same pathname.
864
+ if (wantRouteName && result.routeName !== wantRouteName) continue;
865
+ // The pre-encoded handle string in the intercept body comes
866
+ // from the producer (handles are Flight-encoded so
867
+ // Promise/ReactNode values survive the wire).
868
+ const bodies = payloadBodiesFromResult(result);
869
+ devPrerenderCache.set(routerInstance, keyMain, bodies.main);
870
+ devPrerenderCache.set(routerInstance, keyIntercept, bodies.intercept);
871
+ res.setHeader("content-type", "application/json");
872
+ res.setHeader("x-rango-prerender-cache", "MISS");
873
+ res.end(wantIntercept ? bodies.intercept : bodies.main);
874
+ logResult(200, `match ${result.routeName}`);
875
+ return;
876
+ } catch (err: any) {
877
+ // matchForPrerender now re-throws render failures instead of baking
878
+ // an error page (issue #587). In dev there is no frozen artifact, so
879
+ // we fall through (404 -> live handler). A `throw new Skip()` is the
880
+ // expected "skip this URL" signal, not a failure, so it stays quiet.
881
+ if (err?.name !== "Skip") {
882
+ console.warn(
883
+ `[rango] Dev prerender error for ${pathname} (serving live instead): ${err.message}`,
884
+ );
885
+ }
886
+ }
887
+ }
888
+
889
+ res.statusCode = 404;
890
+ res.end("No prerender match");
891
+ logResult(404, "no match");
892
+ });
893
+
894
+ // Dev on-demand PPR shell production (producer B, #699). There is no
895
+ // build manifest in dev, so the serve path's read-through
896
+ // (rsc/shell-build-manifest.ts) fetches the shell entry from here on a
897
+ // Prerender+ppr route's first request — dev serves x-rango-shell: HIT
898
+ // from request one, mirroring production. Memoized per router HMR
899
+ // generation AND per caller version (a client-module edit bumps the
900
+ // version without rotating the router instance; the stale entry would
901
+ // fail the serve gate forever). The endpoint is policy-free: the caller
902
+ // (the serve gate, which resolved the route's ppr option) sends
903
+ // ttl/swr/tags/version. Only prerender-backed routes produce entries —
904
+ // the /__rsc_prerender pre-flight below both warms the payload memo the
905
+ // capture's dev store fetch will hit AND refuses non-prerenderable
906
+ // routes (a live-handler render must never be served as a baked shell).
907
+ server.middlewares.use("/__rsc_shell", async (req: any, res: any) => {
908
+ await s.discoveryDone;
909
+ const url = new URL(req.url ?? "", "http://localhost");
910
+ const pathname = url.searchParams.get("pathname");
911
+ const routeName = url.searchParams.get("routeName");
912
+ const version = url.searchParams.get("version");
913
+ // ttl is required like the identifiers: the endpoint is policy-free
914
+ // (the serve gate resolved the route's ppr option and always sends
915
+ // it), so there is deliberately no default to drift from
916
+ // resolvePprConfig's.
917
+ const ttlRaw = url.searchParams.get("ttl");
918
+ if (!pathname || !routeName || !version || !ttlRaw) {
919
+ res.statusCode = 400;
920
+ res.end("Missing pathname/routeName/version/ttl");
921
+ return;
922
+ }
923
+
924
+ // Boot-race readiness signal (issue #719): the capture realm is stood
925
+ // up lazily on the first hit (temp server, registry import, and a Vite
926
+ // dep re-optimization the first shell-capture import can trigger). All
927
+ // are TRANSIENT — a retry seconds later succeeds. Tagging them 503 +
928
+ // x-rango-shell-dev: NOT-READY lets the read-through re-poll ONLY these
929
+ // (a bounded await of readiness) instead of mapping the boot window to
930
+ // a hard first-request MISS. Genuine negatives (404) stay untagged so a
931
+ // non-baked route never stalls the foreground.
932
+ const sendNotReady = (detail: string): void => {
933
+ res.statusCode = 503;
934
+ res.setHeader("x-rango-shell-dev", "NOT-READY");
935
+ res.end(detail);
936
+ };
937
+ // A Vite dependency re-optimization surfaces as ERR_OUTDATED_OPTIMIZED_DEP
938
+ // (import throws once, then re-imports clean) — retryable, unlike a real
939
+ // module fault (syntax error, missing export), which stays a hard 500.
940
+ // The message-regex fallback is NOT gratuitous: err.code is stripped when
941
+ // the error serializes across the module-runner/workerd RPC boundary (the
942
+ // message survives), so under the Cloudflare preset .code alone misses it.
943
+ const isReoptimizing = (err: any): boolean =>
944
+ err?.code === "ERR_OUTDATED_OPTIMIZED_DEP" ||
945
+ /Outdated Optimize Dep|optimized dependency|new dependencies optimized/i.test(
946
+ String(err?.message ?? ""),
947
+ );
948
+ // Fold the reoptimize-guard pasted at all three import/capture catch
949
+ // sites: emit NOT-READY + report handled for a transient re-optimization,
950
+ // else leave the caller to send its own terminal (500 for an entry
951
+ // import, 404 for a mid-capture failure that keeps runtime capture).
952
+ const handledAsReoptimizing = (err: any): boolean => {
953
+ if (!isReoptimizing(err)) return false;
954
+ sendNotReady(`Shell capture re-optimizing: ${err.message}`);
955
+ return true;
956
+ };
957
+ // Both entry-import sites (main-server rsc env, temp Node server) fail
958
+ // identically: reoptimize → NOT-READY, else → hard 500.
959
+ const handleShellImportError = (err: any): void => {
960
+ if (handledAsReoptimizing(err)) return;
961
+ res.statusCode = 500;
962
+ res.end(`Shell capture module refresh failed: ${err.message}`);
963
+ };
964
+ // Deterministic boot-race injection for e2e (issue #719 P3): fire ONE
965
+ // reopt-class NOT-READY per pathname through the REAL classifier so the
966
+ // read-through's re-poll path is exercised end-to-end (not just the
967
+ // unit-mocked fetch), then serve normally on the re-poll. Env-gated —
968
+ // inert in every non-test run.
969
+ if (
970
+ process.env.RANGO_E2E_INJECT_SHELL_NOTREADY === "1" &&
971
+ !injectedShellNotReadyPaths.has(pathname)
972
+ ) {
973
+ injectedShellNotReadyPaths.add(pathname);
974
+ const injected = Object.assign(
975
+ new Error("Outdated Optimize Dep (injected boot-race)"),
976
+ { code: "ERR_OUTDATED_OPTIMIZED_DEP" },
977
+ );
978
+ if (handledAsReoptimizing(injected)) return;
979
+ }
980
+ const ttl = Number(ttlRaw);
981
+ const swrRaw = url.searchParams.get("swr");
982
+ const swr = swrRaw === null ? undefined : Number(swrRaw);
983
+ const tagsRaw = url.searchParams.get("tags");
984
+ const tags = tagsRaw ? tagsRaw.split(",") : undefined;
985
+ const maxSnapshotBytesRaw = url.searchParams.get("maxSnapshotBytes");
986
+ const maxSnapshotBytes =
987
+ maxSnapshotBytesRaw === null ? undefined : Number(maxSnapshotBytesRaw);
988
+ // Boundary revalidation via the SHARED normalizer (shell-serve.ts):
989
+ // the param crossed an HTTP query string, and a garbage value must
990
+ // fall back to the capture default, never reach setTimeout as NaN
991
+ // (which Node clamps to ~1ms — an instant abort).
992
+ const captureTimeout = normalizeCaptureTimeout(
993
+ Number(url.searchParams.get("captureTimeout")),
994
+ );
995
+
996
+ // Resolve the capture realms: main-server envs (Node preset) or the
997
+ // shared temp Node server (Cloudflare preset — no main RSC runner).
998
+ // Entry re-import per request picks up HMR edits, exactly like the
999
+ // prerender endpoint above.
1000
+ const rscEnvMain = (server.environments as any)?.rsc;
1001
+ let rscRealm: any = null;
1002
+ let ssrRealm: any = null;
1003
+ let ssrEntryId: string;
1004
+ // Why the temp-server path returned no runner, if it did: a transient
1005
+ // re-optimization is re-pollable (NOT-READY), a terminal create/import
1006
+ // fault is not. Carried from getOrCreateTempServer to the readiness
1007
+ // check below so only reopt re-polls (issue #719 P2).
1008
+ let tempServerError: unknown = null;
1009
+ if (rscEnvMain?.runner && s.resolvedEntryPath) {
1010
+ try {
1011
+ await rscEnvMain.runner.import(s.resolvedEntryPath);
1012
+ } catch (err: any) {
1013
+ handleShellImportError(err);
1014
+ return;
1015
+ }
1016
+ rscRealm = rscEnvMain;
1017
+ ssrRealm = (server.environments as any)?.ssr;
1018
+ ssrEntryId =
1019
+ (server.environments as any)?.ssr?.config?.build?.rollupOptions?.input
1020
+ ?.index ?? VIRTUAL_IDS.ssr;
1021
+ } else {
1022
+ const tempResult = await getOrCreateTempServer();
1023
+ if (tempResult.env) {
1024
+ try {
1025
+ await importEntryAndRegistry(tempResult.env);
1026
+ } catch (err: any) {
1027
+ handleShellImportError(err);
1028
+ return;
1029
+ }
1030
+ } else {
1031
+ tempServerError = tempResult.error;
1032
+ }
1033
+ rscRealm = tempResult.env;
1034
+ ssrRealm = (prerenderTempServer?.environments as any)?.ssr;
1035
+ ssrEntryId = "virtual:entry-ssr";
1036
+ }
1037
+ if (!rscRealm?.runner || !ssrRealm?.runner) {
1038
+ // Reoptimization is the ONLY transient class: re-poll it (NOT-READY).
1039
+ // A terminal temp-server create/import fault, or an SSR runner absent
1040
+ // after a clean createServer, fails fast with a plain 503 (no
1041
+ // NOT-READY header) so the read-through MISSes on its first attempt
1042
+ // instead of re-polling a permanently-broken realm for the full
1043
+ // readiness deadline (issue #719 P2).
1044
+ if (tempServerError && handledAsReoptimizing(tempServerError)) return;
1045
+ res.statusCode = 503;
1046
+ res.end("Shell capture runners not available");
1047
+ return;
1048
+ }
1049
+ let registry: Map<string, any> | null = null;
1050
+ let registryError: unknown = null;
1051
+ try {
1052
+ const serverMod = await rscRealm.runner.import("@rangojs/router/server");
1053
+ registry = serverMod.RouterRegistry ?? null;
1054
+ } catch (err: any) {
1055
+ registryError = err;
1056
+ registry = null;
1057
+ }
1058
+ if (!registry || registry.size === 0) {
1059
+ // Same rule as the runner check: a re-optimization mid-import is
1060
+ // re-pollable (NOT-READY); a terminal import fault or a genuinely
1061
+ // empty registry (no routers registered) fails fast (issue #719 P2).
1062
+ if (registryError && handledAsReoptimizing(registryError)) return;
1063
+ res.statusCode = 503;
1064
+ res.end("Shell capture registry not available");
1065
+ return;
1066
+ }
1067
+
1068
+ // Memo sweep FIRST: after request one the common case is a memo HIT
1069
+ // (this fetch blocks a foreground document request), and the memoized
1070
+ // body needs neither the pre-flight round-trip nor a capture. Keyed
1071
+ // per router instance (= HMR generation) like the prerender memo.
1072
+ const cacheKey = `shell|${pathname}|r=${routeName}|t=${ttl}|s=${swr ?? ""}|g=${(tags ?? []).join("+")}|c=${captureTimeout ?? ""}|v=${version}`;
1073
+ for (const [, routerInstance] of registry) {
1074
+ if (typeof routerInstance.match !== "function") continue;
1075
+ const cached = devPrerenderCache.get(routerInstance, cacheKey);
1076
+ if (cached !== undefined) {
1077
+ res.setHeader("content-type", "application/json");
1078
+ res.setHeader("x-rango-shell-dev", "HIT");
1079
+ res.end(cached);
1080
+ return;
1081
+ }
1082
+ }
1083
+
1084
+ // Pre-flight: the route must be prerender-backed. Warms the payload
1085
+ // memo the capture's dev prerender store will fetch, and closes the
1086
+ // live-handler-bake hole (a non-pr route 404s here).
1087
+ if (s.devServerOrigin) {
1088
+ try {
1089
+ const probe = await fetch(
1090
+ `${s.devServerOrigin}/__rsc_prerender?pathname=${encodeURIComponent(pathname)}&routeName=${encodeURIComponent(routeName)}`,
1091
+ { signal: AbortSignal.timeout(DEV_SHELL_PROBE_TIMEOUT_MS) },
1092
+ );
1093
+ if (!probe.ok) {
1094
+ res.statusCode = 404;
1095
+ res.end("Route is not prerenderable");
1096
+ return;
1097
+ }
1098
+ } catch {
1099
+ res.statusCode = 404;
1100
+ res.end("Prerender pre-flight failed");
1101
+ return;
1102
+ }
1103
+ }
1104
+
1105
+ for (const [, routerInstance] of registry) {
1106
+ if (typeof routerInstance.match !== "function") continue;
1107
+ try {
1108
+ const ssrModule = await ssrRealm.runner.import(ssrEntryId);
1109
+ if (typeof ssrModule?.captureShellHTML !== "function") {
1110
+ res.statusCode = 404;
1111
+ res.end("SSR entry has no captureShellHTML");
1112
+ return;
1113
+ }
1114
+ const captureMod = await rscRealm.runner.import(
1115
+ "@rangojs/router/build/shell-capture",
1116
+ );
1117
+ const result = await captureMod.captureShellForBuild({
1118
+ router: routerInstance,
1119
+ urlPath: pathname,
1120
+ routeName,
1121
+ key: `${pathname}:shell`,
1122
+ ttl,
1123
+ swr,
1124
+ tags,
1125
+ maxSnapshotBytes,
1126
+ captureTimeout,
1127
+ buildEnv: s.resolvedBuildEnv,
1128
+ versions: uniformVersions(version),
1129
+ captureShellHTML: ssrModule.captureShellHTML,
1130
+ debug: !!debugDiscovery,
1131
+ });
1132
+ if (result.outcome === "route-mismatch") continue;
1133
+ if (result.outcome !== "stored" || !result.entry) {
1134
+ res.statusCode = 404;
1135
+ res.end(`Shell capture ${result.outcome}`);
1136
+ return;
1137
+ }
1138
+ const body = JSON.stringify({
1139
+ entry: result.entry,
1140
+ ttl,
1141
+ tags: result.tags,
1142
+ });
1143
+ devPrerenderCache.set(routerInstance, cacheKey, body);
1144
+ res.setHeader("content-type", "application/json");
1145
+ res.setHeader("x-rango-shell-dev", "MISS");
1146
+ res.end(body);
1147
+ return;
1148
+ } catch (err: any) {
1149
+ // A dep re-optimization mid-capture is a boot-race, not a capture
1150
+ // failure: signal NOT-READY so the read-through re-polls instead of
1151
+ // conceding a first-request MISS (issue #719).
1152
+ if (handledAsReoptimizing(err)) return;
1153
+ console.warn(
1154
+ `[rango] Dev shell capture error for ${pathname} (route keeps runtime capture): ${err.message}`,
1155
+ );
1156
+ res.statusCode = 404;
1157
+ res.end(`Shell capture error: ${err.message}`);
1158
+ return;
1159
+ }
1160
+ }
1161
+ res.statusCode = 404;
1162
+ res.end("No router matched");
1163
+ });
1164
+
1165
+ // Watch url module and router files for changes and regenerate named-routes.gen.ts.
1166
+ // Process files containing urls( or createRouter( to update the combined route map.
1167
+ if (s.opts?.staticRouteTypesGeneration !== false) {
1168
+ const isGeneratedRouteFile = (filePath: string): boolean =>
1169
+ filePath.endsWith(".gen.ts") &&
1170
+ (filePath.includes("named-routes.gen.ts") ||
1171
+ filePath.includes("urls.gen.ts"));
1172
+
1173
+ // Files no discovery scan reaches are ignored unless the RSC graph
1174
+ // loaded them (docs/manifests.md, "A reload no file of the app asked for").
1175
+ const isOutsideApp = (filePath: string): boolean =>
1176
+ isFileOutsideApp(
1177
+ s.projectRoot,
1178
+ filePath,
1179
+ (server.environments as any)?.rsc?.moduleGraph,
1180
+ );
1181
+
1182
+ const regenerateGeneratedRouteFiles = () => {
1183
+ if (s.perRouterManifests.length > 0) {
1184
+ writeRouteTypesFiles(s);
1185
+ } else {
1186
+ writeCombinedRouteTypesWithTracking(s);
1187
+ }
1188
+ };
1189
+ const routeShapeSignature = () =>
1190
+ JSON.stringify(
1191
+ s.perRouterManifests.map(
1192
+ ({ id, routeManifest, routeTrailingSlash, routeSearchSchemas }) => ({
1193
+ id,
1194
+ routeManifest,
1195
+ routeTrailingSlash,
1196
+ routeSearchSchemas,
1197
+ }),
1198
+ ),
1199
+ );
1200
+
1201
+ const maybeHandleGeneratedRouteFileMutation = (
1202
+ filePath: string,
1203
+ ): boolean => {
1204
+ if (!isGeneratedRouteFile(filePath)) return false;
1205
+ if (consumeSelfGenWrite(s, filePath)) return true;
1206
+ // In Cloudflare dev (no module runner), perRouterManifests is never
1207
+ // refreshed after HMR so regenerateGeneratedRouteFiles() would use
1208
+ // stale data and revert user edits. Source files own route state;
1209
+ // gen files are derived output. Skip regeneration and let the next
1210
+ // source-file change rebuild them from the static parser.
1211
+ const hasRunner = !!(server.environments as any)?.rsc?.runner;
1212
+ if (!hasRunner) return true;
1213
+ regenerateGeneratedRouteFiles();
1214
+ return true;
1215
+ };
1216
+
1217
+ // Debounce timer for batching rapid route-file changes (e.g. afterEach
1218
+ // restoring two files in quick succession). The cheap checks (extension,
1219
+ // scanFilter, content sniff) run synchronously to gate non-route files;
1220
+ // only the expensive regeneration is debounced.
1221
+ let routeChangeTimer: ReturnType<typeof setTimeout> | undefined;
1222
+
1223
+ // Drop the routes-manifest virtual module's cached transform so the
1224
+ // next runner evaluation regenerates it from current state.
1225
+ const invalidateRoutesManifestModule = (rscEnv: any) => {
1226
+ for (const virtualId of [
1227
+ VIRTUAL_ROUTES_MANIFEST_ID,
1228
+ `\0${VIRTUAL_ROUTES_MANIFEST_ID}`,
1229
+ ]) {
1230
+ const virtualMod = rscEnv.moduleGraph?.getModuleById?.(virtualId);
1231
+ if (virtualMod) rscEnv.moduleGraph.invalidateModule(virtualMod);
1232
+ }
1233
+ };
1234
+
1235
+ // Re-run runtime discovery so factory-generated routes that the
1236
+ // static parser cannot see are refreshed after source changes.
1237
+ // The state-machine concerns (queued/pending/gatePending) are
1238
+ // owned by the gate created above (./gate-state.ts).
1239
+ // Here we provide just the env-specific work.
1240
+ const refreshRuntimeDiscovery = async () => {
1241
+ const rscEnv = (server.environments as any)?.rsc;
1242
+ const hasMainRunner = !!rscEnv?.runner;
1243
+ let previousRouteShape = routeShapeSignature();
1244
+ await gate.runRefreshCycle(async () => {
1245
+ const hmrStart = performance.now();
1246
+ try {
1247
+ if (hasMainRunner) {
1248
+ const recoveringColdStart = s.perRouterManifests.length === 0;
1249
+ await timed(debugDiscovery, "hmr discoverRouters", () =>
1250
+ discoverRouters(s, rscEnv, (server.environments as any)?.ssr),
1251
+ );
1252
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1253
+ writeRouteTypesFiles(s),
1254
+ );
1255
+ await timed(debugDiscovery, "hmr propagateDiscoveryState", () =>
1256
+ propagateDiscoveryState(rscEnv),
1257
+ );
1258
+ // The manifest module emitted after a failed cold discovery has
1259
+ // no gen-file import, so no gen write ever invalidates it.
1260
+ if (recoveringColdStart) invalidateRoutesManifestModule(rscEnv);
1261
+ } else {
1262
+ // Cloudflare HMR has no main RSC runner (workerd is a separate
1263
+ // runtime): re-discover on the temp Node runner. Invalidate its
1264
+ // RSC module graph (or close+recreate as a fallback) so the
1265
+ // runner re-reads the freshly edited source. Keeping the same
1266
+ // Vite instance alive avoids disrupting workerd's transport
1267
+ // during the first post-cold-start module-fetch window. After
1268
+ // a cold start whose temp runner failed there is none, and
1269
+ // getOrCreateTempServer creates one. A recovering cycle needs
1270
+ // no routes-manifest invalidation here: the worker reload below
1271
+ // invalidates its whole module graph.
1272
+ const tempRscEnv = await timed(
1273
+ debugDiscovery,
1274
+ "hmr refreshTempRscEnv (cloudflare)",
1275
+ () => refreshTempRscEnv(),
1276
+ );
1277
+ if (!tempRscEnv) {
1278
+ throw new Error(
1279
+ "temp runner unavailable for cloudflare HMR rediscovery",
1280
+ );
1281
+ }
1282
+ await timed(
1283
+ debugDiscovery,
1284
+ "hmr discoverRouters (cloudflare)",
1285
+ () =>
1286
+ discoverRouters(
1287
+ s,
1288
+ tempRscEnv,
1289
+ (prerenderTempServer?.environments as any)?.ssr,
1290
+ ),
1291
+ );
1292
+ timedSync(debugDiscovery, "hmr writeRouteTypesFiles", () =>
1293
+ writeRouteTypesFiles(s),
1294
+ );
1295
+ }
1296
+ if (s.lastDiscoveryError) {
1297
+ debugDiscovery?.(
1298
+ "hmr: cleared lastDiscoveryError (%s) after successful rediscovery",
1299
+ s.lastDiscoveryError.message,
1300
+ );
1301
+ s.lastDiscoveryError = null;
1302
+ }
1303
+ s.transitionWhenOverlay = null;
1304
+ // Cloudflare dev: on a successful cycle drop the workerd runner's
1305
+ // cached worker-entry chain so the next request re-evaluates
1306
+ // createRouter() with the new routes. Fired here in the work path
1307
+ // (not the caller's .then()) so a queued follow-up cycle that
1308
+ // succeeds after an earlier failed cycle still reloads:
1309
+ // runRefreshCycle recurses queued work without awaiting it, so the
1310
+ // original call already resolved on the failed cycle. A failed
1311
+ // cycle throws above and never reaches here, so a broken edit
1312
+ // never reloads the worker onto bad source.
1313
+ if (rscEnv && !rscEnv.runner) {
1314
+ const nextRouteShape = routeShapeSignature();
1315
+ let expectedEpoch: number | undefined;
1316
+ if (nextRouteShape !== previousRouteShape) {
1317
+ expectedEpoch = Math.max(
1318
+ Date.now(),
1319
+ (s.devDiscoveryEpoch ?? 0) + 1,
1320
+ );
1321
+ s.devDiscoveryEpoch = expectedEpoch;
1322
+ }
1323
+ previousRouteShape = nextRouteShape;
1324
+ forceCloudflareWorkerReload(rscEnv, expectedEpoch);
1325
+ }
1326
+ } catch (err: any) {
1327
+ recordDiscoveryFailure(s, err);
1328
+ // An invalid transition({ when }) is a definition error the
1329
+ // user must see: terminal error plus the browser's Vite overlay,
1330
+ // not a warning while the last-good route tree keeps serving.
1331
+ const whenError = showTransitionWhenError(s, err);
1332
+ if (whenError) {
1333
+ console.error(whenError.message);
1334
+ } else {
1335
+ console.warn(`[rango] Runtime re-discovery failed: ${err.message}`);
1336
+ }
1337
+ debugDiscovery?.(
1338
+ "hmr: lastDiscoveryError set (%s) — manifest preserved at last-good; recovery mode active (any in-scan source change will trigger rediscovery)",
1339
+ err?.message,
1340
+ );
1341
+ } finally {
1342
+ debugDiscovery?.(
1343
+ "hmr re-discovery done (%sms)",
1344
+ (performance.now() - hmrStart).toFixed(1),
1345
+ );
1346
+ }
1347
+ });
1348
+ };
1349
+
1350
+ // Cloudflare dev only. workerd serves every request through the
1351
+ // runner-worker singleton, which re-resolves the worker entry per
1352
+ // request via runner.import("virtual:cloudflare/worker-entry"). The
1353
+ // route table lives in the user's createRouter() instance, captured
1354
+ // when that entry chain (entry -> router -> urls) was last evaluated
1355
+ // and then cached in the runner's evaluatedModules. The route-file
1356
+ // watcher refreshes discovery + types on the Node side, but the worker
1357
+ // keeps serving the cached (stale) router: route-definition modules
1358
+ // have no import.meta.hot boundary, so Vite never sends the worker an
1359
+ // HMR update for them and the entry chain is never evicted.
1360
+ //
1361
+ // Fix: after discovery completes, (1) invalidate the worker env's
1362
+ // Node-side module graph, (2) send a full-reload to the worker, then
1363
+ // (3) probe until the active router reports the new discovery epoch.
1364
+ // Step (2) alone is insufficient: the full-reload handler clears the
1365
+ // runner's evaluatedModules and re-imports entrypoints, but each
1366
+ // re-import fetches the module back through this Node-side graph, which
1367
+ // still holds the pre-edit transform of urls.tsx — so createRouter()
1368
+ // rebuilds the stale route table and the new route 404s/hits the
1369
+ // catch-all. Invalidating the graph forces a fresh transform on
1370
+ // re-fetch (the same mechanism refreshTempRscEnv uses for discovery),
1371
+ // so the re-import re-runs createRouter() with the new routes. The probe
1372
+ // is detached because the refresh callback still holds the discovery
1373
+ // gate; awaiting it here would deadlock the request that proves the new
1374
+ // router is active. Once it succeeds, the client hot channel broadcasts
1375
+ // readiness to open and newly-booted stale documents.
1376
+ const forceCloudflareWorkerReload = (
1377
+ rscEnv: any,
1378
+ expectedEpoch: number | undefined,
1379
+ ) => {
1380
+ if (!rscEnv?.hot) return;
1381
+
1382
+ const graph = rscEnv.moduleGraph;
1383
+ const reloadWorkerd = () => {
1384
+ if (graph?.invalidateAll) {
1385
+ graph.invalidateAll();
1386
+ debugDiscovery?.("hmr: invalidated workerd rsc module graph");
1387
+ }
1388
+ rscEnv.hot.send({ type: "full-reload" });
1389
+ debugDiscovery?.("hmr: forced workerd rsc env reload (full-reload)");
1390
+ };
1391
+ reloadWorkerd();
1392
+
1393
+ if (expectedEpoch === undefined) return;
1394
+ void (async () => {
1395
+ const deadline = Date.now() + 15_000;
1396
+ let reloadBackoffMs = 100;
1397
+ let nextReloadAt = Date.now() + reloadBackoffMs;
1398
+ do {
1399
+ if (devServerClosed || expectedEpoch !== s.devDiscoveryEpoch) {
1400
+ return;
1401
+ }
1402
+ await new Promise<void>((resolve) => setTimeout(resolve, 25));
1403
+ if (devServerClosed || expectedEpoch !== s.devDiscoveryEpoch) {
1404
+ return;
1405
+ }
1406
+ try {
1407
+ const response = await fetch(getDevServerOrigin() + "/", {
1408
+ cache: "no-store",
1409
+ headers: {
1410
+ [DEV_DISCOVERY_PROBE_HEADER]: String(expectedEpoch),
1411
+ },
1412
+ signal: AbortSignal.timeout(1_000),
1413
+ });
1414
+ if (
1415
+ !devServerClosed &&
1416
+ expectedEpoch === s.devDiscoveryEpoch &&
1417
+ response.headers.get(DEV_DISCOVERY_EPOCH_HEADER) ===
1418
+ String(expectedEpoch)
1419
+ ) {
1420
+ publishDevDiscoveryReady(expectedEpoch);
1421
+ return;
1422
+ }
1423
+ await response.body?.cancel().catch(() => {});
1424
+ // A response without the expected epoch proves an older worker
1425
+ // evaluation won the race after the initial invalidation. Clear
1426
+ // that completed evaluation and retry the reload. Back off the
1427
+ // retries: reloading faster than workerd can evaluate prevents
1428
+ // convergence and retains overlapping module generations.
1429
+ const now = Date.now();
1430
+ if (now >= nextReloadAt) {
1431
+ reloadWorkerd();
1432
+ reloadBackoffMs = Math.min(reloadBackoffMs * 2, 1_000);
1433
+ nextReloadAt = now + reloadBackoffMs;
1434
+ }
1435
+ } catch {}
1436
+ } while (Date.now() < deadline);
1437
+
1438
+ debugDiscovery?.(
1439
+ "hmr: workerd readiness probe timed out at epoch %d",
1440
+ expectedEpoch,
1441
+ );
1442
+ })();
1443
+ };
1444
+
1445
+ const scheduleRouteRegeneration = () => {
1446
+ clearTimeout(routeChangeTimer);
1447
+ routeChangeTimer = setTimeout(async () => {
1448
+ routeChangeTimer = undefined;
1449
+ const regenStart = debugDiscovery ? performance.now() : 0;
1450
+ const rscEnv = (server.environments as any)?.rsc;
1451
+ const skipStaticWrite =
1452
+ !rscEnv?.runner && s.perRouterManifests.length > 0;
1453
+ // Refresh clientUrls projections + state BEFORE any gen-file
1454
+ // write below: the write invalidates the routes-manifest virtual
1455
+ // module, whose regenerated code replays state.clientUrlProjectionMap
1456
+ // (clear + set). A stale map at that moment bakes stale literals
1457
+ // that clobber the runtime registry before the re-discovery entry
1458
+ // import materializes the client mount (node HMR served old
1459
+ // client-urls patterns until restart). Lenient: import failures
1460
+ // keep last-known state; discoverRouters' strict pass reports.
1461
+ if (rscEnv?.runner && s.clientUrlSourceByReferenceId?.size) {
1462
+ try {
1463
+ const serverMod = await rscEnv.runner.import(
1464
+ "@rangojs/router/server",
1465
+ );
1466
+ await refreshRecordedClientUrlProjections(
1467
+ s,
1468
+ (server.environments as any)?.ssr,
1469
+ serverMod,
1470
+ rscEnv,
1471
+ );
1472
+ // Force the routes-manifest virtual module to re-transform:
1473
+ // its generated code REPLAYS projections (clear + set) on
1474
+ // every rsc program reload, and self-gen-write suppression
1475
+ // keeps its cached transform alive through this cycle — a
1476
+ // stale replay after propagateDiscoveryState would clobber
1477
+ // the refreshed registry as the realm's last write and the
1478
+ // next router evaluation would materialize the old mount.
1479
+ invalidateRoutesManifestModule(rscEnv);
1480
+ } catch (err: any) {
1481
+ debugDiscovery?.(
1482
+ "watcher: clientUrls projection pre-refresh failed: %s",
1483
+ err?.message,
1484
+ );
1485
+ }
1486
+ }
1487
+ try {
1488
+ // In cloudflare dev with a populated runtime manifest, the
1489
+ // static parser produces a strictly smaller (and actively
1490
+ // wrong) gen file — supplementGenFilesWithRuntimeRoutes can
1491
+ // only restore factory-only prefixes, and apps with mixed
1492
+ // static+factory routes under shared prefixes (cf-stress)
1493
+ // collapse to the 19-route static view. Skip the static
1494
+ // write entirely; runtime rediscovery below will overwrite
1495
+ // the gen file with the authoritative manifest.
1496
+ if (skipStaticWrite) {
1497
+ debugDiscovery?.(
1498
+ "watcher: skipping static write (cloudflare HMR — runtime rediscovery owns gen file)",
1499
+ );
1500
+ } else {
1501
+ writeCombinedRouteTypesWithTracking(s);
1502
+ if (s.perRouterManifests.length > 0) {
1503
+ supplementGenFilesWithRuntimeRoutes(s);
1504
+ }
1505
+ }
1506
+ } catch (err: any) {
1507
+ console.error(`[rango] Route regeneration error: ${err.message}`);
1508
+ }
1509
+ debugDiscovery?.(
1510
+ "watcher: regenerated gen files (%sms)",
1511
+ (performance.now() - regenStart).toFixed(1),
1512
+ );
1513
+ // Async: re-run runtime discovery to refresh factory-generated
1514
+ // routes that the static parser cannot resolve. Resolves the
1515
+ // discovery gate when complete.
1516
+ if (canRefreshRuntimeDiscovery(s)) {
1517
+ // The cloudflare workerd reload fires inside refreshRuntimeDiscovery
1518
+ // on the successful cycle (see forceCloudflareWorkerReload call
1519
+ // there) so queued follow-up cycles also trigger it.
1520
+ refreshRuntimeDiscovery().catch((err: any) => {
1521
+ console.warn(`[rango] Runtime re-discovery error: ${err.message}`);
1522
+ // Even on error, unblock the gate so workerd's reload doesn't
1523
+ // hang indefinitely against the previous manifest.
1524
+ resolveDiscoveryGate();
1525
+ });
1526
+ }
1527
+ }, 100);
1528
+ };
1529
+
1530
+ // The `.use` signature of each component-use module at its last
1531
+ // save: a save that keeps it (markup, hooks) re-projects nothing.
1532
+ const componentUseSignatures = new Map<string, string>();
1533
+ const componentUseChanged = (file: string, source: string) => {
1534
+ const next = componentUseSignature(source, file);
1535
+ const changed = next !== componentUseSignatures.get(file);
1536
+ if (next === undefined) componentUseSignatures.delete(file);
1537
+ else componentUseSignatures.set(file, next);
1538
+ return changed;
1539
+ };
1540
+
1541
+ const handleRouteFileChange = (filePath: string) => {
1542
+ if (isOutsideApp(filePath)) {
1543
+ debugDiscovery?.(
1544
+ "watcher: skip %s (outside the discovery scan)",
1545
+ filePath,
1546
+ );
1547
+ return;
1548
+ }
1549
+ if (maybeHandleGeneratedRouteFileMutation(filePath)) return;
1550
+ if (
1551
+ !filePath.endsWith(".ts") &&
1552
+ !filePath.endsWith(".tsx") &&
1553
+ !filePath.endsWith(".js") &&
1554
+ !filePath.endsWith(".jsx")
1555
+ ) {
1556
+ if (s.lastDiscoveryError) {
1557
+ debugDiscovery?.(
1558
+ "watcher: skip non-source %s [LASTERR %s]",
1559
+ filePath,
1560
+ s.lastDiscoveryError.message,
1561
+ );
1562
+ }
1563
+ return;
1564
+ }
1565
+ // Apply scan filter as early-exit before reading file
1566
+ if (s.scanFilter && !s.scanFilter(filePath)) {
1567
+ if (s.lastDiscoveryError) {
1568
+ debugDiscovery?.(
1569
+ "watcher: skip scan-filter %s [LASTERR %s]",
1570
+ filePath,
1571
+ s.lastDiscoveryError.message,
1572
+ );
1573
+ }
1574
+ return;
1575
+ }
1576
+ // Recovery mode: when the previous HMR re-discovery failed, the
1577
+ // import graph is incomplete and the manifest is stuck at the
1578
+ // last-good state. The fix may land in a non-route file (e.g. a
1579
+ // helper imported by the router, a missing module being created,
1580
+ // or a "use client" component) that the narrow content sniff
1581
+ // would otherwise filter out. While in recovery, treat any
1582
+ // in-scan source change as a candidate for rediscovery; the
1583
+ // tighter filter resumes once discovery succeeds again.
1584
+ const inRecoveryMode = !!s.lastDiscoveryError;
1585
+ try {
1586
+ const source = readFileSync(filePath, "utf-8");
1587
+ const trimmed = source.trimStart();
1588
+ const isUseClient =
1589
+ trimmed.startsWith('"use client"') ||
1590
+ trimmed.startsWith("'use client'");
1591
+ // clientUrls() modules are "use client" by contract yet define
1592
+ // routes: their edits must re-run discovery (server projection +
1593
+ // generated types), so only bail on use-client files WITHOUT a
1594
+ // clientUrls() definition. Scar: before this carve-out, editing a
1595
+ // clientUrls module's route shape in dev left the serving router on
1596
+ // the stale projection — the old pattern kept matching and the new
1597
+ // one 404ed until a full restart.
1598
+ let hasClientUrls = source.includes("clientUrls(");
1599
+ if (hasClientUrls) {
1600
+ hasClientUrls = firstCodeMatchIndex(source, /\bclientUrls\(/g) >= 0;
1601
+ }
1602
+ // A component whose `.use` a group reads changes the group's
1603
+ // projection too (its loaders, loading(), revalidate() keys):
1604
+ // on its first save, and when a `.use` changed, came or went.
1605
+ const hasComponentUse = componentUseChanged(filePath, source);
1606
+ if (
1607
+ !inRecoveryMode &&
1608
+ isUseClient &&
1609
+ !hasClientUrls &&
1610
+ !hasComponentUse
1611
+ ) {
1612
+ return;
1613
+ }
1614
+ // Cheap raw pre-check first; only when a candidate token is present
1615
+ // do we confirm it occurs in real code (not a comment/string) via a
1616
+ // single allocation-free code-region scan. Most saved files contain
1617
+ // neither token and skip the scan entirely. This avoids a comment or
1618
+ // string mention spuriously marking a file relevant and triggering an
1619
+ // unnecessary re-discovery on save.
1620
+ let hasUrls = source.includes("urls(");
1621
+ let hasCreateRouter = /\bcreateRouter\s*[<(]/.test(source);
1622
+ if (hasUrls) hasUrls = firstCodeMatchIndex(source, /urls\(/g) >= 0;
1623
+ if (hasCreateRouter) {
1624
+ hasCreateRouter =
1625
+ firstCodeMatchIndex(source, /\bcreateRouter\s*[<(]/g) >= 0;
1626
+ }
1627
+ // hasClientUrls counts here too: in a clientUrls() module the only
1628
+ // `urls(` token sits INSIDE the `clientUrls(` identifier, which the
1629
+ // code scan correctly rejects as a sub-identifier match — so
1630
+ // without this the file would silently fail the sniff.
1631
+ if (
1632
+ !inRecoveryMode &&
1633
+ !hasUrls &&
1634
+ !hasCreateRouter &&
1635
+ !hasClientUrls &&
1636
+ !hasComponentUse
1637
+ ) {
1638
+ return;
1639
+ }
1640
+ if (inRecoveryMode) {
1641
+ debugDiscovery?.(
1642
+ "watcher: recovery rediscovery for %s (urls=%s, router=%s, clientUrls=%s, useClient=%s) [LASTERR %s]",
1643
+ filePath,
1644
+ hasUrls,
1645
+ hasCreateRouter,
1646
+ hasClientUrls,
1647
+ isUseClient,
1648
+ s.lastDiscoveryError!.message,
1649
+ );
1650
+ } else {
1651
+ debugDiscovery?.(
1652
+ "watcher: %s matches (urls=%s, router=%s, clientUrls=%s, componentUse=%s)",
1653
+ filePath,
1654
+ hasUrls,
1655
+ hasCreateRouter,
1656
+ hasClientUrls,
1657
+ hasComponentUse,
1658
+ );
1659
+ }
1660
+ // A "use client" clientUrls module is an HMR-accepted client
1661
+ // boundary in the rsc graph: its edit never invalidates the router
1662
+ // module that materialized its projection, so the re-discovery
1663
+ // entry import would cache-hit and keep serving the stale mount
1664
+ // (old patterns 200, new patterns 404 until restart). Invalidate
1665
+ // the entry + router sources so the import re-creates the routers
1666
+ // against the refreshed projection (installed by the pre-entry
1667
+ // refresh in discover-routers.ts).
1668
+ const mainRscEnv = (server.environments as any)?.rsc;
1669
+ if (
1670
+ ((isUseClient && hasClientUrls) || hasComponentUse) &&
1671
+ mainRscEnv?.runner
1672
+ ) {
1673
+ const rscGraph = mainRscEnv.moduleGraph;
1674
+ if (rscGraph?.getModulesByFile) {
1675
+ // Importers must be invalidated too: the virtual RSC entry
1676
+ // holds a live `import { router }` binding, and re-evaluating
1677
+ // router.tsx alone leaves that binding on the OLD instance —
1678
+ // the request pipeline would keep serving the stale mount.
1679
+ // Vite's invalidateModule already walks importers. Share its
1680
+ // seen set across roots instead of recursively starting a new
1681
+ // traversal at every importer (quadratic on a large graph).
1682
+ // Vite's walk skips HMR-accepting importers and soft-invalidates
1683
+ // static ones (vs the old unconditional hard walk) — safe here:
1684
+ // the entry and every router source are invalidated directly as
1685
+ // roots, and ancestors get the exact treatment Vite's own
1686
+ // file-change propagation applies on a server urls edit.
1687
+ // Cloudflare has no local runner and skips this block: its temp
1688
+ // discovery graph and workerd graph are invalidated wholesale
1689
+ // by refreshRuntimeDiscovery() after this watcher event.
1690
+ const routerSourceFiles = new Set<string>();
1691
+ if (s.resolvedEntryPath) {
1692
+ routerSourceFiles.add(resolve(s.resolvedEntryPath));
1693
+ }
1694
+ for (const entry of s.perRouterManifests) {
1695
+ if (entry.sourceFile) {
1696
+ routerSourceFiles.add(resolve(entry.sourceFile));
1697
+ }
1698
+ }
1699
+ const seen = new Set<any>();
1700
+ for (const file of routerSourceFiles) {
1701
+ const mods = modulesForFile(rscGraph, file);
1702
+ if (!mods) {
1703
+ debugDiscovery?.(
1704
+ "watcher: clientUrls invalidation found no rsc modules for %s",
1705
+ file,
1706
+ );
1707
+ continue;
1708
+ }
1709
+ for (const mod of mods) {
1710
+ rscGraph.invalidateModule(mod, seen);
1711
+ }
1712
+ }
1713
+ debugDiscovery?.(
1714
+ "watcher: clientUrls edit invalidated %d rsc module(s) for %d router file(s)",
1715
+ seen.size,
1716
+ routerSourceFiles.size,
1717
+ );
1718
+ }
1719
+ }
1720
+ // Invalidate cache when a router file changes (new router added/removed)
1721
+ if (hasCreateRouter) {
1722
+ const nestedRouterConflict = findNestedRouterConflict([
1723
+ ...(s.cachedRouterFiles ?? []),
1724
+ resolve(filePath),
1725
+ ]);
1726
+ if (nestedRouterConflict) {
1727
+ server.config.logger.error(
1728
+ formatNestedRouterConflictError(nestedRouterConflict),
1729
+ );
1730
+ return;
1731
+ }
1732
+ s.cachedRouterFiles = undefined;
1733
+ }
1734
+ // Note the event in the gate machine IMMEDIATELY (before the
1735
+ // 100ms debounce and any downstream HMR fanout). This sets
1736
+ // both `pendingEvents` (so refresh's finally holds the gate
1737
+ // through the tail window even if no rediscovery is queued)
1738
+ // and resets `discoveryDone` to a fresh pending promise (so
1739
+ // workerd reloads triggered by the same source change can't
1740
+ // observe a stale resolved gate from cold-start). Resolved
1741
+ // by the trailing refreshRuntimeDiscovery() cycle, which runs
1742
+ // under the same predicate.
1743
+ if (canRefreshRuntimeDiscovery(s)) {
1744
+ gate.noteRouteEvent();
1745
+ }
1746
+ scheduleRouteRegeneration();
1747
+ } catch (readErr: any) {
1748
+ if (s.lastDiscoveryError) {
1749
+ debugDiscovery?.(
1750
+ "watcher: read error %s: %s [LASTERR %s]",
1751
+ filePath,
1752
+ readErr?.message,
1753
+ s.lastDiscoveryError.message,
1754
+ );
1755
+ }
1756
+ // Ignore read errors for deleted/moved files
1757
+ }
1758
+ };
1759
+
1760
+ // Handle both "add" and "change" events: editors with atomic saves
1761
+ // (unlink + rename) emit "add" instead of "change", and chokidar's
1762
+ // polling mode on CI Linux can also emit "add" for overwrites.
1763
+ server.watcher.on("add", handleRouteFileChange);
1764
+ server.watcher.on("change", handleRouteFileChange);
1765
+
1766
+ // Regenerate gen files when they are deleted (e.g. manual cleanup).
1767
+ // Same no-runner guard as change/add: stale perRouterManifests would
1768
+ // reintroduce reverted content.
1769
+ server.watcher.on("unlink", (filePath) => {
1770
+ if (!isGeneratedRouteFile(filePath) || isOutsideApp(filePath)) return;
1771
+ const hasRunner = !!(server.environments as any)?.rsc?.runner;
1772
+ if (!hasRunner) return;
1773
+ regenerateGeneratedRouteFiles();
1774
+ });
1775
+ }
1776
+ }