rsbuild-plugin-react-router 0.4.1 → 0.6.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 (126) hide show
  1. package/README.md +72 -240
  2. package/dist/{451.js → 511.js} +461 -331
  3. package/dist/build-output-transforms.d.ts +32 -7
  4. package/dist/classic-mode.d.ts +56 -0
  5. package/dist/config-imports.d.ts +8 -2
  6. package/dist/constants.d.ts +3 -0
  7. package/dist/dev-background-resources.d.ts +3 -3
  8. package/dist/dev-generation.d.ts +2 -3
  9. package/dist/dev-hmr.d.ts +8 -2
  10. package/dist/dev-runtime-controller.d.ts +6 -1
  11. package/dist/dev-source-maps.d.ts +4 -0
  12. package/dist/effect-runtime.d.ts +17 -5
  13. package/dist/entry-paths.d.ts +16 -0
  14. package/dist/environment-output.d.ts +6 -0
  15. package/dist/export-utils.d.ts +2 -1
  16. package/dist/federation.d.ts +2 -0
  17. package/dist/index.cjs +3675 -2107
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.js +3614 -2214
  20. package/dist/lazy-compilation-prewarm.d.ts +8 -5
  21. package/dist/manifest.d.ts +16 -4
  22. package/dist/mode-plan.d.ts +82 -0
  23. package/dist/modify-browser-manifest.d.ts +8 -4
  24. package/dist/performance.d.ts +4 -1
  25. package/dist/plugin-utils.d.ts +27 -1
  26. package/dist/prerender-build.d.ts +5 -5
  27. package/dist/prerender.d.ts +1 -5
  28. package/dist/react-router-config.d.ts +11 -3
  29. package/dist/route-artifacts.d.ts +4 -2
  30. package/dist/route-chunks.d.ts +2 -1
  31. package/dist/route-component-transform.d.ts +0 -2
  32. package/dist/route-export-pruning.d.ts +4 -1
  33. package/dist/route-imports.d.ts +18 -0
  34. package/dist/route-module-transform-loader.d.ts +14 -0
  35. package/dist/route-module-transform-loader.js +44 -0
  36. package/dist/route-module-transform-rules.d.ts +14 -0
  37. package/dist/route-transform-tasks.d.ts +6 -0
  38. package/dist/route-watch.d.ts +11 -6
  39. package/dist/rsc-dev-server.d.ts +26 -0
  40. package/dist/rsc-prerender.d.ts +54 -0
  41. package/dist/rsc-route-config.d.ts +6 -0
  42. package/dist/rsc-route-exports.d.ts +15 -0
  43. package/dist/rsc-route-transform-loader.cjs +43 -0
  44. package/dist/rsc-route-transform-loader.d.ts +30 -0
  45. package/dist/rsc-route-transform-loader.js +16 -0
  46. package/dist/rsc-route-transform-registration.d.ts +12 -0
  47. package/dist/rsc-route-transforms.d.ts +21 -0
  48. package/dist/rsc-support.d.ts +23 -0
  49. package/dist/rsc-virtual-modules.d.ts +19 -0
  50. package/dist/server-build-plan.d.ts +2 -1
  51. package/dist/server-build-resolution.d.ts +1 -2
  52. package/dist/server-utils.d.ts +4 -5
  53. package/dist/ssr-asset-relocation.d.ts +98 -0
  54. package/dist/templates/entry.rsc.client.d.ts +1 -0
  55. package/dist/templates/entry.rsc.client.js +61 -0
  56. package/dist/templates/entry.rsc.d.ts +9 -0
  57. package/dist/templates/entry.rsc.js +38 -0
  58. package/dist/templates/entry.rsc.ssr.d.ts +4 -0
  59. package/dist/templates/entry.rsc.ssr.js +24 -0
  60. package/dist/typegen.d.ts +4 -2
  61. package/dist/types.d.ts +34 -6
  62. package/package.json +76 -22
  63. package/src/build-output-transforms.ts +181 -43
  64. package/src/classic-mode.ts +253 -0
  65. package/src/config-imports.ts +153 -6
  66. package/src/constants.ts +6 -2
  67. package/src/dev-background-resources.ts +46 -100
  68. package/src/dev-generation.ts +52 -33
  69. package/src/dev-hmr.ts +112 -80
  70. package/src/dev-runtime-artifacts.ts +11 -12
  71. package/src/dev-runtime-controller.ts +75 -85
  72. package/src/dev-runtime-session.ts +14 -18
  73. package/src/dev-server.ts +2 -0
  74. package/src/dev-source-maps.ts +257 -0
  75. package/src/effect-runtime.ts +105 -57
  76. package/src/entry-paths.ts +80 -0
  77. package/src/environment-output.ts +55 -0
  78. package/src/export-utils.ts +15 -11
  79. package/src/federation.ts +38 -0
  80. package/src/index.ts +666 -519
  81. package/src/lazy-compilation-prewarm.ts +20 -4
  82. package/src/manifest.ts +157 -82
  83. package/src/mode-plan.ts +367 -0
  84. package/src/modify-browser-manifest.ts +130 -124
  85. package/src/performance.ts +11 -2
  86. package/src/plugin-utils.ts +103 -39
  87. package/src/prerender-build.ts +82 -104
  88. package/src/prerender.ts +23 -24
  89. package/src/react-router-config.ts +72 -26
  90. package/src/route-artifacts.ts +96 -66
  91. package/src/route-chunks.ts +167 -51
  92. package/src/route-component-transform.ts +14 -21
  93. package/src/route-export-pruning.ts +4 -3
  94. package/src/route-imports.ts +100 -0
  95. package/src/route-module-transform-loader.ts +149 -0
  96. package/src/route-module-transform-rules.ts +115 -0
  97. package/src/route-transform-tasks.ts +44 -29
  98. package/src/route-watch.ts +166 -188
  99. package/src/rsc-dev-server.ts +112 -0
  100. package/src/rsc-prerender.ts +362 -0
  101. package/src/rsc-route-config.ts +175 -0
  102. package/src/rsc-route-exports.ts +67 -0
  103. package/src/rsc-route-transform-loader.ts +65 -0
  104. package/src/rsc-route-transform-registration.ts +145 -0
  105. package/src/rsc-route-transforms.ts +995 -0
  106. package/src/rsc-runtime.d.ts +143 -0
  107. package/src/rsc-support.ts +116 -0
  108. package/src/rsc-virtual-modules.ts +113 -0
  109. package/src/server-build-plan.ts +14 -3
  110. package/src/server-build-resolution.ts +37 -47
  111. package/src/server-utils.ts +21 -35
  112. package/src/ssr-asset-relocation.ts +183 -0
  113. package/src/ssr-externals.ts +8 -26
  114. package/src/templates/entry.rsc.client.tsx +168 -0
  115. package/src/templates/entry.rsc.ssr.tsx +45 -0
  116. package/src/templates/entry.rsc.tsx +80 -0
  117. package/src/typegen.ts +40 -23
  118. package/src/types.ts +43 -6
  119. package/src/warnings/warn-on-client-source-maps.ts +6 -10
  120. package/dist/parallel-route-transform-protocol.d.ts +0 -25
  121. package/dist/parallel-route-transform-worker.d.ts +0 -1
  122. package/dist/parallel-route-transform-worker.js +0 -38
  123. package/dist/parallel-route-transforms.d.ts +0 -29
  124. package/src/parallel-route-transform-protocol.ts +0 -35
  125. package/src/parallel-route-transform-worker.ts +0 -82
  126. package/src/parallel-route-transforms.ts +0 -458
