-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdev-runtime-controller.ts
More file actions
588 lines (564 loc) · 18.3 KB
/
Copy pathdev-runtime-controller.ts
File metadata and controls
588 lines (564 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import type { RsbuildConfig, RsbuildPluginAPI, Rspack } from '@rsbuild/core';
import type { ServerBuild } from 'react-router';
import { PLUGIN_NAME } from './constants.js';
import { escapeHtml } from './plugin-utils.js';
import {
beginDevCompilerAttempt,
clearDevCompilerStart,
createCompilationIdentityTracker,
createDevCompilerPair,
hasPendingCompilation,
isLatestStartedCompilation,
markDevCompilerPending,
resetDevCompilerPair,
type DevCompilerPair,
} from './dev-runtime-compilation.js';
import {
createReactRouterDevRuntime,
loadReactRouterServerBuild,
registerReactRouterDevRuntime,
unregisterReactRouterDevRuntime,
} from './dev-generation.js';
import { createDevHdrIntentTracker } from './dev-hdr-intent.js';
import { createDevHdrChannel } from './dev-hdr-channel.js';
import { DEV_MANIFEST_UPDATE_EVENT } from './dev-hmr.js';
import {
getEnvironmentStats,
snapshotDevChangedFiles,
type DevGraphIdentity,
type DevRuntimeStats,
type ReactRouterDevBuildPlan,
type ReactRouterDevManifestSet,
} from './dev-runtime-artifacts.js';
import {
createDevRuntimeSessionManager,
type RuntimeBinding,
} from './dev-runtime-session.js';
import { normalizeEffectError } from './effect-runtime.js';
type ServerSetup = Exclude<
NonNullable<NonNullable<RsbuildConfig['server']>['setup']>,
unknown[]
>;
export type ReactRouterDevRuntimeController = {
captureWeb: (
compilation: Rspack.Compilation,
manifestsByEntryName: ReactRouterDevManifestSet
) => void;
createBuildLoader: (entryName?: string) => () => Promise<ServerBuild>;
};
type CreateControllerOptions = {
api: RsbuildPluginAPI;
isBuild: boolean;
buildPlan: ReactRouterDevBuildPlan;
/**
* The browser HMR runtime patches route manifest metadata (loader/action
* flags) in place, so metadata-only changes no longer need a full reload.
*/
clientPatchesRouteMetadata?: boolean | (() => boolean);
};
const CSS_SOURCE_RELOAD_DELAY_MS = 1000;
const isCssSourceFile = (file: string): boolean =>
/\.css(?:\.[cm]?[jt]s)?$/.test(file);
export const createReactRouterDevRuntimeController = ({
api,
isBuild,
buildPlan,
clientPatchesRouteMetadata,
}: CreateControllerOptions): ReactRouterDevRuntimeController => {
if (isBuild) {
return {
captureWeb() {},
createBuildLoader() {
return () =>
Promise.reject(
new Error(
`[${PLUGIN_NAME}] The development server runtime is unavailable during a production build.`
)
);
},
};
}
let scheduledCssAssetOwnershipReload:
| ReturnType<typeof setTimeout>
| undefined;
let lastCssAssetOwnershipReloadAt = 0;
let reloadAfterCssAssetOwnershipRemoval = false;
const sendCssAssetOwnershipReload = (): void => {
const binding = sessions.getActiveBinding();
if (!binding) {
return;
}
lastCssAssetOwnershipReloadAt = Date.now();
binding.server.sockWrite('full-reload', { path: '*' });
};
const scheduleCssAssetOwnershipReload = (): void => {
if (scheduledCssAssetOwnershipReload) {
clearTimeout(scheduledCssAssetOwnershipReload);
}
const scheduledAt = Date.now();
scheduledCssAssetOwnershipReload = setTimeout(() => {
scheduledCssAssetOwnershipReload = undefined;
if (lastCssAssetOwnershipReloadAt > scheduledAt) {
return;
}
sendCssAssetOwnershipReload();
}, CSS_SOURCE_RELOAD_DELAY_MS);
};
const hdrChannels = new WeakMap<
RuntimeBinding,
ReturnType<typeof createDevHdrChannel>
>();
const isHmrEnabled = () =>
typeof clientPatchesRouteMetadata === 'function'
? clientPatchesRouteMetadata()
: clientPatchesRouteMetadata === true;
const closeBinding = (binding: RuntimeBinding, error?: Error): void => {
hdrChannels.get(binding)?.close();
hdrChannels.delete(binding);
if (scheduledCssAssetOwnershipReload) {
clearTimeout(scheduledCssAssetOwnershipReload);
scheduledCssAssetOwnershipReload = undefined;
}
reloadAfterCssAssetOwnershipRemoval = false;
const pair = binding.compilers;
if (pair) {
resetDevCompilerPair(pair);
}
binding.compilers = undefined;
binding.runtime.close(error);
unregisterReactRouterDevRuntime(binding.server, binding.runtime);
};
const sessions = createDevRuntimeSessionManager(closeBinding);
const compilationIdentities = createCompilationIdentityTracker();
const { getCompilationIdentity } = compilationIdentities;
// Pending node-edit intent until a coherent commit retains that compilation.
const hdrIntentsByPair = new WeakMap<
DevCompilerPair,
ReturnType<typeof createDevHdrIntentTracker>
>();
const finishRuntimeAttempt = async (
binding: RuntimeBinding,
pair: DevCompilerPair,
stats: DevRuntimeStats,
changes: Parameters<RuntimeBinding['runtime']['finishAttempt']>[1],
identity: Parameters<RuntimeBinding['runtime']['finishAttempt']>[2]
): Promise<void> => {
try {
const result = await binding.runtime.finishAttempt(
stats,
changes,
identity
);
if (sessions.getActiveBinding()?.id !== binding.id) {
return;
}
if (result === 'retry-node') {
pair.node.watching?.invalidate();
return;
}
const nodeCompilation = getEnvironmentStats(stats, 'node')?.compilation;
if (
result === 'committed' &&
nodeCompilation &&
identity.node === binding.runtime.getCommittedNodeIdentity()
) {
hdrIntentsByPair.get(pair)?.signalCommitted(nodeCompilation, () => {
hdrChannels.get(binding)?.publish();
});
}
} catch (cause) {
if (sessions.getActiveBinding()?.id === binding.id) {
binding.runtime.failAttempt(normalizeEffectError(cause));
}
}
};
const flushSettledAttempt = (
binding: RuntimeBinding,
pair: DevCompilerPair
): void => {
const pending = pair.pendingAttempt;
if (
!pending ||
sessions.getActiveBinding()?.id !== binding.id ||
!pair.settledCompilations.has(pending.webCompilation) ||
!pair.settledCompilations.has(pending.nodeCompilation)
) {
return;
}
pair.pendingAttempt = undefined;
if (
!isLatestStartedCompilation(pending.identity.web, pair.latestWebStart) ||
!isLatestStartedCompilation(pending.identity.node, pair.latestNodeStart)
) {
return;
}
void finishRuntimeAttempt(
binding,
pair,
pending.stats,
pending.changes,
pending.identity
);
};
const rejectUnsupportedCompiler = (reason: string): void => {
const message = `[${PLUGIN_NAME}] Could not coordinate React Router development output because ${reason}.`;
api.logger.warn(message);
const binding = sessions.getActiveBinding();
if (!binding) {
return;
}
const error = new Error(message);
sessions.terminate(binding, error);
};
// Rsbuild runs server.setup before onBeforeStartDevServer. Prepending the
// observer here ensures setup callbacks cannot capture an unobserved close.
api.modifyRsbuildConfig({
order: 'post',
handler(config) {
const existingSetup = config.server?.setup;
const setup = existingSetup
? Array.isArray(existingSetup)
? existingSetup
: [existingSetup]
: [];
const observeServer: ServerSetup = context => {
if (context.action === 'dev') {
sessions.observeClose(context.server);
}
};
return {
...config,
server: {
...config.server,
setup: [observeServer, ...setup],
},
};
},
});
api.onBeforeStartDevServer({
order: 'pre',
async handler({ server }) {
sessions.assertCanStart();
const runtime = createReactRouterDevRuntime({
server,
buildPlan,
onEvaluationError(error) {
if (sessions.getActiveBinding()?.runtime !== runtime) {
return;
}
api.logger.error(error.message);
server.sockWrite('errors', {
text: [error.message],
html: escapeHtml(error.message),
});
},
onCssAssetOwnershipChanged(change) {
if (sessions.getActiveBinding()?.runtime !== runtime) {
return;
}
reloadAfterCssAssetOwnershipRemoval = change === 'removed';
sendCssAssetOwnershipReload();
},
onRouteManifestChanged(manifest) {
if (sessions.getActiveBinding()?.runtime !== runtime) {
return;
}
if (isHmrEnabled()) {
server.sockWrite('custom', {
event: DEV_MANIFEST_UPDATE_EVENT,
data: manifest.routes,
});
} else {
server.sockWrite('full-reload', { path: '*' });
}
},
onWarning: message => api.logger.warn(message),
});
const binding = sessions.createBinding(server, runtime);
hdrChannels.set(
binding,
createDevHdrChannel({
hot: server.environments.web.hot,
isEnabled: () =>
sessions.getActiveBinding() === binding && isHmrEnabled(),
})
);
registerReactRouterDevRuntime(server, runtime);
sessions.bindCloseObservation(binding);
},
});
api.onCloseDevServer({
order: 'pre',
handler() {
const binding = sessions.getActiveBinding();
if (!binding) {
return;
}
closeBinding(binding);
sessions.markClosing(binding);
},
});
api.onBeforeDevCompile({
order: 'pre',
handler() {
const binding = sessions.getActiveBinding();
const pair = binding?.compilers;
if (!binding || !pair || hasPendingCompilation(pair)) {
return;
}
beginDevCompilerAttempt(pair);
binding.runtime.beginAttempt();
},
});
api.onAfterCreateCompiler(({ compiler }) => {
if (!('compilers' in compiler)) {
rejectUnsupportedCompiler('Rsbuild did not create a multi-compiler');
return;
}
const web = compiler.compilers.find(item => item.name === 'web');
const node = compiler.compilers.find(item => item.name === 'node');
if (!web || !node) {
rejectUnsupportedCompiler('the web or node compiler was missing');
return;
}
const binding = sessions.getActiveBinding();
if (!binding) {
return;
}
const pair: DevCompilerPair = createDevCompilerPair({ web, node });
binding.compilers = pair;
const hdrIntents = createDevHdrIntentTracker();
hdrIntentsByPair.set(pair, hdrIntents);
const sessionId = binding.id;
const runtime = binding.runtime;
const failCurrentAttempt = (side: 'web' | 'node', error: Error): void => {
if (sessions.getActiveBinding()?.id === sessionId) {
if (side === 'web') {
clearDevCompilerStart(pair, 'latestWebStart');
} else {
clearDevCompilerStart(pair, 'latestNodeStart');
}
runtime.failAttempt(error);
}
};
const beginCompilerAttempt = (
side: 'latestWebStart' | 'latestNodeStart'
): void => {
if (
sessions.getActiveBinding()?.id === sessionId &&
pair[side]?.status !== 'pending'
) {
// Invalidation can arrive before the aggregate before-compile hook.
// Supersede any evaluation that could resolve in that gap immediately.
if (markDevCompilerPending(pair, side)) {
runtime.beginAttempt();
}
if (side === 'latestWebStart' && reloadAfterCssAssetOwnershipRemoval) {
reloadAfterCssAssetOwnershipRemoval = false;
scheduleCssAssetOwnershipReload();
}
}
};
web.hooks.invalid.tap(`${PLUGIN_NAME}:dev-web-invalid`, () =>
beginCompilerAttempt('latestWebStart')
);
node.hooks.invalid.tap(`${PLUGIN_NAME}:dev-node-invalid`, () =>
beginCompilerAttempt('latestNodeStart')
);
web.hooks.done.tap(
{ name: `${PLUGIN_NAME}:dev-web-complete`, stage: -1000 },
stats => {
if (sessions.getActiveBinding()?.id !== sessionId) {
return;
}
pair.latestCompletedWebIdentity = getCompilationIdentity(
stats.compilation
);
pair.latestCompletedWebStats = stats;
}
);
node.hooks.done.tap(
{ name: `${PLUGIN_NAME}:dev-node-complete`, stage: -1000 },
stats => {
if (sessions.getActiveBinding()?.id === sessionId) {
pair.latestCompletedNodeStats = stats;
}
}
);
web.hooks.thisCompilation.tap(
`${PLUGIN_NAME}:dev-web-compilation`,
compilation => {
if (sessions.getActiveBinding()?.id === sessionId) {
if (pair.currentAttemptIdentity) {
compilationIdentities.setAttemptIdentityForCompilation(
compilation,
pair.currentAttemptIdentity
);
}
pair.latestWebStart = {
status: 'started',
identity: getCompilationIdentity(compilation),
};
if (reloadAfterCssAssetOwnershipRemoval) {
reloadAfterCssAssetOwnershipRemoval = false;
scheduleCssAssetOwnershipReload();
}
}
}
);
node.hooks.thisCompilation.tap(
`${PLUGIN_NAME}:dev-node-web-compilation`,
compilation => {
if (sessions.getActiveBinding()?.id !== sessionId) {
return;
}
const changes = snapshotDevChangedFiles(pair.node);
hdrIntents.capture(
compilation,
changes.known &&
Array.from(changes.files).some(file => !isCssSourceFile(file))
);
pair.latestNodeStart = {
status: 'started',
identity: getCompilationIdentity(compilation),
};
if (pair.currentAttemptIdentity) {
compilationIdentities.setAttemptIdentityForCompilation(
compilation,
pair.currentAttemptIdentity
);
}
if (pair.latestCompletedWebIdentity) {
compilationIdentities.setWebIdentityForNodeCompilation(
compilation,
pair.latestCompletedWebIdentity
);
}
}
);
const settleCompilation = (stats: Rspack.Stats): void => {
if (sessions.getActiveBinding()?.id !== sessionId) {
return;
}
pair.settledCompilations.add(stats.compilation);
flushSettledAttempt(binding, pair);
};
web.hooks.afterDone.tap(
`${PLUGIN_NAME}:dev-web-settled`,
settleCompilation
);
node.hooks.afterDone.tap(
`${PLUGIN_NAME}:dev-node-settled`,
settleCompilation
);
web.hooks.failed.tap(`${PLUGIN_NAME}:dev-web-failed`, error =>
failCurrentAttempt('web', error)
);
node.hooks.failed.tap(`${PLUGIN_NAME}:dev-node-failed`, error =>
failCurrentAttempt('node', error)
);
});
api.onAfterDevCompile(async ({ stats }) => {
const binding = sessions.getActiveBinding();
const pair = binding?.compilers;
if (!binding || !pair) {
return;
}
const webStats =
getEnvironmentStats(stats, 'web') ?? pair.latestCompletedWebStats;
const nodeStats =
getEnvironmentStats(stats, 'node') ?? pair.latestCompletedNodeStats;
if (
(webStats && webStats.compilation.compiler !== pair.web) ||
(nodeStats && nodeStats.compilation.compiler !== pair.node)
) {
return;
}
const webIdentity = webStats
? getCompilationIdentity(webStats.compilation)
: undefined;
const nodeIdentity = nodeStats
? getCompilationIdentity(nodeStats.compilation)
: undefined;
if (
!isLatestStartedCompilation(webIdentity, pair.latestWebStart) ||
!isLatestStartedCompilation(nodeIdentity, pair.latestNodeStart)
) {
return;
}
const changes = {
web: snapshotDevChangedFiles(pair.web),
node: snapshotDevChangedFiles(pair.node),
};
const webAttempt = webStats
? compilationIdentities.getAttemptIdentityForCompilation(
webStats.compilation
)
: undefined;
const nodeAttempt = nodeStats
? compilationIdentities.getAttemptIdentityForCompilation(
nodeStats.compilation
)
: undefined;
const identity: DevGraphIdentity = {
web: webIdentity,
node: nodeIdentity,
nodeWeb: nodeStats
? compilationIdentities.getWebIdentityForNodeCompilation(
nodeStats.compilation
)
: undefined,
attempt:
webAttempt && nodeAttempt && webAttempt === nodeAttempt
? webAttempt
: undefined,
};
const finishStats: DevRuntimeStats =
webStats && nodeStats ? { web: webStats, node: nodeStats } : stats;
if (!webStats || !nodeStats) {
await finishRuntimeAttempt(binding, pair, finishStats, changes, identity);
return;
}
pair.pendingAttempt = {
stats: finishStats,
changes,
identity,
webCompilation: webStats.compilation,
nodeCompilation: nodeStats.compilation,
};
flushSettledAttempt(binding, pair);
});
return {
captureWeb(compilation, manifestsByEntryName): void {
const binding = sessions.getActiveBinding();
if (binding?.compilers?.web === compilation.compiler) {
binding.runtime.captureWeb(compilation, manifestsByEntryName);
}
},
createBuildLoader(entryName?: string): () => Promise<ServerBuild> {
// Pin the loader to the dev-server session active at creation time. Once a
// loader is handed to React Router for session N it must keep serving N (or
// fail loudly with 'not registered' once N closes) and never silently migrate
// to a replacement session — this preserves SSR generation/session coherency.
// The live fallback below applies ONLY when no session exists yet at creation
// (boundServer === undefined), i.e. a loader built during config setup before
// the dev server has started; there is no session to stay coherent with yet.
const boundServer = sessions.getActiveBinding()?.server;
return () => {
const server = boundServer ?? sessions.getActiveBinding()?.server;
if (server) {
return loadReactRouterServerBuild(server, entryName);
}
const state = sessions.getState();
if (state.status === 'terminal') {
return Promise.reject(state.error);
}
return Promise.reject(
new Error(
`[${PLUGIN_NAME}] The development server runtime is not ready.`
)
);
};
},
};
};