@c0va23/react-router-dev 7.8.3-alpha.1 → 7.9.4-patch.1

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.
package/dist/internal.js DELETED
@@ -1,2216 +0,0 @@
1
- /**
2
- * @c0va23/react-router-dev v7.8.3-alpha.1
3
- *
4
- * Copyright (c) Remix Software Inc.
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- "use strict";
12
- var __create = Object.create;
13
- var __defProp = Object.defineProperty;
14
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
- var __getOwnPropNames = Object.getOwnPropertyNames;
16
- var __getProtoOf = Object.getPrototypeOf;
17
- var __hasOwnProp = Object.prototype.hasOwnProperty;
18
- var __export = (target, all) => {
19
- for (var name in all)
20
- __defProp(target, name, { get: all[name], enumerable: true });
21
- };
22
- var __copyProps = (to, from, except, desc) => {
23
- if (from && typeof from === "object" || typeof from === "function") {
24
- for (let key of __getOwnPropNames(from))
25
- if (!__hasOwnProp.call(to, key) && key !== except)
26
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
- }
28
- return to;
29
- };
30
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
- // If the importer is in node compatibility mode or this is not an ESM
32
- // file that has been converted to a CommonJS file using a Babel-
33
- // compatible transform (i.e. "__esModule" has not been set), then set
34
- // "default" to the CommonJS "module.exports" for node compatibility.
35
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
36
- mod
37
- ));
38
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
39
-
40
- // internal.ts
41
- var internal_exports = {};
42
- __export(internal_exports, {
43
- __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__: () => __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__
44
- });
45
- module.exports = __toCommonJS(internal_exports);
46
-
47
- // vite/rsc/plugin.ts
48
- var import_es_module_lexer2 = require("es-module-lexer");
49
- var babel = __toESM(require("@babel/core"));
50
- var import_picocolors3 = __toESM(require("picocolors"));
51
-
52
- // vite/virtual-module.ts
53
- function create(name) {
54
- let id = `virtual:react-router/${name}`;
55
- return {
56
- id,
57
- resolvedId: `\0${id}`,
58
- url: `/@id/__x00__${id}`
59
- };
60
- }
61
-
62
- // typegen/index.ts
63
- var import_promises = __toESM(require("fs/promises"));
64
- var Path4 = __toESM(require("pathe"));
65
- var import_picocolors2 = require("picocolors");
66
-
67
- // config/config.ts
68
- var import_node_fs = __toESM(require("fs"));
69
- var import_node_child_process = require("child_process");
70
- var import_package_json = __toESM(require("@npmcli/package-json"));
71
-
72
- // vite/vite.ts
73
- var import_pathe2 = __toESM(require("pathe"));
74
-
75
- // invariant.ts
76
- function invariant(value, message) {
77
- if (value === false || value === null || typeof value === "undefined") {
78
- console.error(
79
- "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
80
- );
81
- throw new Error(message);
82
- }
83
- }
84
-
85
- // config/is-react-router-repo.ts
86
- var import_pathe = __toESM(require("pathe"));
87
- function isReactRouterRepo() {
88
- let serverRuntimePath = import_pathe.default.dirname(
89
- require.resolve("@react-router/node/package.json")
90
- );
91
- let serverRuntimeParentDir = import_pathe.default.basename(
92
- import_pathe.default.resolve(serverRuntimePath, "..")
93
- );
94
- return serverRuntimeParentDir === "packages";
95
- }
96
-
97
- // vite/vite.ts
98
- var vite;
99
- var viteImportSpecifier = isReactRouterRepo() ? (
100
- // Support testing against different versions of Vite by ensuring that Vite
101
- // is resolved from the current working directory when running within this
102
- // repo. If we don't do this, Vite will always be imported relative to this
103
- // file, which means that it will always resolve to Vite 6.
104
- `file:///${import_pathe2.default.normalize(
105
- require.resolve("vite/package.json", { paths: [process.cwd()] })
106
- ).replace("package.json", "dist/node/index.js")}`
107
- ) : "vite";
108
- async function preloadVite() {
109
- vite = await import(viteImportSpecifier);
110
- }
111
- function getVite() {
112
- invariant(vite, "getVite() called before preloadVite()");
113
- return vite;
114
- }
115
-
116
- // vite/ssr-externals.ts
117
- var ssrExternals = isReactRouterRepo() ? [
118
- // This is only needed within this repo because these packages
119
- // are linked to a directory outside of node_modules so Vite
120
- // treats them as internal code by default.
121
- "react-router",
122
- "react-router-dom",
123
- "@react-router/architect",
124
- "@react-router/cloudflare",
125
- "@react-router/dev",
126
- "@react-router/express",
127
- "@react-router/node",
128
- "@react-router/serve"
129
- ] : void 0;
130
-
131
- // vite/vite-node.ts
132
- async function createContext({
133
- root,
134
- mode,
135
- customLogger
136
- }) {
137
- await preloadVite();
138
- const vite2 = getVite();
139
- const [{ ViteNodeServer }, { ViteNodeRunner }, { installSourcemapsSupport }] = await Promise.all([
140
- import("vite-node/server"),
141
- import("vite-node/client"),
142
- import("vite-node/source-map")
143
- ]);
144
- const devServer = await vite2.createServer({
145
- root,
146
- mode,
147
- customLogger,
148
- server: {
149
- preTransformRequests: false,
150
- hmr: false,
151
- watch: null
152
- },
153
- ssr: {
154
- external: ssrExternals
155
- },
156
- optimizeDeps: {
157
- noDiscovery: true
158
- },
159
- css: {
160
- // This empty PostCSS config object prevents the PostCSS config file from
161
- // being loaded. We don't need it in a React Router config context, and
162
- // there's also an issue in Vite 5 when using a .ts PostCSS config file in
163
- // an ESM project: https://github.com/vitejs/vite/issues/15869. Consumers
164
- // can work around this in their own Vite config file, but they can't
165
- // configure this internal usage of vite-node.
166
- postcss: {}
167
- },
168
- configFile: false,
169
- envFile: false,
170
- plugins: []
171
- });
172
- await devServer.pluginContainer.buildStart({});
173
- const server = new ViteNodeServer(devServer);
174
- installSourcemapsSupport({
175
- getSourceMap: (source) => server.getSourceMap(source)
176
- });
177
- const runner = new ViteNodeRunner({
178
- root: devServer.config.root,
179
- base: devServer.config.base,
180
- fetchModule(id) {
181
- return server.fetchModule(id);
182
- },
183
- resolveId(id, importer) {
184
- return server.resolveId(id, importer);
185
- }
186
- });
187
- return { devServer, server, runner };
188
- }
189
-
190
- // config/config.ts
191
- var import_pathe3 = __toESM(require("pathe"));
192
- var import_chokidar = __toESM(require("chokidar"));
193
- var import_picocolors = __toESM(require("picocolors"));
194
- var import_pick2 = __toESM(require("lodash/pick"));
195
- var import_omit = __toESM(require("lodash/omit"));
196
- var import_cloneDeep = __toESM(require("lodash/cloneDeep"));
197
- var import_isEqual = __toESM(require("lodash/isEqual"));
198
-
199
- // config/routes.ts
200
- var Path = __toESM(require("pathe"));
201
- var v = __toESM(require("valibot"));
202
- var import_pick = __toESM(require("lodash/pick"));
203
- function setAppDirectory(directory) {
204
- globalThis.__reactRouterAppDirectory = directory;
205
- }
206
- var routeConfigEntrySchema = v.pipe(
207
- v.custom((value) => {
208
- return !(typeof value === "object" && value !== null && "then" in value && "catch" in value);
209
- }, "Invalid type: Expected object but received a promise. Did you forget to await?"),
210
- v.object({
211
- id: v.optional(
212
- v.pipe(
213
- v.string(),
214
- v.notValue("root", "A route cannot use the reserved id 'root'.")
215
- )
216
- ),
217
- path: v.optional(v.string()),
218
- index: v.optional(v.boolean()),
219
- caseSensitive: v.optional(v.boolean()),
220
- file: v.string(),
221
- children: v.optional(v.array(v.lazy(() => routeConfigEntrySchema)))
222
- })
223
- );
224
- var resolvedRouteConfigSchema = v.array(routeConfigEntrySchema);
225
- function validateRouteConfig({
226
- routeConfigFile,
227
- routeConfig
228
- }) {
229
- if (!routeConfig) {
230
- return {
231
- valid: false,
232
- message: `Route config must be the default export in "${routeConfigFile}".`
233
- };
234
- }
235
- if (!Array.isArray(routeConfig)) {
236
- return {
237
- valid: false,
238
- message: `Route config in "${routeConfigFile}" must be an array.`
239
- };
240
- }
241
- let { issues } = v.safeParse(resolvedRouteConfigSchema, routeConfig);
242
- if (issues?.length) {
243
- let { root, nested } = v.flatten(issues);
244
- return {
245
- valid: false,
246
- message: [
247
- `Route config in "${routeConfigFile}" is invalid.`,
248
- root ? `${root}` : [],
249
- nested ? Object.entries(nested).map(
250
- ([path6, message]) => `Path: routes.${path6}
251
- ${message}`
252
- ) : []
253
- ].flat().join("\n\n")
254
- };
255
- }
256
- return {
257
- valid: true,
258
- routeConfig
259
- };
260
- }
261
- function configRoutesToRouteManifest(appDirectory, routes) {
262
- let routeManifest = {};
263
- function walk(route, parentId) {
264
- let id = route.id || createRouteId(route.file);
265
- let manifestItem = {
266
- id,
267
- parentId,
268
- file: Path.isAbsolute(route.file) ? Path.relative(appDirectory, route.file) : route.file,
269
- path: route.path,
270
- index: route.index,
271
- caseSensitive: route.caseSensitive
272
- };
273
- if (routeManifest.hasOwnProperty(id)) {
274
- throw new Error(
275
- `Unable to define routes with duplicate route id: "${id}"`
276
- );
277
- }
278
- routeManifest[id] = manifestItem;
279
- if (route.children) {
280
- for (let child of route.children) {
281
- walk(child, id);
282
- }
283
- }
284
- }
285
- for (let route of routes) {
286
- walk(route);
287
- }
288
- return routeManifest;
289
- }
290
- function createRouteId(file) {
291
- return Path.normalize(stripFileExtension(file));
292
- }
293
- function stripFileExtension(file) {
294
- return file.replace(/\.[a-z0-9]+$/i, "");
295
- }
296
-
297
- // config/config.ts
298
- var excludedConfigPresetKeys = ["presets"];
299
- var mergeReactRouterConfig = (...configs) => {
300
- let reducer = (configA, configB) => {
301
- let mergeRequired = (key) => configA[key] !== void 0 && configB[key] !== void 0;
302
- return {
303
- ...configA,
304
- ...configB,
305
- ...mergeRequired("buildEnd") ? {
306
- buildEnd: async (...args) => {
307
- await Promise.all([
308
- configA.buildEnd?.(...args),
309
- configB.buildEnd?.(...args)
310
- ]);
311
- }
312
- } : {},
313
- ...mergeRequired("future") ? {
314
- future: {
315
- ...configA.future,
316
- ...configB.future
317
- }
318
- } : {},
319
- ...mergeRequired("presets") ? {
320
- presets: [...configA.presets ?? [], ...configB.presets ?? []]
321
- } : {}
322
- };
323
- };
324
- return configs.reduce(reducer, {});
325
- };
326
- var deepFreeze = (o) => {
327
- Object.freeze(o);
328
- let oIsFunction = typeof o === "function";
329
- let hasOwnProp = Object.prototype.hasOwnProperty;
330
- Object.getOwnPropertyNames(o).forEach(function(prop) {
331
- if (hasOwnProp.call(o, prop) && (oIsFunction ? prop !== "caller" && prop !== "callee" && prop !== "arguments" : true) && o[prop] !== null && (typeof o[prop] === "object" || typeof o[prop] === "function") && !Object.isFrozen(o[prop])) {
332
- deepFreeze(o[prop]);
333
- }
334
- });
335
- return o;
336
- };
337
- function ok(value) {
338
- return { ok: true, value };
339
- }
340
- function err(error) {
341
- return { ok: false, error };
342
- }
343
- async function resolveConfig({
344
- root,
345
- viteNodeContext,
346
- reactRouterConfigFile,
347
- skipRoutes,
348
- validateConfig
349
- }) {
350
- let reactRouterUserConfig = {};
351
- if (reactRouterConfigFile) {
352
- try {
353
- if (!import_node_fs.default.existsSync(reactRouterConfigFile)) {
354
- return err(`${reactRouterConfigFile} no longer exists`);
355
- }
356
- let configModule = await viteNodeContext.runner.executeFile(
357
- reactRouterConfigFile
358
- );
359
- if (configModule.default === void 0) {
360
- return err(`${reactRouterConfigFile} must provide a default export`);
361
- }
362
- if (typeof configModule.default !== "object") {
363
- return err(`${reactRouterConfigFile} must export a config`);
364
- }
365
- reactRouterUserConfig = configModule.default;
366
- if (validateConfig) {
367
- const error = validateConfig(reactRouterUserConfig);
368
- if (error) {
369
- return err(error);
370
- }
371
- }
372
- } catch (error) {
373
- return err(`Error loading ${reactRouterConfigFile}: ${error}`);
374
- }
375
- }
376
- reactRouterUserConfig = deepFreeze((0, import_cloneDeep.default)(reactRouterUserConfig));
377
- let presets = (await Promise.all(
378
- (reactRouterUserConfig.presets ?? []).map(async (preset) => {
379
- if (!preset.name) {
380
- throw new Error(
381
- "React Router presets must have a `name` property defined."
382
- );
383
- }
384
- if (!preset.reactRouterConfig) {
385
- return null;
386
- }
387
- let configPreset = (0, import_omit.default)(
388
- await preset.reactRouterConfig({ reactRouterUserConfig }),
389
- excludedConfigPresetKeys
390
- );
391
- return configPreset;
392
- })
393
- )).filter(function isNotNull(value) {
394
- return value !== null;
395
- });
396
- let defaults = {
397
- basename: "/",
398
- buildDirectory: "build",
399
- serverBuildFile: "index.js",
400
- serverModuleFormat: "esm",
401
- ssr: true
402
- };
403
- let userAndPresetConfigs = mergeReactRouterConfig(
404
- ...presets,
405
- reactRouterUserConfig
406
- );
407
- let {
408
- appDirectory: userAppDirectory,
409
- basename: basename2,
410
- buildDirectory: userBuildDirectory,
411
- buildEnd,
412
- prerender,
413
- routeDiscovery: userRouteDiscovery,
414
- serverBuildFile,
415
- serverBundles,
416
- serverModuleFormat,
417
- ssr
418
- } = {
419
- ...defaults,
420
- // Default values should be completely overridden by user/preset config, not merged
421
- ...userAndPresetConfigs
422
- };
423
- if (!ssr && serverBundles) {
424
- serverBundles = void 0;
425
- }
426
- let isValidPrerenderConfig = prerender == null || typeof prerender === "boolean" || Array.isArray(prerender) || typeof prerender === "function";
427
- if (!isValidPrerenderConfig) {
428
- return err(
429
- "The `prerender` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths"
430
- );
431
- }
432
- let routeDiscovery;
433
- if (userRouteDiscovery == null) {
434
- if (ssr) {
435
- routeDiscovery = {
436
- mode: "lazy",
437
- manifestPath: "/__manifest"
438
- };
439
- } else {
440
- routeDiscovery = { mode: "initial" };
441
- }
442
- } else if (userRouteDiscovery.mode === "initial") {
443
- routeDiscovery = userRouteDiscovery;
444
- } else if (userRouteDiscovery.mode === "lazy") {
445
- if (!ssr) {
446
- return err(
447
- 'The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`'
448
- );
449
- }
450
- let { manifestPath } = userRouteDiscovery;
451
- if (manifestPath != null && !manifestPath.startsWith("/")) {
452
- return err(
453
- 'The `routeDiscovery.manifestPath` config must be a root-relative pathname beginning with a slash (i.e., "/__manifest")'
454
- );
455
- }
456
- routeDiscovery = userRouteDiscovery;
457
- }
458
- let appDirectory = import_pathe3.default.resolve(root, userAppDirectory || "app");
459
- let buildDirectory = import_pathe3.default.resolve(root, userBuildDirectory);
460
- let rootRouteFile = findEntry(appDirectory, "root");
461
- if (!rootRouteFile) {
462
- let rootRouteDisplayPath = import_pathe3.default.relative(
463
- root,
464
- import_pathe3.default.join(appDirectory, "root.tsx")
465
- );
466
- return err(
467
- `Could not find a root route module in the app directory as "${rootRouteDisplayPath}"`
468
- );
469
- }
470
- let routes;
471
- let routeConfig = [];
472
- if (skipRoutes) {
473
- routes = {};
474
- } else {
475
- let routeConfigFile = findEntry(appDirectory, "routes");
476
- try {
477
- if (!routeConfigFile) {
478
- let routeConfigDisplayPath = import_pathe3.default.relative(
479
- root,
480
- import_pathe3.default.join(appDirectory, "routes.ts")
481
- );
482
- return err(
483
- `Route config file not found at "${routeConfigDisplayPath}".`
484
- );
485
- }
486
- setAppDirectory(appDirectory);
487
- let routeConfigExport = (await viteNodeContext.runner.executeFile(
488
- import_pathe3.default.join(appDirectory, routeConfigFile)
489
- )).default;
490
- let result = validateRouteConfig({
491
- routeConfigFile,
492
- routeConfig: await routeConfigExport
493
- });
494
- if (!result.valid) {
495
- return err(result.message);
496
- }
497
- routeConfig = [
498
- {
499
- id: "root",
500
- path: "",
501
- file: rootRouteFile,
502
- children: result.routeConfig
503
- }
504
- ];
505
- routes = configRoutesToRouteManifest(appDirectory, routeConfig);
506
- } catch (error) {
507
- return err(
508
- [
509
- import_picocolors.default.red(`Route config in "${routeConfigFile}" is invalid.`),
510
- "",
511
- error.loc?.file && error.loc?.column && error.frame ? [
512
- import_pathe3.default.relative(appDirectory, error.loc.file) + ":" + error.loc.line + ":" + error.loc.column,
513
- error.frame.trim?.()
514
- ] : error.stack
515
- ].flat().join("\n")
516
- );
517
- }
518
- }
519
- let future = {
520
- v8_middleware: reactRouterUserConfig.future?.v8_middleware ?? false,
521
- unstable_optimizeDeps: reactRouterUserConfig.future?.unstable_optimizeDeps ?? false,
522
- unstable_splitRouteModules: reactRouterUserConfig.future?.unstable_splitRouteModules ?? false,
523
- unstable_subResourceIntegrity: reactRouterUserConfig.future?.unstable_subResourceIntegrity ?? false,
524
- unstable_viteEnvironmentApi: reactRouterUserConfig.future?.unstable_viteEnvironmentApi ?? false
525
- };
526
- let reactRouterConfig = deepFreeze({
527
- appDirectory,
528
- basename: basename2,
529
- buildDirectory,
530
- buildEnd,
531
- future,
532
- prerender,
533
- routes,
534
- routeDiscovery,
535
- serverBuildFile,
536
- serverBundles,
537
- serverModuleFormat,
538
- ssr,
539
- unstable_routeConfig: routeConfig
540
- });
541
- for (let preset of reactRouterUserConfig.presets ?? []) {
542
- await preset.reactRouterConfigResolved?.({ reactRouterConfig });
543
- }
544
- return ok(reactRouterConfig);
545
- }
546
- async function createConfigLoader({
547
- rootDirectory: root,
548
- watch: watch2,
549
- mode,
550
- skipRoutes,
551
- validateConfig
552
- }) {
553
- root = import_pathe3.default.normalize(root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd());
554
- let vite2 = await import("vite");
555
- let viteNodeContext = await createContext({
556
- root,
557
- mode,
558
- // Filter out any info level logs from vite-node
559
- customLogger: vite2.createLogger("warn", {
560
- prefix: "[react-router]"
561
- })
562
- });
563
- let reactRouterConfigFile;
564
- let updateReactRouterConfigFile = () => {
565
- reactRouterConfigFile = findEntry(root, "react-router.config", {
566
- absolute: true
567
- });
568
- };
569
- updateReactRouterConfigFile();
570
- let getConfig = () => resolveConfig({
571
- root,
572
- viteNodeContext,
573
- reactRouterConfigFile,
574
- skipRoutes,
575
- validateConfig
576
- });
577
- let appDirectory;
578
- let initialConfigResult = await getConfig();
579
- if (!initialConfigResult.ok) {
580
- throw new Error(initialConfigResult.error);
581
- }
582
- appDirectory = import_pathe3.default.normalize(initialConfigResult.value.appDirectory);
583
- let currentConfig = initialConfigResult.value;
584
- let fsWatcher;
585
- let changeHandlers = [];
586
- return {
587
- getConfig,
588
- onChange: (handler) => {
589
- if (!watch2) {
590
- throw new Error(
591
- "onChange is not supported when watch mode is disabled"
592
- );
593
- }
594
- changeHandlers.push(handler);
595
- if (!fsWatcher) {
596
- fsWatcher = import_chokidar.default.watch([root, appDirectory], {
597
- ignoreInitial: true,
598
- ignored: (path6) => {
599
- let dirname4 = import_pathe3.default.dirname(path6);
600
- return !dirname4.startsWith(appDirectory) && // Ensure we're only watching files outside of the app directory
601
- // that are at the root level, not nested in subdirectories
602
- path6 !== root && // Watch the root directory itself
603
- dirname4 !== root;
604
- }
605
- });
606
- fsWatcher.on("all", async (...args) => {
607
- let [event, rawFilepath] = args;
608
- let filepath = import_pathe3.default.normalize(rawFilepath);
609
- let fileAddedOrRemoved = event === "add" || event === "unlink";
610
- let appFileAddedOrRemoved = fileAddedOrRemoved && filepath.startsWith(import_pathe3.default.normalize(appDirectory));
611
- let rootRelativeFilepath = import_pathe3.default.relative(root, filepath);
612
- let configFileAddedOrRemoved = fileAddedOrRemoved && isEntryFile("react-router.config", rootRelativeFilepath);
613
- if (configFileAddedOrRemoved) {
614
- updateReactRouterConfigFile();
615
- }
616
- let moduleGraphChanged = configFileAddedOrRemoved || Boolean(
617
- viteNodeContext.devServer?.moduleGraph.getModuleById(filepath)
618
- );
619
- if (!moduleGraphChanged && !appFileAddedOrRemoved) {
620
- return;
621
- }
622
- viteNodeContext.devServer?.moduleGraph.invalidateAll();
623
- viteNodeContext.runner?.moduleCache.clear();
624
- let result = await getConfig();
625
- let prevAppDirectory = appDirectory;
626
- appDirectory = import_pathe3.default.normalize(
627
- (result.value ?? currentConfig).appDirectory
628
- );
629
- if (appDirectory !== prevAppDirectory) {
630
- fsWatcher.unwatch(prevAppDirectory);
631
- fsWatcher.add(appDirectory);
632
- }
633
- let configCodeChanged = configFileAddedOrRemoved || reactRouterConfigFile !== void 0 && isEntryFileDependency(
634
- viteNodeContext.devServer.moduleGraph,
635
- reactRouterConfigFile,
636
- filepath
637
- );
638
- let routeConfigFile = !skipRoutes ? findEntry(appDirectory, "routes", {
639
- absolute: true
640
- }) : void 0;
641
- let routeConfigCodeChanged = routeConfigFile !== void 0 && isEntryFileDependency(
642
- viteNodeContext.devServer.moduleGraph,
643
- routeConfigFile,
644
- filepath
645
- );
646
- let configChanged = result.ok && !(0, import_isEqual.default)(omitRoutes(currentConfig), omitRoutes(result.value));
647
- let routeConfigChanged = result.ok && !(0, import_isEqual.default)(currentConfig?.routes, result.value.routes);
648
- for (let handler2 of changeHandlers) {
649
- handler2({
650
- result,
651
- configCodeChanged,
652
- routeConfigCodeChanged,
653
- configChanged,
654
- routeConfigChanged,
655
- path: filepath,
656
- event
657
- });
658
- }
659
- if (result.ok) {
660
- currentConfig = result.value;
661
- }
662
- });
663
- }
664
- return () => {
665
- changeHandlers = changeHandlers.filter(
666
- (changeHandler) => changeHandler !== handler
667
- );
668
- };
669
- },
670
- close: async () => {
671
- changeHandlers = [];
672
- await viteNodeContext.devServer.close();
673
- await fsWatcher?.close();
674
- }
675
- };
676
- }
677
- function omitRoutes(config) {
678
- return {
679
- ...config,
680
- routes: {}
681
- };
682
- }
683
- var entryExts = [".js", ".jsx", ".ts", ".tsx", ".mjs", ".mts"];
684
- function isEntryFile(entryBasename, filename2) {
685
- return entryExts.some((ext) => filename2 === `${entryBasename}${ext}`);
686
- }
687
- function findEntry(dir, basename2, options) {
688
- let currentDir = import_pathe3.default.resolve(dir);
689
- let { root } = import_pathe3.default.parse(currentDir);
690
- while (true) {
691
- for (let ext of options?.extensions ?? entryExts) {
692
- let file = import_pathe3.default.resolve(currentDir, basename2 + ext);
693
- if (import_node_fs.default.existsSync(file)) {
694
- return options?.absolute ?? false ? file : import_pathe3.default.relative(dir, file);
695
- }
696
- }
697
- if (!options?.walkParents) {
698
- return void 0;
699
- }
700
- let parentDir = import_pathe3.default.dirname(currentDir);
701
- if (currentDir === root || parentDir === currentDir) {
702
- return void 0;
703
- }
704
- currentDir = parentDir;
705
- }
706
- }
707
- function isEntryFileDependency(moduleGraph, entryFilepath, filepath, visited = /* @__PURE__ */ new Set()) {
708
- entryFilepath = import_pathe3.default.normalize(entryFilepath);
709
- filepath = import_pathe3.default.normalize(filepath);
710
- if (visited.has(filepath)) {
711
- return false;
712
- }
713
- visited.add(filepath);
714
- if (filepath === entryFilepath) {
715
- return true;
716
- }
717
- let mod = moduleGraph.getModuleById(filepath);
718
- if (!mod) {
719
- return false;
720
- }
721
- for (let importer of mod.importers) {
722
- if (!importer.id) {
723
- continue;
724
- }
725
- if (importer.id === entryFilepath || isEntryFileDependency(moduleGraph, entryFilepath, importer.id, visited)) {
726
- return true;
727
- }
728
- }
729
- return false;
730
- }
731
-
732
- // typegen/context.ts
733
- async function createContext2({
734
- rootDirectory,
735
- watch: watch2,
736
- mode
737
- }) {
738
- const configLoader = await createConfigLoader({ rootDirectory, mode, watch: watch2 });
739
- const configResult = await configLoader.getConfig();
740
- if (!configResult.ok) {
741
- throw new Error(configResult.error);
742
- }
743
- const config = configResult.value;
744
- return {
745
- configLoader,
746
- rootDirectory,
747
- config
748
- };
749
- }
750
-
751
- // typegen/generate.ts
752
- var import_dedent = __toESM(require("dedent"));
753
- var Path3 = __toESM(require("pathe"));
754
- var Pathe = __toESM(require("pathe/utils"));
755
-
756
- // vite/babel.ts
757
- var babel_exports = {};
758
- __export(babel_exports, {
759
- generate: () => generate,
760
- parse: () => import_parser.parse,
761
- t: () => t,
762
- traverse: () => traverse
763
- });
764
- var import_parser = require("@babel/parser");
765
- var t = __toESM(require("@babel/types"));
766
- var traverse = require("@babel/traverse").default;
767
- var generate = require("@babel/generator").default;
768
-
769
- // typegen/params.ts
770
- function parse2(fullpath2) {
771
- const result = {};
772
- let segments = fullpath2.split("/");
773
- segments.forEach((segment) => {
774
- const match = segment.match(/^:([\w-]+)(\?)?/);
775
- if (!match) return;
776
- const param = match[1];
777
- const isRequired = match[2] === void 0;
778
- result[param] ||= isRequired;
779
- return;
780
- });
781
- const hasSplat = segments.at(-1) === "*";
782
- if (hasSplat) result["*"] = true;
783
- return result;
784
- }
785
-
786
- // typegen/route.ts
787
- function lineage(routes, route) {
788
- const result = [];
789
- while (route) {
790
- result.push(route);
791
- if (!route.parentId) break;
792
- route = routes[route.parentId];
793
- }
794
- result.reverse();
795
- return result;
796
- }
797
- function fullpath(lineage2) {
798
- const route = lineage2.at(-1);
799
- if (lineage2.length === 1 && route?.id === "root") return "/";
800
- const isLayout = route && route.index !== true && route.path === void 0;
801
- if (isLayout) return void 0;
802
- return "/" + lineage2.map((route2) => route2.path?.replace(/^\//, "")?.replace(/\/$/, "")).filter((path6) => path6 !== void 0 && path6 !== "").join("/");
803
- }
804
-
805
- // typegen/generate.ts
806
- function typesDirectory(ctx) {
807
- return Path3.join(ctx.rootDirectory, ".react-router/types");
808
- }
809
- function generateFuture(ctx) {
810
- const filename2 = Path3.join(typesDirectory(ctx), "+future.ts");
811
- const content = import_dedent.default`
812
- // Generated by React Router
813
-
814
- import "react-router";
815
-
816
- declare module "react-router" {
817
- interface Future {
818
- middleware: ${ctx.config.future.v8_middleware}
819
- }
820
- }
821
- `;
822
- return { filename: filename2, content };
823
- }
824
- function generateServerBuild(ctx) {
825
- const filename2 = Path3.join(typesDirectory(ctx), "+server-build.d.ts");
826
- const content = import_dedent.default`
827
- // Generated by React Router
828
-
829
- declare module "virtual:react-router/server-build" {
830
- import { ServerBuild } from "react-router";
831
- export const assets: ServerBuild["assets"];
832
- export const assetsBuildDirectory: ServerBuild["assetsBuildDirectory"];
833
- export const basename: ServerBuild["basename"];
834
- export const entry: ServerBuild["entry"];
835
- export const future: ServerBuild["future"];
836
- export const isSpaMode: ServerBuild["isSpaMode"];
837
- export const prerender: ServerBuild["prerender"];
838
- export const publicPath: ServerBuild["publicPath"];
839
- export const routeDiscovery: ServerBuild["routeDiscovery"];
840
- export const routes: ServerBuild["routes"];
841
- export const ssr: ServerBuild["ssr"];
842
- export const unstable_getCriticalCss: ServerBuild["unstable_getCriticalCss"];
843
- }
844
- `;
845
- return { filename: filename2, content };
846
- }
847
- var { t: t2 } = babel_exports;
848
- function generateRoutes(ctx) {
849
- const fileToRoutes = /* @__PURE__ */ new Map();
850
- const lineages = /* @__PURE__ */ new Map();
851
- const allPages = /* @__PURE__ */ new Set();
852
- const routeToPages = /* @__PURE__ */ new Map();
853
- for (const route of Object.values(ctx.config.routes)) {
854
- let routeIds = fileToRoutes.get(route.file);
855
- if (!routeIds) {
856
- routeIds = /* @__PURE__ */ new Set();
857
- fileToRoutes.set(route.file, routeIds);
858
- }
859
- routeIds.add(route.id);
860
- const lineage2 = lineage(ctx.config.routes, route);
861
- lineages.set(route.id, lineage2);
862
- const fullpath2 = fullpath(lineage2);
863
- if (!fullpath2) continue;
864
- const pages = expand(fullpath2);
865
- pages.forEach((page) => allPages.add(page));
866
- lineage2.forEach(({ id }) => {
867
- let routePages = routeToPages.get(id);
868
- if (!routePages) {
869
- routePages = /* @__PURE__ */ new Set();
870
- routeToPages.set(id, routePages);
871
- }
872
- pages.forEach((page) => routePages.add(page));
873
- });
874
- }
875
- const routesTs = {
876
- filename: Path3.join(typesDirectory(ctx), "+routes.ts"),
877
- content: import_dedent.default`
878
- // Generated by React Router
879
-
880
- import "react-router"
881
-
882
- declare module "react-router" {
883
- interface Register {
884
- pages: Pages
885
- routeFiles: RouteFiles
886
- }
887
- }
888
- ` + "\n\n" + generate(pagesType(allPages)).code + "\n\n" + generate(routeFilesType({ fileToRoutes, routeToPages })).code
889
- };
890
- const allAnnotations = Array.from(fileToRoutes.entries()).filter(([file]) => isInAppDirectory(ctx, file)).map(
891
- ([file, routeIds]) => getRouteAnnotations({ ctx, file, routeIds, lineages })
892
- );
893
- return [routesTs, ...allAnnotations];
894
- }
895
- function pagesType(pages) {
896
- return t2.tsTypeAliasDeclaration(
897
- t2.identifier("Pages"),
898
- null,
899
- t2.tsTypeLiteral(
900
- Array.from(pages).map((page) => {
901
- return t2.tsPropertySignature(
902
- t2.stringLiteral(page),
903
- t2.tsTypeAnnotation(
904
- t2.tsTypeLiteral([
905
- t2.tsPropertySignature(
906
- t2.identifier("params"),
907
- t2.tsTypeAnnotation(paramsType(page))
908
- )
909
- ])
910
- )
911
- );
912
- })
913
- )
914
- );
915
- }
916
- function routeFilesType({
917
- fileToRoutes,
918
- routeToPages
919
- }) {
920
- return t2.tsTypeAliasDeclaration(
921
- t2.identifier("RouteFiles"),
922
- null,
923
- t2.tsTypeLiteral(
924
- Array.from(fileToRoutes).map(
925
- ([file, routeIds]) => t2.tsPropertySignature(
926
- t2.stringLiteral(file),
927
- t2.tsTypeAnnotation(
928
- t2.tsUnionType(
929
- Array.from(routeIds).map((routeId) => {
930
- const pages = routeToPages.get(routeId) ?? /* @__PURE__ */ new Set();
931
- return t2.tsTypeLiteral([
932
- t2.tsPropertySignature(
933
- t2.identifier("id"),
934
- t2.tsTypeAnnotation(
935
- t2.tsLiteralType(t2.stringLiteral(routeId))
936
- )
937
- ),
938
- t2.tsPropertySignature(
939
- t2.identifier("page"),
940
- t2.tsTypeAnnotation(
941
- pages ? t2.tsUnionType(
942
- Array.from(pages).map(
943
- (page) => t2.tsLiteralType(t2.stringLiteral(page))
944
- )
945
- ) : t2.tsNeverKeyword()
946
- )
947
- )
948
- ]);
949
- })
950
- )
951
- )
952
- )
953
- )
954
- )
955
- );
956
- }
957
- function isInAppDirectory(ctx, routeFile) {
958
- const path6 = Path3.resolve(ctx.config.appDirectory, routeFile);
959
- return path6.startsWith(ctx.config.appDirectory);
960
- }
961
- function getRouteAnnotations({
962
- ctx,
963
- file,
964
- routeIds,
965
- lineages
966
- }) {
967
- const filename2 = Path3.join(
968
- typesDirectory(ctx),
969
- Path3.relative(ctx.rootDirectory, ctx.config.appDirectory),
970
- Path3.dirname(file),
971
- "+types",
972
- Pathe.filename(file) + ".ts"
973
- );
974
- const matchesType = t2.tsTypeAliasDeclaration(
975
- t2.identifier("Matches"),
976
- null,
977
- t2.tsUnionType(
978
- Array.from(routeIds).map((routeId) => {
979
- const lineage2 = lineages.get(routeId);
980
- return t2.tsTupleType(
981
- lineage2.map(
982
- (route) => t2.tsTypeLiteral([
983
- t2.tsPropertySignature(
984
- t2.identifier("id"),
985
- t2.tsTypeAnnotation(t2.tsLiteralType(t2.stringLiteral(route.id)))
986
- ),
987
- t2.tsPropertySignature(
988
- t2.identifier("module"),
989
- t2.tsTypeAnnotation(
990
- t2.tsTypeQuery(
991
- t2.tsImportType(
992
- t2.stringLiteral(
993
- relativeImportSource(
994
- rootDirsPath(ctx, filename2),
995
- Path3.resolve(ctx.config.appDirectory, route.file)
996
- )
997
- )
998
- )
999
- )
1000
- )
1001
- )
1002
- ])
1003
- )
1004
- );
1005
- })
1006
- )
1007
- );
1008
- const routeImportSource = relativeImportSource(
1009
- rootDirsPath(ctx, filename2),
1010
- Path3.resolve(ctx.config.appDirectory, file)
1011
- );
1012
- const content = import_dedent.default`
1013
- // Generated by React Router
1014
-
1015
- import type { GetInfo, GetAnnotations } from "react-router/internal";
1016
-
1017
- type Module = typeof import("${routeImportSource}")
1018
-
1019
- type Info = GetInfo<{
1020
- file: "${file}",
1021
- module: Module
1022
- }>
1023
- ` + "\n\n" + generate(matchesType).code + "\n\n" + import_dedent.default`
1024
- type Annotations = GetAnnotations<Info & { module: Module, matches: Matches }>;
1025
-
1026
- export namespace Route {
1027
- // links
1028
- export type LinkDescriptors = Annotations["LinkDescriptors"];
1029
- export type LinksFunction = Annotations["LinksFunction"];
1030
-
1031
- // meta
1032
- export type MetaArgs = Annotations["MetaArgs"];
1033
- export type MetaDescriptors = Annotations["MetaDescriptors"];
1034
- export type MetaFunction = Annotations["MetaFunction"];
1035
-
1036
- // headers
1037
- export type HeadersArgs = Annotations["HeadersArgs"];
1038
- export type HeadersFunction = Annotations["HeadersFunction"];
1039
-
1040
- // middleware
1041
- export type MiddlewareFunction = Annotations["MiddlewareFunction"];
1042
-
1043
- // clientMiddleware
1044
- export type ClientMiddlewareFunction = Annotations["ClientMiddlewareFunction"];
1045
-
1046
- // loader
1047
- export type LoaderArgs = Annotations["LoaderArgs"];
1048
-
1049
- // clientLoader
1050
- export type ClientLoaderArgs = Annotations["ClientLoaderArgs"];
1051
-
1052
- // action
1053
- export type ActionArgs = Annotations["ActionArgs"];
1054
-
1055
- // clientAction
1056
- export type ClientActionArgs = Annotations["ClientActionArgs"];
1057
-
1058
- // HydrateFallback
1059
- export type HydrateFallbackProps = Annotations["HydrateFallbackProps"];
1060
-
1061
- // Component
1062
- export type ComponentProps = Annotations["ComponentProps"];
1063
-
1064
- // ErrorBoundary
1065
- export type ErrorBoundaryProps = Annotations["ErrorBoundaryProps"];
1066
- }
1067
- `;
1068
- return { filename: filename2, content };
1069
- }
1070
- function relativeImportSource(from, to) {
1071
- let path6 = Path3.relative(Path3.dirname(from), to);
1072
- let extension = Path3.extname(path6);
1073
- path6 = Path3.join(Path3.dirname(path6), Pathe.filename(path6));
1074
- if (!path6.startsWith("../")) path6 = "./" + path6;
1075
- if (!extension || /\.(js|ts)x?$/.test(extension)) {
1076
- extension = ".js";
1077
- }
1078
- return path6 + extension;
1079
- }
1080
- function rootDirsPath(ctx, typesPath) {
1081
- const rel = Path3.relative(typesDirectory(ctx), typesPath);
1082
- return Path3.join(ctx.rootDirectory, rel);
1083
- }
1084
- function paramsType(path6) {
1085
- const params = parse2(path6);
1086
- return t2.tsTypeLiteral(
1087
- Object.entries(params).map(([param, isRequired]) => {
1088
- const property = t2.tsPropertySignature(
1089
- t2.stringLiteral(param),
1090
- t2.tsTypeAnnotation(t2.tsStringKeyword())
1091
- );
1092
- property.optional = !isRequired;
1093
- return property;
1094
- })
1095
- );
1096
- }
1097
- function expand(fullpath2) {
1098
- function recurse(segments2, index) {
1099
- if (index === segments2.length) return [""];
1100
- const segment = segments2[index];
1101
- const isOptional = segment.endsWith("?");
1102
- const isDynamic = segment.startsWith(":");
1103
- const required = segment.replace(/\?$/, "");
1104
- const keep = !isOptional || isDynamic;
1105
- const kept = isDynamic ? segment : required;
1106
- const withoutSegment = recurse(segments2, index + 1);
1107
- const withSegment = withoutSegment.map((rest) => [kept, rest].join("/"));
1108
- if (keep) return withSegment;
1109
- return [...withoutSegment, ...withSegment];
1110
- }
1111
- const segments = fullpath2.split("/");
1112
- const expanded = /* @__PURE__ */ new Set();
1113
- for (let result of recurse(segments, 0)) {
1114
- if (result !== "/") result = result.replace(/\/$/, "");
1115
- expanded.add(result);
1116
- }
1117
- return expanded;
1118
- }
1119
-
1120
- // typegen/index.ts
1121
- async function clearRouteModuleAnnotations(ctx) {
1122
- await import_promises.default.rm(
1123
- Path4.join(typesDirectory(ctx), Path4.basename(ctx.config.appDirectory)),
1124
- { recursive: true, force: true }
1125
- );
1126
- }
1127
- async function write(...files) {
1128
- return Promise.all(
1129
- files.map(async ({ filename: filename2, content }) => {
1130
- await import_promises.default.mkdir(Path4.dirname(filename2), { recursive: true });
1131
- await import_promises.default.writeFile(filename2, content);
1132
- })
1133
- );
1134
- }
1135
- async function watch(rootDirectory, { mode, logger }) {
1136
- const ctx = await createContext2({ rootDirectory, mode, watch: true });
1137
- await import_promises.default.rm(typesDirectory(ctx), { recursive: true, force: true });
1138
- await write(
1139
- generateFuture(ctx),
1140
- generateServerBuild(ctx),
1141
- ...generateRoutes(ctx)
1142
- );
1143
- logger?.info((0, import_picocolors2.green)("generated types"), { timestamp: true, clear: true });
1144
- ctx.configLoader.onChange(
1145
- async ({ result, configChanged, routeConfigChanged }) => {
1146
- if (!result.ok) {
1147
- logger?.error((0, import_picocolors2.red)(result.error), { timestamp: true, clear: true });
1148
- return;
1149
- }
1150
- ctx.config = result.value;
1151
- if (configChanged) {
1152
- await write(generateFuture(ctx));
1153
- logger?.info((0, import_picocolors2.green)("regenerated types"), {
1154
- timestamp: true,
1155
- clear: true
1156
- });
1157
- }
1158
- if (routeConfigChanged) {
1159
- await clearRouteModuleAnnotations(ctx);
1160
- await write(...generateRoutes(ctx));
1161
- logger?.info((0, import_picocolors2.green)("regenerated types"), {
1162
- timestamp: true,
1163
- clear: true
1164
- });
1165
- }
1166
- }
1167
- );
1168
- return {
1169
- close: async () => await ctx.configLoader.close()
1170
- };
1171
- }
1172
-
1173
- // vite/rsc/plugin.ts
1174
- var import_fs = require("fs");
1175
- var import_promises2 = require("fs/promises");
1176
- var import_pathe6 = __toESM(require("pathe"));
1177
-
1178
- // vite/has-dependency.ts
1179
- function hasDependency({
1180
- name,
1181
- rootDirectory
1182
- }) {
1183
- try {
1184
- return Boolean(require.resolve(name, { paths: [rootDirectory] }));
1185
- } catch (err2) {
1186
- return false;
1187
- }
1188
- }
1189
-
1190
- // vite/optimize-deps-entries.ts
1191
- var import_tinyglobby = require("tinyglobby");
1192
-
1193
- // vite/resolve-relative-route-file-path.ts
1194
- var import_pathe4 = __toESM(require("pathe"));
1195
- function resolveRelativeRouteFilePath(route, reactRouterConfig) {
1196
- let vite2 = getVite();
1197
- let file = route.file;
1198
- let fullPath = import_pathe4.default.resolve(reactRouterConfig.appDirectory, file);
1199
- return vite2.normalizePath(fullPath);
1200
- }
1201
-
1202
- // vite/optimize-deps-entries.ts
1203
- function getOptimizeDepsEntries({
1204
- entryClientFilePath,
1205
- reactRouterConfig
1206
- }) {
1207
- if (!reactRouterConfig.future.unstable_optimizeDeps) {
1208
- return [];
1209
- }
1210
- const vite2 = getVite();
1211
- const viteMajorVersion = parseInt(vite2.version.split(".")[0], 10);
1212
- return [
1213
- vite2.normalizePath(entryClientFilePath),
1214
- ...Object.values(reactRouterConfig.routes).map(
1215
- (route) => resolveRelativeRouteFilePath(route, reactRouterConfig)
1216
- )
1217
- ].map(
1218
- (entry) => (
1219
- // In Vite 7, the `optimizeDeps.entries` option only accepts glob patterns.
1220
- // In prior versions, absolute file paths were treated differently.
1221
- viteMajorVersion >= 7 ? (0, import_tinyglobby.escapePath)(entry) : entry
1222
- )
1223
- );
1224
- }
1225
-
1226
- // vite/rsc/virtual-route-config.ts
1227
- var import_pathe5 = __toESM(require("pathe"));
1228
- function createVirtualRouteConfig({
1229
- appDirectory,
1230
- routeConfig
1231
- }) {
1232
- let routeIdByFile = /* @__PURE__ */ new Map();
1233
- let code = "export default [";
1234
- const closeRouteSymbol = Symbol("CLOSE_ROUTE");
1235
- let stack = [
1236
- ...routeConfig
1237
- ];
1238
- while (stack.length > 0) {
1239
- const route = stack.pop();
1240
- if (!route) break;
1241
- if (route === closeRouteSymbol) {
1242
- code += "]},";
1243
- continue;
1244
- }
1245
- code += "{";
1246
- const routeFile = import_pathe5.default.resolve(appDirectory, route.file);
1247
- const routeId = route.id || createRouteId2(route.file, appDirectory);
1248
- routeIdByFile.set(routeFile, routeId);
1249
- code += `lazy: () => import(${JSON.stringify(
1250
- `${routeFile}?route-module${routeId === "root" ? "&root-route=true" : ""}`
1251
- )}),`;
1252
- code += `id: ${JSON.stringify(routeId)},`;
1253
- if (typeof route.path === "string") {
1254
- code += `path: ${JSON.stringify(route.path)},`;
1255
- }
1256
- if (route.index) {
1257
- code += `index: true,`;
1258
- }
1259
- if (route.caseSensitive) {
1260
- code += `caseSensitive: true,`;
1261
- }
1262
- if (route.children) {
1263
- code += ["children:["];
1264
- stack.push(closeRouteSymbol);
1265
- stack.push(...[...route.children].reverse());
1266
- } else {
1267
- code += "},";
1268
- }
1269
- }
1270
- code += "];\n";
1271
- return { code, routeIdByFile };
1272
- }
1273
- function createRouteId2(file, appDirectory) {
1274
- return import_pathe5.default.relative(appDirectory, file).replace(/\\+/, "/").slice(0, -import_pathe5.default.extname(file).length);
1275
- }
1276
-
1277
- // vite/rsc/virtual-route-modules.ts
1278
- var import_es_module_lexer = require("es-module-lexer");
1279
-
1280
- // vite/remove-exports.ts
1281
- var import_babel_dead_code_elimination = require("babel-dead-code-elimination");
1282
- var removeExports = (ast, exportsToRemove) => {
1283
- let previouslyReferencedIdentifiers = (0, import_babel_dead_code_elimination.findReferencedIdentifiers)(ast);
1284
- let exportsFiltered = false;
1285
- let markedForRemoval = /* @__PURE__ */ new Set();
1286
- let removedExportLocalNames = /* @__PURE__ */ new Set();
1287
- traverse(ast, {
1288
- ExportDeclaration(path6) {
1289
- if (path6.node.type === "ExportNamedDeclaration") {
1290
- if (path6.node.specifiers.length) {
1291
- path6.node.specifiers = path6.node.specifiers.filter((specifier) => {
1292
- if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier") {
1293
- if (exportsToRemove.includes(specifier.exported.name)) {
1294
- exportsFiltered = true;
1295
- if (specifier.local && specifier.local.name !== specifier.exported.name) {
1296
- removedExportLocalNames.add(specifier.local.name);
1297
- }
1298
- return false;
1299
- }
1300
- }
1301
- return true;
1302
- });
1303
- if (path6.node.specifiers.length === 0) {
1304
- markedForRemoval.add(path6);
1305
- }
1306
- }
1307
- if (path6.node.declaration?.type === "VariableDeclaration") {
1308
- let declaration = path6.node.declaration;
1309
- declaration.declarations = declaration.declarations.filter(
1310
- (declaration2) => {
1311
- if (declaration2.id.type === "Identifier" && exportsToRemove.includes(declaration2.id.name)) {
1312
- exportsFiltered = true;
1313
- return false;
1314
- }
1315
- if (declaration2.id.type === "ArrayPattern" || declaration2.id.type === "ObjectPattern") {
1316
- validateDestructuredExports(declaration2.id, exportsToRemove);
1317
- }
1318
- return true;
1319
- }
1320
- );
1321
- if (declaration.declarations.length === 0) {
1322
- markedForRemoval.add(path6);
1323
- }
1324
- }
1325
- if (path6.node.declaration?.type === "FunctionDeclaration") {
1326
- let id = path6.node.declaration.id;
1327
- if (id && exportsToRemove.includes(id.name)) {
1328
- markedForRemoval.add(path6);
1329
- }
1330
- }
1331
- if (path6.node.declaration?.type === "ClassDeclaration") {
1332
- let id = path6.node.declaration.id;
1333
- if (id && exportsToRemove.includes(id.name)) {
1334
- markedForRemoval.add(path6);
1335
- }
1336
- }
1337
- }
1338
- if (path6.node.type === "ExportDefaultDeclaration") {
1339
- if (exportsToRemove.includes("default")) {
1340
- markedForRemoval.add(path6);
1341
- if (path6.node.declaration) {
1342
- if (path6.node.declaration.type === "Identifier") {
1343
- removedExportLocalNames.add(path6.node.declaration.name);
1344
- } else if ((path6.node.declaration.type === "FunctionDeclaration" || path6.node.declaration.type === "ClassDeclaration") && path6.node.declaration.id) {
1345
- removedExportLocalNames.add(path6.node.declaration.id.name);
1346
- }
1347
- }
1348
- }
1349
- }
1350
- }
1351
- });
1352
- traverse(ast, {
1353
- ExpressionStatement(path6) {
1354
- if (!path6.parentPath.isProgram()) {
1355
- return;
1356
- }
1357
- if (path6.node.expression.type === "AssignmentExpression") {
1358
- const left = path6.node.expression.left;
1359
- if (left.type === "MemberExpression" && left.object.type === "Identifier" && (exportsToRemove.includes(left.object.name) || removedExportLocalNames.has(left.object.name))) {
1360
- markedForRemoval.add(path6);
1361
- }
1362
- }
1363
- }
1364
- });
1365
- if (markedForRemoval.size > 0 || exportsFiltered) {
1366
- for (let path6 of markedForRemoval) {
1367
- path6.remove();
1368
- }
1369
- (0, import_babel_dead_code_elimination.deadCodeElimination)(ast, previouslyReferencedIdentifiers);
1370
- }
1371
- };
1372
- function validateDestructuredExports(id, exportsToRemove) {
1373
- if (id.type === "ArrayPattern") {
1374
- for (let element of id.elements) {
1375
- if (!element) {
1376
- continue;
1377
- }
1378
- if (element.type === "Identifier" && exportsToRemove.includes(element.name)) {
1379
- throw invalidDestructureError(element.name);
1380
- }
1381
- if (element.type === "RestElement" && element.argument.type === "Identifier" && exportsToRemove.includes(element.argument.name)) {
1382
- throw invalidDestructureError(element.argument.name);
1383
- }
1384
- if (element.type === "ArrayPattern" || element.type === "ObjectPattern") {
1385
- validateDestructuredExports(element, exportsToRemove);
1386
- }
1387
- }
1388
- }
1389
- if (id.type === "ObjectPattern") {
1390
- for (let property of id.properties) {
1391
- if (!property) {
1392
- continue;
1393
- }
1394
- if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
1395
- if (property.value.type === "Identifier" && exportsToRemove.includes(property.value.name)) {
1396
- throw invalidDestructureError(property.value.name);
1397
- }
1398
- if (property.value.type === "ArrayPattern" || property.value.type === "ObjectPattern") {
1399
- validateDestructuredExports(property.value, exportsToRemove);
1400
- }
1401
- }
1402
- if (property.type === "RestElement" && property.argument.type === "Identifier" && exportsToRemove.includes(property.argument.name)) {
1403
- throw invalidDestructureError(property.argument.name);
1404
- }
1405
- }
1406
- }
1407
- }
1408
- function invalidDestructureError(name) {
1409
- return new Error(`Cannot remove destructured export "${name}"`);
1410
- }
1411
-
1412
- // vite/rsc/virtual-route-modules.ts
1413
- var SERVER_ONLY_COMPONENT_EXPORTS = ["ServerComponent"];
1414
- var SERVER_ONLY_ROUTE_EXPORTS = [
1415
- ...SERVER_ONLY_COMPONENT_EXPORTS,
1416
- "loader",
1417
- "action",
1418
- "middleware",
1419
- "headers"
1420
- ];
1421
- var SERVER_ONLY_ROUTE_EXPORTS_SET = new Set(SERVER_ONLY_ROUTE_EXPORTS);
1422
- function isServerOnlyRouteExport(name) {
1423
- return SERVER_ONLY_ROUTE_EXPORTS_SET.has(name);
1424
- }
1425
- var COMMON_COMPONENT_EXPORTS = [
1426
- "ErrorBoundary",
1427
- "HydrateFallback",
1428
- "Layout"
1429
- ];
1430
- var SERVER_FIRST_COMPONENT_EXPORTS = [
1431
- ...COMMON_COMPONENT_EXPORTS,
1432
- ...SERVER_ONLY_COMPONENT_EXPORTS
1433
- ];
1434
- var SERVER_FIRST_COMPONENT_EXPORTS_SET = new Set(
1435
- SERVER_FIRST_COMPONENT_EXPORTS
1436
- );
1437
- function isServerFirstComponentExport(name) {
1438
- return SERVER_FIRST_COMPONENT_EXPORTS_SET.has(
1439
- name
1440
- );
1441
- }
1442
- var CLIENT_COMPONENT_EXPORTS = [
1443
- ...COMMON_COMPONENT_EXPORTS,
1444
- "default"
1445
- ];
1446
- var CLIENT_NON_COMPONENT_EXPORTS = [
1447
- "clientAction",
1448
- "clientLoader",
1449
- "clientMiddleware",
1450
- "handle",
1451
- "meta",
1452
- "links",
1453
- "shouldRevalidate"
1454
- ];
1455
- var CLIENT_NON_COMPONENT_EXPORTS_SET = new Set(CLIENT_NON_COMPONENT_EXPORTS);
1456
- function isClientNonComponentExport(name) {
1457
- return CLIENT_NON_COMPONENT_EXPORTS_SET.has(name);
1458
- }
1459
- var CLIENT_ROUTE_EXPORTS = [
1460
- ...CLIENT_NON_COMPONENT_EXPORTS,
1461
- ...CLIENT_COMPONENT_EXPORTS
1462
- ];
1463
- var CLIENT_ROUTE_EXPORTS_SET = new Set(CLIENT_ROUTE_EXPORTS);
1464
- function isClientRouteExport(name) {
1465
- return CLIENT_ROUTE_EXPORTS_SET.has(name);
1466
- }
1467
- var ROUTE_EXPORTS = [
1468
- ...SERVER_ONLY_ROUTE_EXPORTS,
1469
- ...CLIENT_ROUTE_EXPORTS
1470
- ];
1471
- var ROUTE_EXPORTS_SET = new Set(ROUTE_EXPORTS);
1472
- function isRouteExport(name) {
1473
- return ROUTE_EXPORTS_SET.has(name);
1474
- }
1475
- function isCustomRouteExport(name) {
1476
- return !isRouteExport(name);
1477
- }
1478
- function hasReactServerCondition(viteEnvironment) {
1479
- return viteEnvironment.config.resolve.conditions.includes("react-server");
1480
- }
1481
- function transformVirtualRouteModules({
1482
- id,
1483
- code,
1484
- viteCommand,
1485
- routeIdByFile,
1486
- viteEnvironment
1487
- }) {
1488
- if (isVirtualRouteModuleId(id) || routeIdByFile.has(id)) {
1489
- return createVirtualRouteModuleCode({
1490
- id,
1491
- code,
1492
- viteCommand,
1493
- viteEnvironment
1494
- });
1495
- }
1496
- if (isVirtualServerRouteModuleId(id)) {
1497
- return createVirtualServerRouteModuleCode({ id, code, viteEnvironment });
1498
- }
1499
- if (isVirtualClientRouteModuleId(id)) {
1500
- return createVirtualClientRouteModuleCode({ id, code, viteCommand });
1501
- }
1502
- }
1503
- async function createVirtualRouteModuleCode({
1504
- id,
1505
- code: routeSource,
1506
- viteCommand,
1507
- viteEnvironment
1508
- }) {
1509
- const isReactServer = hasReactServerCondition(viteEnvironment);
1510
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
1511
- const clientModuleId = getVirtualClientModuleId(id);
1512
- const serverModuleId = getVirtualServerModuleId(id);
1513
- let code = "";
1514
- if (isServerFirstRoute) {
1515
- if (staticExports.some(isServerFirstComponentExport)) {
1516
- code += `import React from "react";
1517
- `;
1518
- }
1519
- for (const staticExport of staticExports) {
1520
- if (isClientNonComponentExport(staticExport)) {
1521
- code += `export { ${staticExport} } from "${clientModuleId}";
1522
- `;
1523
- } else if (isReactServer && isServerFirstComponentExport(staticExport) && // Layout wraps all other component exports so doesn't need CSS injected
1524
- staticExport !== "Layout") {
1525
- code += `import { ${staticExport} as ${staticExport}WithoutCss } from "${serverModuleId}";
1526
- `;
1527
- code += `export ${staticExport === "ServerComponent" ? "default " : " "}function ${staticExport}(props) {
1528
- `;
1529
- code += ` return React.createElement(React.Fragment, null,
1530
- `;
1531
- code += ` import.meta.viteRsc.loadCss(),
1532
- `;
1533
- code += ` React.createElement(${staticExport}WithoutCss, props),
1534
- `;
1535
- code += ` );
1536
- `;
1537
- code += `}
1538
- `;
1539
- } else if (isReactServer && isRouteExport(staticExport)) {
1540
- code += `export { ${staticExport} } from "${serverModuleId}";
1541
- `;
1542
- } else if (isCustomRouteExport(staticExport)) {
1543
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
1544
- `;
1545
- }
1546
- }
1547
- if (viteCommand === "serve" && !hasClientExports) {
1548
- code += `export { __ensureClientRouteModuleForHMR } from "${clientModuleId}";
1549
- `;
1550
- }
1551
- } else {
1552
- for (const staticExport of staticExports) {
1553
- if (isClientRouteExport(staticExport)) {
1554
- code += `export { ${staticExport} } from "${clientModuleId}";
1555
- `;
1556
- } else if (isReactServer && isServerOnlyRouteExport(staticExport)) {
1557
- code += `export { ${staticExport} } from "${serverModuleId}";
1558
- `;
1559
- } else if (isCustomRouteExport(staticExport)) {
1560
- code += `export { ${staticExport} } from "${isReactServer ? serverModuleId : clientModuleId}";
1561
- `;
1562
- }
1563
- }
1564
- }
1565
- if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1566
- code += `export { ErrorBoundary } from "${clientModuleId}";
1567
- `;
1568
- }
1569
- return code;
1570
- }
1571
- function createVirtualServerRouteModuleCode({
1572
- id,
1573
- code: routeSource,
1574
- viteEnvironment
1575
- }) {
1576
- if (!hasReactServerCondition(viteEnvironment)) {
1577
- throw new Error(
1578
- [
1579
- "Virtual server route module was loaded outside of the RSC environment.",
1580
- `Environment Name: ${viteEnvironment.name}`,
1581
- `Module ID: ${id}`
1582
- ].join("\n")
1583
- );
1584
- }
1585
- const { staticExports, isServerFirstRoute } = parseRouteExports(routeSource);
1586
- const clientModuleId = getVirtualClientModuleId(id);
1587
- const serverRouteModuleAst = import_parser.parse(routeSource, {
1588
- sourceType: "module"
1589
- });
1590
- removeExports(
1591
- serverRouteModuleAst,
1592
- isServerFirstRoute ? CLIENT_NON_COMPONENT_EXPORTS : CLIENT_ROUTE_EXPORTS
1593
- );
1594
- const generatorResult = generate(serverRouteModuleAst);
1595
- if (!isServerFirstRoute) {
1596
- for (const staticExport of staticExports) {
1597
- if (isClientRouteExport(staticExport)) {
1598
- generatorResult.code += "\n";
1599
- generatorResult.code += `export { ${staticExport} } from "${clientModuleId}";
1600
- `;
1601
- }
1602
- }
1603
- }
1604
- return generatorResult;
1605
- }
1606
- function createVirtualClientRouteModuleCode({
1607
- id,
1608
- code: routeSource,
1609
- viteCommand
1610
- }) {
1611
- const { staticExports, isServerFirstRoute, hasClientExports } = parseRouteExports(routeSource);
1612
- const exportsToRemove = isServerFirstRoute ? [...SERVER_ONLY_ROUTE_EXPORTS, ...CLIENT_COMPONENT_EXPORTS] : SERVER_ONLY_ROUTE_EXPORTS;
1613
- const clientRouteModuleAst = import_parser.parse(routeSource, {
1614
- sourceType: "module"
1615
- });
1616
- removeExports(clientRouteModuleAst, exportsToRemove);
1617
- const generatorResult = generate(clientRouteModuleAst);
1618
- generatorResult.code = '"use client";' + generatorResult.code;
1619
- if (isRootRouteId(id) && !staticExports.includes("ErrorBoundary")) {
1620
- const hasRootLayout = staticExports.includes("Layout");
1621
- generatorResult.code += `
1622
- import { createElement as __rr_createElement } from "react";
1623
- `;
1624
- generatorResult.code += `import { UNSAFE_RSCDefaultRootErrorBoundary } from "react-router";
1625
- `;
1626
- generatorResult.code += `export function ErrorBoundary() {
1627
- `;
1628
- generatorResult.code += ` return __rr_createElement(UNSAFE_RSCDefaultRootErrorBoundary, { hasRootLayout: ${hasRootLayout} });
1629
- `;
1630
- generatorResult.code += `}
1631
- `;
1632
- }
1633
- if (viteCommand === "serve" && isServerFirstRoute && !hasClientExports) {
1634
- generatorResult.code += `
1635
- export const __ensureClientRouteModuleForHMR = true;`;
1636
- }
1637
- return generatorResult;
1638
- }
1639
- function parseRouteExports(code) {
1640
- const [, exportSpecifiers] = (0, import_es_module_lexer.parse)(code);
1641
- const staticExports = exportSpecifiers.map(({ n: name }) => name);
1642
- const isServerFirstRoute = staticExports.some(
1643
- (staticExport) => staticExport === "ServerComponent"
1644
- );
1645
- return {
1646
- staticExports,
1647
- isServerFirstRoute,
1648
- hasClientExports: staticExports.some(
1649
- isServerFirstRoute ? isClientNonComponentExport : isClientRouteExport
1650
- )
1651
- };
1652
- }
1653
- function getVirtualClientModuleId(id) {
1654
- return `${id.split("?")[0]}?client-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1655
- }
1656
- function getVirtualServerModuleId(id) {
1657
- return `${id.split("?")[0]}?server-route-module${isRootRouteId(id) ? "&root-route=true" : ""}`;
1658
- }
1659
- function isRootRouteId(id) {
1660
- return /(\?|&)root-route=true(&|$)/.test(id);
1661
- }
1662
- function isVirtualRouteModuleId(id) {
1663
- return /(\?|&)route-module(&|$)/.test(id);
1664
- }
1665
- function isVirtualClientRouteModuleId(id) {
1666
- return /(\?|&)client-route-module(&|$)/.test(id);
1667
- }
1668
- function isVirtualServerRouteModuleId(id) {
1669
- return /(\?|&)server-route-module(&|$)/.test(id);
1670
- }
1671
-
1672
- // vite/plugins/validate-plugin-order.ts
1673
- function validatePluginOrder() {
1674
- return {
1675
- name: "react-router:validate-plugin-order",
1676
- configResolved(viteConfig) {
1677
- let pluginIndex = (pluginName) => {
1678
- pluginName = Array.isArray(pluginName) ? pluginName : [pluginName];
1679
- return viteConfig.plugins.findIndex(
1680
- (plugin) => pluginName.includes(plugin.name)
1681
- );
1682
- };
1683
- let reactRouterRscPluginIndex = pluginIndex("react-router/rsc");
1684
- let viteRscPluginIndex = pluginIndex("rsc");
1685
- if (reactRouterRscPluginIndex >= 0 && viteRscPluginIndex >= 0 && reactRouterRscPluginIndex > viteRscPluginIndex) {
1686
- throw new Error(
1687
- `The "@vitejs/plugin-rsc" plugin should be placed after the React Router RSC plugin in your Vite config`
1688
- );
1689
- }
1690
- let reactRouterPluginIndex = pluginIndex([
1691
- "react-router",
1692
- "react-router/rsc"
1693
- ]);
1694
- let mdxPluginIndex = pluginIndex("@mdx-js/rollup");
1695
- if (mdxPluginIndex >= 0 && mdxPluginIndex > reactRouterPluginIndex) {
1696
- throw new Error(
1697
- `The "@mdx-js/rollup" plugin should be placed before the React Router plugin in your Vite config`
1698
- );
1699
- }
1700
- }
1701
- };
1702
- }
1703
-
1704
- // vite/rsc/plugin.ts
1705
- function reactRouterRSCVitePlugin() {
1706
- let configLoader;
1707
- let config;
1708
- let typegenWatcherPromise;
1709
- let viteCommand;
1710
- let routeIdByFile;
1711
- let logger;
1712
- const defaultEntries = getDefaultEntries();
1713
- return [
1714
- {
1715
- name: "react-router/rsc",
1716
- async config(viteUserConfig, { command, mode }) {
1717
- await import_es_module_lexer2.init;
1718
- await preloadVite();
1719
- viteCommand = command;
1720
- const rootDirectory = getRootDirectory(viteUserConfig);
1721
- const watch2 = command === "serve";
1722
- configLoader = await createConfigLoader({
1723
- rootDirectory,
1724
- mode,
1725
- watch: watch2,
1726
- validateConfig: (userConfig) => {
1727
- let errors = [];
1728
- if (userConfig.buildEnd) errors.push("buildEnd");
1729
- if (userConfig.prerender) errors.push("prerender");
1730
- if (userConfig.presets?.length) errors.push("presets");
1731
- if (userConfig.routeDiscovery) errors.push("routeDiscovery");
1732
- if (userConfig.serverBundles) errors.push("serverBundles");
1733
- if (userConfig.ssr === false) errors.push("ssr: false");
1734
- if (userConfig.future?.unstable_splitRouteModules)
1735
- errors.push("future.unstable_splitRouteModules");
1736
- if (userConfig.future?.unstable_viteEnvironmentApi === false)
1737
- errors.push("future.unstable_viteEnvironmentApi: false");
1738
- if (userConfig.future?.v8_middleware === false)
1739
- errors.push("future.v8_middleware: false");
1740
- if (userConfig.future?.unstable_subResourceIntegrity)
1741
- errors.push("future.unstable_subResourceIntegrity");
1742
- if (errors.length) {
1743
- return `RSC Framework Mode does not currently support the following React Router config:
1744
- ${errors.map((x) => ` - ${x}`).join("\n")}
1745
- `;
1746
- }
1747
- }
1748
- });
1749
- const configResult = await configLoader.getConfig();
1750
- if (!configResult.ok) throw new Error(configResult.error);
1751
- config = configResult.value;
1752
- if (viteUserConfig.base && config.basename !== "/" && viteCommand === "serve" && !viteUserConfig.server?.middlewareMode && !config.basename.startsWith(viteUserConfig.base)) {
1753
- throw new Error(
1754
- "When using the React Router `basename` and the Vite `base` config, the `basename` config must begin with `base` for the default Vite dev server."
1755
- );
1756
- }
1757
- const vite2 = await import("vite");
1758
- logger = vite2.createLogger(viteUserConfig.logLevel, {
1759
- prefix: "[react-router]"
1760
- });
1761
- return {
1762
- resolve: {
1763
- dedupe: [
1764
- // https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
1765
- "react",
1766
- "react-dom",
1767
- // Avoid router duplicates since mismatching routers cause `Error:
1768
- // You must render this element inside a <Remix> element`.
1769
- "react-router",
1770
- "react-router/dom",
1771
- ...hasDependency({ name: "react-router-dom", rootDirectory }) ? ["react-router-dom"] : []
1772
- ]
1773
- },
1774
- optimizeDeps: {
1775
- entries: getOptimizeDepsEntries({
1776
- entryClientFilePath: defaultEntries.client,
1777
- reactRouterConfig: config
1778
- }),
1779
- esbuildOptions: {
1780
- jsx: "automatic"
1781
- },
1782
- include: [
1783
- // Pre-bundle React dependencies to avoid React duplicates,
1784
- // even if React dependencies are not direct dependencies.
1785
- // https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
1786
- "react",
1787
- "react/jsx-runtime",
1788
- "react/jsx-dev-runtime",
1789
- "react-dom",
1790
- "react-dom/client",
1791
- "react-router/internal/react-server-client"
1792
- ]
1793
- },
1794
- esbuild: {
1795
- jsx: "automatic",
1796
- jsxDev: viteCommand !== "build"
1797
- },
1798
- environments: {
1799
- client: {
1800
- build: {
1801
- rollupOptions: {
1802
- input: {
1803
- index: defaultEntries.client
1804
- }
1805
- },
1806
- outDir: (0, import_pathe6.join)(config.buildDirectory, "client")
1807
- }
1808
- },
1809
- rsc: {
1810
- build: {
1811
- rollupOptions: {
1812
- input: {
1813
- // We use a virtual entry here so that consumers can import
1814
- // it as `virtual:react-router/unstable_rsc/rsc-entry`
1815
- // without needing to know the actual file path, which is
1816
- // important when using the default entries.
1817
- index: defaultEntries.rsc
1818
- },
1819
- output: {
1820
- entryFileNames: config.serverBuildFile,
1821
- format: config.serverModuleFormat
1822
- }
1823
- },
1824
- outDir: (0, import_pathe6.join)(config.buildDirectory, "server")
1825
- }
1826
- },
1827
- ssr: {
1828
- build: {
1829
- rollupOptions: {
1830
- input: {
1831
- index: defaultEntries.ssr
1832
- },
1833
- output: {
1834
- // Note: We don't set `entryFileNames` here because it's
1835
- // considered private to the RSC environment build, and
1836
- // @vitejs/plugin-rsc currently breaks if it's set to
1837
- // something other than `index.js`.
1838
- format: config.serverModuleFormat
1839
- }
1840
- },
1841
- outDir: (0, import_pathe6.join)(config.buildDirectory, "server/__ssr_build")
1842
- }
1843
- }
1844
- },
1845
- build: {
1846
- rollupOptions: {
1847
- // Copied from https://github.com/vitejs/vite-plugin-react/blob/c602225271d4acf462ba00f8d6d8a2e42492c5cd/packages/common/warning.ts
1848
- onwarn(warning, defaultHandler) {
1849
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) {
1850
- return;
1851
- }
1852
- if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) {
1853
- return;
1854
- }
1855
- if (viteUserConfig.build?.rollupOptions?.onwarn) {
1856
- viteUserConfig.build.rollupOptions.onwarn(
1857
- warning,
1858
- defaultHandler
1859
- );
1860
- } else {
1861
- defaultHandler(warning);
1862
- }
1863
- }
1864
- }
1865
- }
1866
- };
1867
- },
1868
- async configureServer(viteDevServer) {
1869
- configLoader.onChange(
1870
- async ({
1871
- result,
1872
- configCodeChanged,
1873
- routeConfigCodeChanged,
1874
- configChanged,
1875
- routeConfigChanged
1876
- }) => {
1877
- if (!result.ok) {
1878
- invalidateVirtualModules(viteDevServer);
1879
- logger.error(result.error, {
1880
- clear: true,
1881
- timestamp: true
1882
- });
1883
- return;
1884
- }
1885
- let message = configChanged ? "Config changed." : routeConfigChanged ? "Route config changed." : configCodeChanged ? "Config saved." : routeConfigCodeChanged ? " Route config saved." : "Config saved";
1886
- logger.info(import_picocolors3.default.green(message), {
1887
- clear: true,
1888
- timestamp: true
1889
- });
1890
- config = result.value;
1891
- if (configChanged || routeConfigChanged) {
1892
- invalidateVirtualModules(viteDevServer);
1893
- }
1894
- }
1895
- );
1896
- },
1897
- async buildEnd() {
1898
- await configLoader.close();
1899
- }
1900
- },
1901
- {
1902
- name: "react-router/rsc/typegen",
1903
- async config(viteUserConfig, { command, mode }) {
1904
- if (command === "serve") {
1905
- const vite2 = await import("vite");
1906
- typegenWatcherPromise = watch(
1907
- getRootDirectory(viteUserConfig),
1908
- {
1909
- mode,
1910
- // ignore `info` logs from typegen since they are
1911
- // redundant when Vite plugin logs are active
1912
- logger: vite2.createLogger("warn", {
1913
- prefix: "[react-router]"
1914
- })
1915
- }
1916
- );
1917
- }
1918
- },
1919
- async buildEnd() {
1920
- (await typegenWatcherPromise)?.close();
1921
- }
1922
- },
1923
- {
1924
- name: "react-router/rsc/virtual-rsc-entry",
1925
- resolveId(id) {
1926
- if (id === virtual.rscEntry.id) return defaultEntries.rsc;
1927
- }
1928
- },
1929
- {
1930
- name: "react-router/rsc/virtual-route-config",
1931
- resolveId(id) {
1932
- if (id === virtual.routeConfig.id) {
1933
- return virtual.routeConfig.resolvedId;
1934
- }
1935
- },
1936
- load(id) {
1937
- if (id === virtual.routeConfig.resolvedId) {
1938
- const result = createVirtualRouteConfig({
1939
- appDirectory: config.appDirectory,
1940
- routeConfig: config.unstable_routeConfig
1941
- });
1942
- routeIdByFile = result.routeIdByFile;
1943
- return result.code;
1944
- }
1945
- }
1946
- },
1947
- {
1948
- name: "react-router/rsc/virtual-route-modules",
1949
- transform(code, id) {
1950
- if (!routeIdByFile) return;
1951
- return transformVirtualRouteModules({
1952
- code,
1953
- id,
1954
- viteCommand,
1955
- routeIdByFile,
1956
- viteEnvironment: this.environment
1957
- });
1958
- }
1959
- },
1960
- {
1961
- name: "react-router/rsc/virtual-basename",
1962
- resolveId(id) {
1963
- if (id === virtual.basename.id) {
1964
- return virtual.basename.resolvedId;
1965
- }
1966
- },
1967
- load(id) {
1968
- if (id === virtual.basename.resolvedId) {
1969
- return `export default ${JSON.stringify(config.basename)};`;
1970
- }
1971
- }
1972
- },
1973
- {
1974
- name: "react-router/rsc/hmr/inject-runtime",
1975
- enforce: "pre",
1976
- resolveId(id) {
1977
- if (id === virtual.injectHmrRuntime.id) {
1978
- return virtual.injectHmrRuntime.resolvedId;
1979
- }
1980
- },
1981
- async load(id) {
1982
- if (id !== virtual.injectHmrRuntime.resolvedId) return;
1983
- return viteCommand === "serve" ? [
1984
- `import RefreshRuntime from "${virtual.hmrRuntime.id}"`,
1985
- "RefreshRuntime.injectIntoGlobalHook(window)",
1986
- "window.$RefreshReg$ = () => {}",
1987
- "window.$RefreshSig$ = () => (type) => type",
1988
- "window.__vite_plugin_react_preamble_installed__ = true"
1989
- ].join("\n") : "";
1990
- }
1991
- },
1992
- {
1993
- name: "react-router/rsc/hmr/runtime",
1994
- enforce: "pre",
1995
- resolveId(id) {
1996
- if (id === virtual.hmrRuntime.id) return virtual.hmrRuntime.resolvedId;
1997
- },
1998
- async load(id) {
1999
- if (id !== virtual.hmrRuntime.resolvedId) return;
2000
- const reactRefreshDir = import_pathe6.default.dirname(
2001
- require.resolve("react-refresh/package.json")
2002
- );
2003
- const reactRefreshRuntimePath = import_pathe6.default.join(
2004
- reactRefreshDir,
2005
- "cjs/react-refresh-runtime.development.js"
2006
- );
2007
- return [
2008
- "const exports = {}",
2009
- await (0, import_promises2.readFile)(reactRefreshRuntimePath, "utf8"),
2010
- await (0, import_promises2.readFile)(
2011
- require.resolve("./static/rsc-refresh-utils.mjs"),
2012
- "utf8"
2013
- ),
2014
- "export default exports"
2015
- ].join("\n");
2016
- }
2017
- },
2018
- {
2019
- name: "react-router/rsc/hmr/react-refresh",
2020
- async transform(code, id, options) {
2021
- if (viteCommand !== "serve") return;
2022
- if (id.includes("/node_modules/")) return;
2023
- const filepath = id.split("?")[0];
2024
- const extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
2025
- if (!extensionsRE.test(filepath)) return;
2026
- const devRuntime = "react/jsx-dev-runtime";
2027
- const ssr = options?.ssr === true;
2028
- const isJSX = filepath.endsWith("x");
2029
- const useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
2030
- if (!useFastRefresh) return;
2031
- if (isVirtualClientRouteModuleId(id)) {
2032
- const routeId = routeIdByFile?.get(filepath);
2033
- return { code: addRefreshWrapper({ routeId, code, id }) };
2034
- }
2035
- const result = await babel.transformAsync(code, {
2036
- babelrc: false,
2037
- configFile: false,
2038
- filename: id,
2039
- sourceFileName: filepath,
2040
- parserOpts: {
2041
- sourceType: "module",
2042
- allowAwaitOutsideFunction: true
2043
- },
2044
- plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
2045
- sourceMaps: true
2046
- });
2047
- if (result === null) return;
2048
- code = result.code;
2049
- const refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
2050
- if (refreshContentRE.test(code)) {
2051
- code = addRefreshWrapper({ code, id });
2052
- }
2053
- return { code, map: result.map };
2054
- }
2055
- },
2056
- {
2057
- name: "react-router/rsc/hmr/updates",
2058
- async hotUpdate({ server, file, modules }) {
2059
- if (this.environment.name !== "rsc") return;
2060
- const clientModules = server.environments.client.moduleGraph.getModulesByFile(file);
2061
- const vite2 = await import("vite");
2062
- const isServerOnlyChange = !clientModules || clientModules.size === 0 || // Handle CSS injected from server-first routes (with ?direct query
2063
- // string) since the client graph has a reference to the CSS
2064
- vite2.isCSSRequest(file) && Array.from(clientModules).some(
2065
- (mod) => mod.id?.includes("?direct")
2066
- );
2067
- for (const mod of getModulesWithImporters(modules)) {
2068
- if (!mod.file) continue;
2069
- const normalizedPath = import_pathe6.default.normalize(mod.file);
2070
- const routeId = routeIdByFile?.get(normalizedPath);
2071
- if (routeId !== void 0) {
2072
- const routeSource = await (0, import_promises2.readFile)(normalizedPath, "utf8");
2073
- const virtualRouteModuleCode = (await server.environments.rsc.pluginContainer.transform(
2074
- routeSource,
2075
- `${normalizedPath}?route-module`
2076
- )).code;
2077
- const { staticExports } = parseRouteExports(virtualRouteModuleCode);
2078
- const hasAction = staticExports.includes("action");
2079
- const hasComponent = staticExports.includes("default");
2080
- const hasErrorBoundary = staticExports.includes("ErrorBoundary");
2081
- const hasLoader = staticExports.includes("loader");
2082
- server.hot.send({
2083
- type: "custom",
2084
- event: "react-router:hmr",
2085
- data: {
2086
- routeId,
2087
- isServerOnlyChange,
2088
- hasAction,
2089
- hasComponent,
2090
- hasErrorBoundary,
2091
- hasLoader
2092
- }
2093
- });
2094
- }
2095
- }
2096
- return modules;
2097
- }
2098
- },
2099
- validatePluginOrder()
2100
- ];
2101
- }
2102
- var virtual = {
2103
- routeConfig: create("unstable_rsc/routes"),
2104
- injectHmrRuntime: create("unstable_rsc/inject-hmr-runtime"),
2105
- hmrRuntime: create("unstable_rsc/runtime"),
2106
- basename: create("unstable_rsc/basename"),
2107
- rscEntry: create("unstable_rsc/rsc-entry")
2108
- };
2109
- function invalidateVirtualModules(viteDevServer) {
2110
- for (const vmod of Object.values(virtual)) {
2111
- for (const env of Object.values(viteDevServer.environments)) {
2112
- const mod = env.moduleGraph.getModuleById(vmod.resolvedId);
2113
- if (mod) {
2114
- env.moduleGraph.invalidateModule(mod);
2115
- }
2116
- }
2117
- }
2118
- }
2119
- function getRootDirectory(viteUserConfig) {
2120
- return viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
2121
- }
2122
- function getDevPackageRoot() {
2123
- const currentDir = (0, import_pathe6.dirname)(__dirname);
2124
- let dir = currentDir;
2125
- while (dir !== (0, import_pathe6.dirname)(dir)) {
2126
- try {
2127
- const packageJsonPath = (0, import_pathe6.join)(dir, "package.json");
2128
- (0, import_fs.readFileSync)(packageJsonPath, "utf-8");
2129
- return dir;
2130
- } catch {
2131
- dir = (0, import_pathe6.dirname)(dir);
2132
- }
2133
- }
2134
- throw new Error("Could not find package.json");
2135
- }
2136
- function getDefaultEntries() {
2137
- const defaultEntriesDir = (0, import_pathe6.join)(
2138
- getDevPackageRoot(),
2139
- "dist",
2140
- "config",
2141
- "default-rsc-entries"
2142
- );
2143
- return {
2144
- rsc: (0, import_pathe6.join)(defaultEntriesDir, "entry.rsc.tsx"),
2145
- ssr: (0, import_pathe6.join)(defaultEntriesDir, "entry.ssr.tsx"),
2146
- client: (0, import_pathe6.join)(defaultEntriesDir, "entry.client.tsx")
2147
- };
2148
- }
2149
- function getModulesWithImporters(modules) {
2150
- const visited = /* @__PURE__ */ new Set();
2151
- const result = /* @__PURE__ */ new Set();
2152
- function walk(module2) {
2153
- if (visited.has(module2)) return;
2154
- visited.add(module2);
2155
- result.add(module2);
2156
- for (const importer of module2.importers) {
2157
- walk(importer);
2158
- }
2159
- }
2160
- for (const module2 of modules) {
2161
- walk(module2);
2162
- }
2163
- return result;
2164
- }
2165
- function addRefreshWrapper({
2166
- routeId,
2167
- code,
2168
- id
2169
- }) {
2170
- const acceptExports = routeId !== void 0 ? CLIENT_NON_COMPONENT_EXPORTS : [];
2171
- return REACT_REFRESH_HEADER.replaceAll("__SOURCE__", JSON.stringify(id)) + code + REACT_REFRESH_FOOTER.replaceAll("__SOURCE__", JSON.stringify(id)).replaceAll("__ACCEPT_EXPORTS__", JSON.stringify(acceptExports)).replaceAll("__ROUTE_ID__", JSON.stringify(routeId));
2172
- }
2173
- var REACT_REFRESH_HEADER = `
2174
- import RefreshRuntime from "${virtual.hmrRuntime.id}";
2175
-
2176
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
2177
- let prevRefreshReg;
2178
- let prevRefreshSig;
2179
-
2180
- if (import.meta.hot && !inWebWorker) {
2181
- if (!window.__vite_plugin_react_preamble_installed__) {
2182
- throw new Error(
2183
- "React Router Vite plugin can't detect preamble. Something is wrong."
2184
- );
2185
- }
2186
-
2187
- prevRefreshReg = window.$RefreshReg$;
2188
- prevRefreshSig = window.$RefreshSig$;
2189
- window.$RefreshReg$ = (type, id) => {
2190
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
2191
- };
2192
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
2193
- }`.replaceAll("\n", "");
2194
- var REACT_REFRESH_FOOTER = `
2195
- if (import.meta.hot && !inWebWorker) {
2196
- window.$RefreshReg$ = prevRefreshReg;
2197
- window.$RefreshSig$ = prevRefreshSig;
2198
- RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
2199
- RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
2200
- import.meta.hot.accept((nextExports) => {
2201
- if (!nextExports) return;
2202
- __ROUTE_ID__ && window.__reactRouterRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
2203
- const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
2204
- if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
2205
- });
2206
- });
2207
- }`;
2208
-
2209
- // internal.ts
2210
- var __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__ = {
2211
- unstable_reactRouterRSC: reactRouterRSCVitePlugin
2212
- };
2213
- // Annotate the CommonJS export names for ESM import in node:
2214
- 0 && (module.exports = {
2215
- __INTERNAL_DO_NOT_USE_OR_YOU_WILL_GET_A_STRONGLY_WORDED_LETTER__
2216
- });