@@ -1,7 +1,9 @@
1
1
  import type { RsbuildDevServer, Rspack } from '@rsbuild/core';
2
2
  import * as EffectDeferred from 'effect/Deferred';
3
3
  import * as Effect from 'effect/Effect';
4
+ import * as FiberId from 'effect/FiberId';
4
5
  import type { ServerBuild } from 'react-router';
6
+ import { HMR_PATCHABLE_ROUTE_FLAGS } from './route-artifacts.js';
5
7
  import {
6
8
  evaluateServerBuilds,
7
9
  getEnvironmentStats,
@@ -20,14 +22,10 @@ import {
20
22
  } from './dev-runtime-artifacts.js';
21
23
  import { normalizeEffectError, runPluginEffect } from './effect-runtime.js';
22
24
 
23
- export { snapshotDevChangedFiles } from './dev-runtime-artifacts.js';
24
25
  export type {
25
- DevChangedFiles,
26
26
  DevGraphChanges,
27
27
  DevGraphIdentity,
28
- ReactRouterDevBuildPlan,
29
28
  ReactRouterDevManifest,
30
- ReactRouterDevManifestSet,
31
29
  } from './dev-runtime-artifacts.js';
32
30
 
33
31
  type CommittedGeneration = {
@@ -73,7 +71,9 @@ type CreateReactRouterDevRuntimeOptions = {
73
71
  buildPlan: ReactRouterDevBuildPlan;
74
72
  onEvaluationError: (error: Error) => void;
75
73
  onCssAssetOwnershipChanged?: (change: 'removed' | 'restored') => void;
76
- onRouteManifestChanged?: () => void;
74
+ onRouteManifestChanged?: (
75
+ manifest: ReactRouterDevManifestSet[string]
76
+ ) => void;
77
77
  onWarning?: (message: string) => void;
78
78
  };
79
79
 
@@ -199,28 +199,35 @@ type DevRouteManifestEntry = NonNullable<
199
199
 
200
200
  const hasSameRouteMetadata = (
201
201
  previous: DevRouteManifestEntry,
202
- next: DevRouteManifestEntry
203
- ): boolean =>
204
- previous.caseSensitive === next.caseSensitive &&
205
- previous.clientActionModule === next.clientActionModule &&
206
- previous.clientLoaderModule === next.clientLoaderModule &&
207
- previous.clientMiddlewareModule === next.clientMiddlewareModule &&
208
- previous.hasErrorBoundary === next.hasErrorBoundary &&
209
- previous.hasAction === next.hasAction &&
210
- previous.hasClientAction === next.hasClientAction &&
211
- previous.hasClientLoader === next.hasClientLoader &&
212
- previous.hasClientMiddleware === next.hasClientMiddleware &&
213
- previous.hasDefaultExport === next.hasDefaultExport &&
214
- previous.hasLoader === next.hasLoader &&
215
- previous.hydrateFallbackModule === next.hydrateFallbackModule &&
216
- previous.id === next.id &&
217
- previous.index === next.index &&
218
- previous.parentId === next.parentId &&
219
- previous.path === next.path;
202
+ next: DevRouteManifestEntry,
203
+ includeHmrPatchableFlags: boolean
204
+ ): boolean => {
205
+ const structuralEqual =
206
+ previous.caseSensitive === next.caseSensitive &&
207
+ previous.clientActionModule === next.clientActionModule &&
208
+ previous.clientLoaderModule === next.clientLoaderModule &&
209
+ previous.clientMiddlewareModule === next.clientMiddlewareModule &&
210
+ previous.hasDefaultExport === next.hasDefaultExport &&
211
+ previous.hydrateFallbackModule === next.hydrateFallbackModule &&
212
+ previous.id === next.id &&
213
+ previous.index === next.index &&
214
+ previous.parentId === next.parentId &&
215
+ previous.path === next.path;
216
+ if (!structuralEqual) {
217
+ return false;
218
+ }
219
+ if (!includeHmrPatchableFlags) {
220
+ return true;
221
+ }
222
+ // Without a client-side HMR runtime these flags can only reach the browser
223
+ // through a full reload.
224
+ return HMR_PATCHABLE_ROUTE_FLAGS.every(flag => previous[flag] === next[flag]);
225
+ };
220
226
 
221
227
  const hasRouteManifestMetadataChanges = (
222
228
  previous: ReactRouterDevManifestSet,
223
- next: ReactRouterDevManifestSet
229
+ next: ReactRouterDevManifestSet,
230
+ includeHmrPatchableFlags: boolean
224
231
  ): boolean => {
225
232
  const previousEntryNames = Object.keys(previous);
226
233
  if (previousEntryNames.length !== Object.keys(next).length) {
@@ -240,7 +247,14 @@ const hasRouteManifestMetadataChanges = (
240
247
  for (const routeId of previousRouteIds) {
241
248
  const previousRoute = previousRoutes[routeId];
242
249
  const nextRoute = nextRoutes[routeId];
243
- if (!nextRoute || !hasSameRouteMetadata(previousRoute, nextRoute)) {
250
+ if (
251
+ !nextRoute ||
252
+ !hasSameRouteMetadata(
253
+ previousRoute,
254
+ nextRoute,
255
+ includeHmrPatchableFlags
256
+ )
257
+ ) {
244
258
  return true;
245
259
  }
246
260
  }
@@ -251,7 +265,7 @@ const hasRouteManifestMetadataChanges = (
251
265
  const createReadinessDeferred = (): EffectDeferred.Deferred<
252
266
  CommittedGeneration,
253
267
  Error
254
- > => Effect.runSync(EffectDeferred.make<CommittedGeneration, Error>());
268
+ > => EffectDeferred.unsafeMake<CommittedGeneration, Error>(FiberId.none);
255
269
 
256
270
  export const createReactRouterDevRuntime = ({
257
271
  server,
@@ -285,9 +299,11 @@ export const createReactRouterDevRuntime = ({
285
299
  }
286
300
  };
287
301
 
288
- const notifyRouteManifestChanged = (): void => {
302
+ const notifyRouteManifestChanged = (
303
+ manifest: ReactRouterDevManifestSet[string]
304
+ ): void => {
289
305
  try {
290
- onRouteManifestChanged();
306
+ onRouteManifestChanged(manifest);
291
307
  } catch (cause) {
292
308
  onWarning(
293
309
  `[rsbuild-plugin-react-router] Failed to notify the browser after route manifest metadata changed: ${normalizeEffectError(cause).message}`
@@ -340,7 +356,7 @@ export const createReactRouterDevRuntime = ({
340
356
  if (state.kind === 'starting') {
341
357
  const { readiness } = state;
342
358
  state = { kind: 'failed', attemptId, error };
343
- Effect.runSync(EffectDeferred.fail(readiness, error));
359
+ EffectDeferred.unsafeDone(readiness, Effect.fail(error));
344
360
  } else if (state.kind === 'ready') {
345
361
  state = { ...state, pendingAttemptId: null };
346
362
  }
@@ -359,7 +375,7 @@ export const createReactRouterDevRuntime = ({
359
375
  if (state.kind === 'starting') {
360
376
  const { readiness } = state;
361
377
  state = { kind: 'ready', committed, pendingAttemptId: null };
362
- Effect.runSync(EffectDeferred.succeed(readiness, committed));
378
+ EffectDeferred.unsafeDone(readiness, Effect.succeed(committed));
363
379
  } else if (state.kind === 'ready') {
364
380
  state = { kind: 'ready', committed, pendingAttemptId: null };
365
381
  }
@@ -513,7 +529,8 @@ export const createReactRouterDevRuntime = ({
513
529
  webChanged &&
514
530
  hasRouteManifestMetadataChanges(
515
531
  previous.web.manifestsByEntryName,
516
- manifestsByEntryName
532
+ manifestsByEntryName,
533
+ true
517
534
  );
518
535
  const reusePreviousNodeBuild =
519
536
  !!previous &&
@@ -587,7 +604,9 @@ export const createReactRouterDevRuntime = ({
587
604
  reloadAfterCssRemoval = false;
588
605
  }
589
606
  if (routeManifestMetadataChanged) {
590
- notifyRouteManifestChanged();
607
+ notifyRouteManifestChanged(
608
+ web.manifestsByEntryName[buildPlan.defaultEntryName]
609
+ );
591
610
  }
592
611
  return 'committed';
593
612
  } catch (cause) {
@@ -636,7 +655,7 @@ export const createReactRouterDevRuntime = ({
636
655
  '[rsbuild-plugin-react-router] The development server closed before a React Router build was ready.'
637
656
  );
638
657
  if (state.kind === 'starting') {
639
- Effect.runSync(EffectDeferred.fail(state.readiness, closeError));
658
+ EffectDeferred.unsafeDone(state.readiness, Effect.fail(closeError));
640
659
  }
641
660
  state = { kind: 'closed', error: closeError };
642
661
  },
package/src/dev-hmr.ts CHANGED
@@ -3,9 +3,14 @@ import { createRequire } from 'node:module';
3
3
  import type { Rspack } from '@rsbuild/core';
4
4
  import { dirname, join } from 'pathe';
5
5
 
6
- import { HMR_PATCHABLE_ROUTE_FLAGS } from './route-artifacts.js';
7
-
8
6
  export const DEV_HMR_RUNTIME_MODULE_ID = 'virtual/react-router/hmr-runtime';
7
+ export const DEV_MANIFEST_UPDATE_EVENT = 'react-router:manifest-update';
8
+
9
+ export type DevHmrPlanOptions = {
10
+ isEnabled: () => boolean;
11
+ runtimeModule: string;
12
+ onNodeRebuildCommitted: () => void;
13
+ };
9
14
 
10
15
  type SwcLoaderOptions = {
11
16
  jsc?: { transform?: { react?: { refresh?: boolean } } };
@@ -17,30 +22,21 @@ const isObject = (value: unknown): value is Record<string, unknown> =>
17
22
  const isSwcLoader = (loader: unknown): boolean =>
18
23
  typeof loader === 'string' && loader.includes('builtin:swc-loader');
19
24
 
20
- const hasReactRefresh = (options: unknown): boolean =>
21
- (options as SwcLoaderOptions | undefined)?.jsc?.transform?.react?.refresh ===
22
- true;
23
-
24
25
  const readSwcLoaderRefresh = (value: unknown): boolean => {
25
- if (Array.isArray(value)) {
26
- return value.some(readSwcLoaderRefresh);
27
- }
28
- if (!isObject(value)) {
29
- return false;
30
- }
26
+ if (Array.isArray(value)) return value.some(readSwcLoaderRefresh);
27
+ if (!isObject(value)) return false;
31
28
  if (isSwcLoader(value.loader)) {
32
- return hasReactRefresh(value.options);
29
+ return (
30
+ (value.options as SwcLoaderOptions | undefined)?.jsc?.transform?.react
31
+ ?.refresh === true
32
+ );
33
33
  }
34
34
  return Object.values(value).some(readSwcLoaderRefresh);
35
35
  };
36
36
 
37
37
  const readRuleSwcRefresh = (rule: unknown): boolean => {
38
- if (!isObject(rule)) {
39
- return false;
40
- }
41
- if (isSwcLoader(rule.loader)) {
42
- return hasReactRefresh(rule.options);
43
- }
38
+ if (!isObject(rule)) return false;
39
+ if (isSwcLoader(rule.loader)) return readSwcLoaderRefresh(rule);
44
40
  return (
45
41
  readSwcLoaderRefresh(rule.use) ||
46
42
  readRuleSetSwcRefresh(rule.oneOf) ||
@@ -94,12 +90,11 @@ const hdrRevisionModuleContent = (revision: number): string =>
94
90
  * whenever server code changes, which the client answers by revalidating
95
91
  * React Router loader data.
96
92
  */
97
- export const DEV_HDR_REVISION_RELATIVE_PATH = '.react-router/hdr-revision.mjs';
98
-
99
93
  export const getDevHdrRevisionFilePath = (rootPath: string): string =>
100
- join(rootPath, DEV_HDR_REVISION_RELATIVE_PATH);
94
+ join(rootPath, '.react-router', 'hdr-revision.mjs');
101
95
 
102
96
  export type DevHdrRevisionSignal = {
97
+ filePath: string;
103
98
  /** Writes the initial revision module so the first compile can resolve it. */
104
99
  ensure: () => void;
105
100
  /** Increments the revision, signaling hot data revalidation to the client. */
@@ -127,6 +122,7 @@ export const createDevHdrRevisionSignal = ({
127
122
  }
128
123
  };
129
124
  return {
125
+ filePath,
130
126
  ensure: write,
131
127
  bump() {
132
128
  revision += 1;
@@ -138,7 +134,7 @@ export const createDevHdrRevisionSignal = ({
138
134
  /**
139
135
  * Browser-side HMR runtime shared by all route client entries in development.
140
136
  *
141
- * This mirrors React Router's Vite HMR contract (see `refresh-utils.mjs` in
137
+ * This mirrors React Router framework HMR contract (see `refresh-utils.mjs` in
142
138
  * `@react-router/dev`): route module updates are applied by patching
143
139
  * `window.__reactRouterRouteModules` while preserving the previous component
144
140
  * identities (React Fast Refresh swaps their implementations in place),
@@ -156,7 +152,11 @@ import * as __refreshRuntimeModule from ${JSON.stringify(reactRefreshRuntimePath
156
152
  // Read revision so the import survives sideEffects: false tree-shaking.
157
153
  import __hdrRevision from ${JSON.stringify(hdrRevisionFilePath)};
158
154
 
159
- void __hdrRevision;
155
+ let latestHdrRevision = __hdrRevision;
156
+
157
+ export function getReactRouterHdrRevision() {
158
+ return latestHdrRevision;
159
+ }
160
160
 
161
161
  const RefreshRuntime =
162
162
  __refreshRuntimeModule && __refreshRuntimeModule.performReactRefresh
@@ -166,6 +166,7 @@ const RefreshRuntime =
166
166
  const pendingRouteUpdates = new Map();
167
167
  let flushTimeout;
168
168
  let pendingRevalidation = false;
169
+ let pendingComponentRouteRevalidation = false;
169
170
 
170
171
  function getCurrentRouterPath(router) {
171
172
  const basename = router.basename || '/';
@@ -199,10 +200,10 @@ export function registerReactRouterRouteExports(routeId, moduleExports) {
199
200
 
200
201
  export function scheduleReactRouterRouteUpdate(
201
202
  routeId,
202
- routeFlags,
203
+ routeMetadata,
203
204
  getRouteModuleExports
204
205
  ) {
205
- pendingRouteUpdates.set(routeId, { routeFlags, getRouteModuleExports });
206
+ pendingRouteUpdates.set(routeId, { routeMetadata, getRouteModuleExports });
206
207
  scheduleFlush();
207
208
  }
208
209
 
@@ -228,16 +229,8 @@ function takePendingRouteUpdates() {
228
229
  return updates;
229
230
  }
230
231
 
231
- function getRouteMetadata(routeFlags) {
232
- return {
233
- ${HMR_PATCHABLE_ROUTE_FLAGS.map(
234
- (flag, index) => ` ${flag}: Boolean(routeFlags & ${1 << index}),`
235
- ).join('\n')}
236
- };
237
- }
238
-
239
232
  function applyRouteModuleUpdate(routeId, update, routeEntry, routeModules) {
240
- Object.assign(routeEntry, getRouteMetadata(update.routeFlags));
233
+ Object.assign(routeEntry, update.routeMetadata);
241
234
  const imported = update.getRouteModuleExports();
242
235
  registerReactRouterRouteExports(routeId, imported);
243
236
  const current = routeModules[routeId];
@@ -294,11 +287,7 @@ function patchCurrentRouteMatches(router, routes) {
294
287
 
295
288
  function applyPendingRouteUpdates(router, routeModules, manifest, context) {
296
289
  if (pendingRouteUpdates.size === 0) {
297
- return {
298
- nextManifest: undefined,
299
- shouldRefreshRouteState: false,
300
- routesToRevalidate: new Set(),
301
- };
290
+ return { nextManifest: undefined, hmrRoutes: undefined };
302
291
  }
303
292
 
304
293
  // Clone only entries mutated before the manifest is committed in flush().
@@ -309,8 +298,7 @@ function applyPendingRouteUpdates(router, routeModules, manifest, context) {
309
298
  const existingEntry = nextManifest.routes[routeId];
310
299
  if (!existingEntry) continue;
311
300
 
312
- // Shallow clone is enough: only top-level flags are mutated below.
313
- const routeEntry = { ...existingEntry };
301
+ const routeEntry = JSON.parse(JSON.stringify(existingEntry));
314
302
  nextManifest.routes[routeId] = routeEntry;
315
303
  applyRouteModuleUpdate(routeId, update, routeEntry, routeModules);
316
304
  if (
@@ -332,54 +320,52 @@ function applyPendingRouteUpdates(router, routeModules, manifest, context) {
332
320
  }
333
321
  }
334
322
 
323
+ let hmrRoutes;
335
324
  if (
336
325
  typeof router.createRoutesForHMR === 'function' &&
337
326
  typeof router._internalSetRoutes === 'function'
338
327
  ) {
339
- const routes = router.createRoutesForHMR(
328
+ hmrRoutes = router.createRoutesForHMR(
340
329
  routesToRevalidate,
341
330
  nextManifest.routes,
342
331
  routeModules,
343
332
  context.ssr,
344
333
  context.isSpaMode
345
334
  );
346
- router._internalSetRoutes(routes);
347
- patchCurrentRouteMatches(router, routes);
335
+ router._internalSetRoutes(hmrRoutes);
348
336
  }
349
337
 
350
- return { nextManifest, shouldRefreshRouteState, routesToRevalidate };
338
+ return { nextManifest, hmrRoutes, shouldRefreshRouteState };
351
339
  }
352
340
 
353
- async function withHdrActive(fn) {
341
+ async function revalidateRouter(router) {
354
342
  try {
355
343
  window.__reactRouterHdrActive = true;
356
- await fn();
344
+ if (typeof router.revalidate === 'function') {
345
+ await router.revalidate();
346
+ return;
347
+ }
348
+ if (typeof router.navigate === 'function') {
349
+ await router.navigate(getCurrentRouterPath(router), {
350
+ replace: true,
351
+ preventScrollReset: true,
352
+ });
353
+ }
357
354
  } finally {
358
355
  window.__reactRouterHdrActive = false;
359
356
  }
360
357
  }
361
358
 
362
- async function revalidateRouter(router) {
363
- if (typeof router.revalidate === 'function') {
364
- await withHdrActive(() => router.revalidate());
359
+ async function refreshRouteState(router) {
360
+ if (typeof router.revalidate !== 'function') {
365
361
  return;
366
362
  }
367
- if (typeof router.navigate === 'function') {
368
- await withHdrActive(() =>
369
- router.navigate(getCurrentRouterPath(router), {
370
- replace: true,
371
- preventScrollReset: true,
372
- })
373
- );
374
- }
375
- }
376
-
377
- async function refreshRouteState(router) {
378
- if (typeof router.revalidate === 'function') {
379
- await withHdrActive(() => router.revalidate());
380
- return true;
363
+ try {
364
+ window.__reactRouterHdrActive = true;
365
+ await router.revalidate();
366
+ } finally {
367
+ window.__reactRouterHdrActive = false;
381
368
  }
382
- return false;
383
369
  }
384
370
 
385
371
  function performReactRefresh() {
@@ -391,6 +377,34 @@ function performReactRefresh() {
391
377
  }
392
378
  }
393
379
 
380
+ function applyManifestUpdate(nextRoutes) {
381
+ const router = window.__reactRouterDataRouter;
382
+ const routeModules = window.__reactRouterRouteModules;
383
+ const manifest = window.__reactRouterManifest;
384
+ const context = window.__reactRouterContext;
385
+ if (
386
+ !router ||
387
+ !routeModules ||
388
+ !manifest ||
389
+ !context ||
390
+ !nextRoutes ||
391
+ typeof router.createRoutesForHMR !== 'function' ||
392
+ typeof router._internalSetRoutes !== 'function'
393
+ ) {
394
+ return;
395
+ }
396
+ const routes = router.createRoutesForHMR(
397
+ new Set(Object.keys(nextRoutes)),
398
+ nextRoutes,
399
+ routeModules,
400
+ context.ssr,
401
+ context.isSpaMode
402
+ );
403
+ manifest.routes = nextRoutes;
404
+ router._internalSetRoutes(routes);
405
+ patchCurrentRouteMatches(router, routes);
406
+ }
407
+
394
408
  async function flush() {
395
409
  const router = window.__reactRouterDataRouter;
396
410
  const routeModules = window.__reactRouterRouteModules;
@@ -402,30 +416,48 @@ async function flush() {
402
416
 
403
417
  let shouldRevalidate = pendingRevalidation;
404
418
  pendingRevalidation = false;
405
- const { nextManifest, shouldRefreshRouteState, routesToRevalidate } =
419
+ const { nextManifest, hmrRoutes, shouldRefreshRouteState } =
406
420
  applyPendingRouteUpdates(router, routeModules, manifest, context);
407
- if (nextManifest) {
421
+ // Loader updates must be visible during revalidation. Component-only routes
422
+ // stay staged until revalidation completes, matching React Router's HMR flow.
423
+ if (nextManifest && shouldRefreshRouteState) {
424
+ pendingComponentRouteRevalidation = false;
425
+ if (hmrRoutes) {
426
+ patchCurrentRouteMatches(router, hmrRoutes);
427
+ }
408
428
  Object.assign(manifest, nextManifest);
409
- }
410
- // Component-only updates do not need a full loader revalidation.
411
- if (
412
- shouldRefreshRouteState &&
413
- (routesToRevalidate.size > 0 || shouldRevalidate)
414
- ) {
415
- if (await refreshRouteState(router)) {
416
- shouldRevalidate = false;
429
+ await refreshRouteState(router);
430
+ shouldRevalidate = false;
431
+ } else if (nextManifest) {
432
+ if (hmrRoutes) {
433
+ patchCurrentRouteMatches(router, hmrRoutes);
434
+ }
435
+ Object.assign(manifest, nextManifest);
436
+ // The node compiler also emits an HDR revision for this route edit. If it
437
+ // did not arrive in this flush, consume that redundant revalidation later.
438
+ pendingComponentRouteRevalidation = !shouldRevalidate;
439
+ shouldRevalidate = false;
440
+ } else if (shouldRevalidate) {
441
+ if (pendingComponentRouteRevalidation) {
442
+ pendingComponentRouteRevalidation = false;
443
+ } else {
444
+ await revalidateRouter(router);
417
445
  }
418
- }
419
- if (shouldRevalidate) {
420
- await revalidateRouter(router);
421
446
  }
422
447
  performReactRefresh();
423
448
  }
424
449
 
425
450
  if (typeof window !== 'undefined' && import.meta.webpackHot) {
451
+ import.meta.webpackHot.on(
452
+ ${JSON.stringify(DEV_MANIFEST_UPDATE_EVENT)},
453
+ applyManifestUpdate
454
+ );
426
455
  import.meta.webpackHot.accept(
427
456
  ${JSON.stringify(hdrRevisionFilePath)},
428
- scheduleReactRouterRevalidation
457
+ () => {
458
+ latestHdrRevision = __hdrRevision;
459
+ scheduleReactRouterRevalidation();
460
+ }
429
461
  );
430
462
  }
431
463
  `;
@@ -5,7 +5,7 @@ import type { ServerBuild } from 'react-router';
5
5
  import type { ReactRouterManifestForDev } from './manifest.js';
6
6
  import { getCappedPluginConcurrency } from './concurrency.js';
7
7
  import { runPluginEffect, tryPluginPromise } from './effect-runtime.js';
8
- import { resolveServerBuildModuleEffect } from './server-build-resolution.js';
8
+ import { resolveServerBuildModule } from './server-build-resolution.js';
9
9
 
10
10
  export type ReactRouterDevManifest = ReactRouterManifestForDev;
11
11
 
@@ -137,14 +137,17 @@ export const getEnvironmentStats = (
137
137
  const startServerBuildEvaluationEffect = (
138
138
  server: RsbuildDevServer,
139
139
  entryName: string
140
- ): Effect.Effect<ServerBuild, Error, never> =>
140
+ ): Effect.Effect<readonly [string, ServerBuild], Error, never> =>
141
141
  tryPluginPromise(() => server.environments.node.loadBundle(entryName)).pipe(
142
142
  Effect.flatMap(buildModule =>
143
- resolveServerBuildModuleEffect(
144
- buildModule,
145
- `Server entry ${JSON.stringify(entryName)}`
143
+ tryPluginPromise(() =>
144
+ resolveServerBuildModule(
145
+ buildModule,
146
+ `Server entry ${JSON.stringify(entryName)}`
147
+ )
146
148
  )
147
- )
149
+ ),
150
+ Effect.map(build => [entryName, build] as const)
148
151
  );
149
152
 
150
153
  const evaluateServerBuildsEffect = (
@@ -152,12 +155,8 @@ const evaluateServerBuildsEffect = (
152
155
  entryNames: readonly string[]
153
156
  ): Effect.Effect<ReactRouterServerBuilds, Error, never> =>
154
157
  Effect.forEach(
155
- entryNames.map(entryName =>
156
- startServerBuildEvaluationEffect(server, entryName).pipe(
157
- Effect.map(build => [entryName, build] as const)
158
- )
159
- ),
160
- evaluation => evaluation,
158
+ entryNames,
159
+ entryName => startServerBuildEvaluationEffect(server, entryName),
161
160
  { concurrency: getCappedPluginConcurrency() }
162
161
  ).pipe(
163
162
  Effect.map(