@react-router/dev 7.15.1 → 8.0.0-pre.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * @react-router/dev v7.15.1
3
+ * @react-router/dev v8.0.0-pre.0
4
4
  *
5
5
  * Copyright (c) Remix Software Inc.
6
6
  *
@@ -9,2507 +9,307 @@
9
9
  *
10
10
  * @license MIT
11
11
  */
12
- "use strict";
13
- var __create = Object.create;
14
- var __defProp = Object.defineProperty;
15
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
16
- var __getOwnPropNames = Object.getOwnPropertyNames;
17
- var __getProtoOf = Object.getPrototypeOf;
18
- var __hasOwnProp = Object.prototype.hasOwnProperty;
19
- var __esm = (fn, res) => function __init() {
20
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
21
- };
22
- var __export = (target, all) => {
23
- for (var name in all)
24
- __defProp(target, name, { get: all[name], enumerable: true });
25
- };
26
- var __copyProps = (to, from, except, desc) => {
27
- if (from && typeof from === "object" || typeof from === "function") {
28
- for (let key of __getOwnPropNames(from))
29
- if (!__hasOwnProp.call(to, key) && key !== except)
30
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
31
- }
32
- return to;
33
- };
34
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
35
- // If the importer is in node compatibility mode or this is not an ESM
36
- // file that has been converted to a CommonJS file using a Babel-
37
- // compatible transform (i.e. "__esModule" has not been set), then set
38
- // "default" to the CommonJS "module.exports" for node compatibility.
39
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
40
- mod
41
- ));
42
-
43
- // invariant.ts
44
- function invariant(value, message) {
45
- if (value === false || value === null || typeof value === "undefined") {
46
- console.error(
47
- "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
48
- );
49
- throw new Error(message);
50
- }
51
- }
52
- var init_invariant = __esm({
53
- "invariant.ts"() {
54
- "use strict";
55
- }
56
- });
57
-
58
- // config/is-react-router-repo.ts
59
- function isReactRouterRepo() {
60
- let serverRuntimePath = import_pathe.default.dirname(
61
- require.resolve("@react-router/node/package.json")
62
- );
63
- let serverRuntimeParentDir = import_pathe.default.basename(
64
- import_pathe.default.resolve(serverRuntimePath, "..")
65
- );
66
- return serverRuntimeParentDir === "packages";
67
- }
68
- var import_pathe;
69
- var init_is_react_router_repo = __esm({
70
- "config/is-react-router-repo.ts"() {
71
- "use strict";
72
- import_pathe = __toESM(require("pathe"));
73
- }
74
- });
75
-
76
- // vite/vite.ts
77
- async function preloadVite() {
78
- vite = await import(viteImportSpecifier);
79
- }
80
- function getVite() {
81
- invariant(vite, "getVite() called before preloadVite()");
82
- return vite;
83
- }
84
- var import_pathe2, vite, viteImportSpecifier;
85
- var init_vite = __esm({
86
- "vite/vite.ts"() {
87
- "use strict";
88
- import_pathe2 = __toESM(require("pathe"));
89
- init_invariant();
90
- init_is_react_router_repo();
91
- viteImportSpecifier = isReactRouterRepo() ? (
92
- // Support testing against different versions of Vite by ensuring that Vite
93
- // is resolved from the current working directory when running within this
94
- // repo. If we don't do this, Vite will always be imported relative to this
95
- // file, which means that it will always resolve to Vite 6.
96
- `file:///${import_pathe2.default.normalize(
97
- require.resolve("vite/package.json", { paths: [process.cwd()] })
98
- ).replace("package.json", "dist/node/index.js")}`
99
- ) : "vite";
100
- }
101
- });
102
-
103
- // vite/ssr-externals.ts
104
- var ssrExternals;
105
- var init_ssr_externals = __esm({
106
- "vite/ssr-externals.ts"() {
107
- "use strict";
108
- init_is_react_router_repo();
109
- ssrExternals = isReactRouterRepo() ? [
110
- // This is only needed within this repo because these packages
111
- // are linked to a directory outside of node_modules so Vite
112
- // treats them as internal code by default.
113
- "react-router",
114
- "react-router-dom",
115
- "@react-router/architect",
116
- "@react-router/cloudflare",
117
- "@react-router/dev",
118
- "@react-router/express",
119
- "@react-router/node",
120
- "@react-router/serve"
121
- ] : void 0;
122
- }
123
- });
124
-
125
- // vite/vite-node.ts
126
- async function createContext({
127
- root,
128
- mode,
129
- customLogger
130
- }) {
131
- await preloadVite();
132
- const vite2 = getVite();
133
- const [{ ViteNodeServer }, { ViteNodeRunner }, { installSourcemapsSupport }] = await Promise.all([
134
- import("vite-node/server"),
135
- import("vite-node/client"),
136
- import("vite-node/source-map")
137
- ]);
138
- const devServer = await vite2.createServer({
139
- root,
140
- mode,
141
- customLogger,
142
- server: {
143
- preTransformRequests: false,
144
- hmr: false,
145
- watch: null
146
- },
147
- ssr: {
148
- external: ssrExternals
149
- },
150
- optimizeDeps: {
151
- noDiscovery: true
152
- },
153
- css: {
154
- // This empty PostCSS config object prevents the PostCSS config file from
155
- // being loaded. We don't need it in a React Router config context, and
156
- // there's also an issue in Vite 5 when using a .ts PostCSS config file in
157
- // an ESM project: https://github.com/vitejs/vite/issues/15869. Consumers
158
- // can work around this in their own Vite config file, but they can't
159
- // configure this internal usage of vite-node.
160
- postcss: {}
161
- },
162
- configFile: false,
163
- envFile: false,
164
- plugins: []
165
- });
166
- await devServer.pluginContainer.buildStart({});
167
- const server = new ViteNodeServer(devServer);
168
- installSourcemapsSupport({
169
- getSourceMap: (source) => server.getSourceMap(source)
170
- });
171
- const runner = new ViteNodeRunner({
172
- root: devServer.config.root,
173
- base: devServer.config.base,
174
- fetchModule(id) {
175
- return server.fetchModule(id);
176
- },
177
- resolveId(id, importer) {
178
- return server.resolveId(id, importer);
179
- }
180
- });
181
- return { devServer, server, runner };
182
- }
183
- var init_vite_node = __esm({
184
- "vite/vite-node.ts"() {
185
- "use strict";
186
- init_vite();
187
- init_ssr_externals();
188
- }
189
- });
190
-
191
- // config/routes.ts
192
- function setAppDirectory(directory) {
193
- globalThis.__reactRouterAppDirectory = directory;
194
- }
195
- function validateRouteConfig({
196
- routeConfigFile,
197
- routeConfig
198
- }) {
199
- if (!routeConfig) {
200
- return {
201
- valid: false,
202
- message: `Route config must be the default export in "${routeConfigFile}".`
203
- };
204
- }
205
- if (!Array.isArray(routeConfig)) {
206
- return {
207
- valid: false,
208
- message: `Route config in "${routeConfigFile}" must be an array.`
209
- };
210
- }
211
- let { issues } = v.safeParse(resolvedRouteConfigSchema, routeConfig);
212
- if (issues?.length) {
213
- let { root, nested } = v.flatten(issues);
214
- return {
215
- valid: false,
216
- message: [
217
- `Route config in "${routeConfigFile}" is invalid.`,
218
- root ? `${root}` : [],
219
- nested ? Object.entries(nested).map(
220
- ([path10, message]) => `Path: routes.${path10}
221
- ${message}`
222
- ) : []
223
- ].flat().join("\n\n")
224
- };
225
- }
226
- return {
227
- valid: true,
228
- routeConfig
229
- };
230
- }
231
- function configRoutesToRouteManifest(appDirectory, routes2) {
232
- let routeManifest = {};
233
- function walk(route, parentId) {
234
- let id = route.id || createRouteId(route.file);
235
- let manifestItem = {
236
- id,
237
- parentId,
238
- file: Path.isAbsolute(route.file) ? Path.relative(appDirectory, route.file) : route.file,
239
- path: route.path,
240
- index: route.index,
241
- caseSensitive: route.caseSensitive
242
- };
243
- if (routeManifest.hasOwnProperty(id)) {
244
- throw new Error(
245
- `Unable to define routes with duplicate route id: "${id}"`
246
- );
247
- }
248
- routeManifest[id] = manifestItem;
249
- if (route.children) {
250
- for (let child of route.children) {
251
- walk(child, id);
252
- }
253
- }
254
- }
255
- for (let route of routes2) {
256
- walk(route);
257
- }
258
- return routeManifest;
259
- }
260
- function createRouteId(file) {
261
- return Path.normalize(stripFileExtension(file));
262
- }
263
- function stripFileExtension(file) {
264
- return file.replace(/\.[a-z0-9]+$/i, "");
265
- }
266
- var Path, v, import_pick, routeConfigEntrySchema, resolvedRouteConfigSchema;
267
- var init_routes = __esm({
268
- "config/routes.ts"() {
269
- "use strict";
270
- Path = __toESM(require("pathe"));
271
- v = __toESM(require("valibot"));
272
- import_pick = __toESM(require("lodash/pick"));
273
- init_invariant();
274
- routeConfigEntrySchema = v.pipe(
275
- v.custom((value) => {
276
- return !(typeof value === "object" && value !== null && "then" in value && "catch" in value);
277
- }, "Invalid type: Expected object but received a promise. Did you forget to await?"),
278
- v.object({
279
- id: v.optional(
280
- v.pipe(
281
- v.string(),
282
- v.notValue("root", "A route cannot use the reserved id 'root'.")
283
- )
284
- ),
285
- path: v.optional(v.string()),
286
- index: v.optional(v.boolean()),
287
- caseSensitive: v.optional(v.boolean()),
288
- file: v.string(),
289
- children: v.optional(v.array(v.lazy(() => routeConfigEntrySchema)))
290
- })
291
- );
292
- resolvedRouteConfigSchema = v.array(routeConfigEntrySchema);
293
- }
294
- });
295
-
296
- // cli/detectPackageManager.ts
297
- var init_detectPackageManager = __esm({
298
- "cli/detectPackageManager.ts"() {
299
- "use strict";
300
- }
301
- });
302
-
303
- // config/config.ts
304
- function ok(value) {
305
- return { ok: true, value };
306
- }
307
- function err(error) {
308
- return { ok: false, error };
309
- }
310
- async function resolveConfig({
311
- root,
312
- viteNodeContext,
313
- reactRouterConfigFile,
314
- skipRoutes,
315
- validateConfig
316
- }) {
317
- let reactRouterUserConfig = {};
318
- if (reactRouterConfigFile) {
319
- try {
320
- if (!import_node_fs.default.existsSync(reactRouterConfigFile)) {
321
- return err(`${reactRouterConfigFile} no longer exists`);
322
- }
323
- let configModule = await viteNodeContext.runner.executeFile(
324
- reactRouterConfigFile
325
- );
326
- if (configModule.default === void 0) {
327
- return err(`${reactRouterConfigFile} must provide a default export`);
328
- }
329
- if (typeof configModule.default !== "object") {
330
- return err(`${reactRouterConfigFile} must export a config`);
331
- }
332
- reactRouterUserConfig = configModule.default;
333
- if (validateConfig) {
334
- const error = validateConfig(reactRouterUserConfig);
335
- if (error) {
336
- return err(error);
337
- }
338
- }
339
- } catch (error) {
340
- return err(`Error loading ${reactRouterConfigFile}: ${error}`);
341
- }
342
- }
343
- reactRouterUserConfig = deepFreeze((0, import_cloneDeep.default)(reactRouterUserConfig));
344
- let presets = (await Promise.all(
345
- (reactRouterUserConfig.presets ?? []).map(async (preset) => {
346
- if (!preset.name) {
347
- throw new Error(
348
- "React Router presets must have a `name` property defined."
349
- );
350
- }
351
- if (!preset.reactRouterConfig) {
352
- return null;
353
- }
354
- let configPreset = (0, import_omit.default)(
355
- await preset.reactRouterConfig({ reactRouterUserConfig }),
356
- excludedConfigPresetKeys
357
- );
358
- return configPreset;
359
- })
360
- )).filter(function isNotNull(value) {
361
- return value !== null;
362
- });
363
- let defaults = {
364
- basename: "/",
365
- buildDirectory: "build",
366
- serverBuildFile: "index.js",
367
- serverModuleFormat: "esm",
368
- ssr: true
369
- };
370
- let userAndPresetConfigs = mergeReactRouterConfig(
371
- ...presets,
372
- reactRouterUserConfig
373
- );
374
- let {
375
- appDirectory: userAppDirectory,
376
- basename: basename3,
377
- buildDirectory: userBuildDirectory,
378
- buildEnd,
379
- prerender: prerender2,
380
- routeDiscovery: userRouteDiscovery,
381
- serverBuildFile,
382
- serverBundles,
383
- serverModuleFormat,
384
- ssr
385
- } = {
386
- ...defaults,
387
- // Default values should be completely overridden by user/preset config, not merged
388
- ...userAndPresetConfigs
389
- };
390
- if (!ssr && serverBundles) {
391
- serverBundles = void 0;
392
- }
393
- if (prerender2) {
394
- let isValidPrerenderPathsConfig = (p) => typeof p === "boolean" || typeof p === "function" || Array.isArray(p);
395
- let isValidPrerenderConfig = isValidPrerenderPathsConfig(prerender2) || typeof prerender2 === "object" && "paths" in prerender2 && isValidPrerenderPathsConfig(prerender2.paths);
396
- if (!isValidPrerenderConfig) {
397
- return err(
398
- "The `prerender`/`prerender.paths` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths."
399
- );
400
- }
401
- if (typeof prerender2 === "object" && "unstable_concurrency" in prerender2) {
402
- return err(
403
- "The `prerender.unstable_concurrency` config field has been stabilized as `prerender.concurrency`"
404
- );
405
- }
406
- let isValidConcurrencyConfig = typeof prerender2 != "object" || !("concurrency" in prerender2) || typeof prerender2.concurrency === "number" && Number.isInteger(prerender2.concurrency) && prerender2.concurrency > 0;
407
- if (!isValidConcurrencyConfig) {
408
- return err(
409
- "The `prerender.concurrency` config must be a positive integer if specified."
410
- );
411
- }
412
- }
413
- let routeDiscovery;
414
- if (userRouteDiscovery == null) {
415
- if (ssr) {
416
- routeDiscovery = {
417
- mode: "lazy",
418
- manifestPath: "/__manifest"
419
- };
420
- } else {
421
- routeDiscovery = { mode: "initial" };
422
- }
423
- } else if (userRouteDiscovery.mode === "initial") {
424
- routeDiscovery = userRouteDiscovery;
425
- } else if (userRouteDiscovery.mode === "lazy") {
426
- if (!ssr) {
427
- return err(
428
- 'The `routeDiscovery.mode` config cannot be set to "lazy" when setting `ssr:false`'
429
- );
430
- }
431
- let { manifestPath } = userRouteDiscovery;
432
- if (manifestPath != null && !manifestPath.startsWith("/")) {
433
- return err(
434
- 'The `routeDiscovery.manifestPath` config must be a root-relative pathname beginning with a slash (i.e., "/__manifest")'
435
- );
436
- }
437
- routeDiscovery = userRouteDiscovery;
438
- }
439
- let appDirectory = import_pathe3.default.resolve(root, userAppDirectory || "app");
440
- let buildDirectory = import_pathe3.default.resolve(root, userBuildDirectory);
441
- let rootRouteFile = findEntry(appDirectory, "root", { absolute: true });
442
- if (!rootRouteFile) {
443
- let rootRouteDisplayPath = import_pathe3.default.relative(
444
- root,
445
- import_pathe3.default.join(appDirectory, "root.tsx")
446
- );
447
- return err(
448
- `Could not find a root route module in the app directory as "${rootRouteDisplayPath}"`
449
- );
450
- }
451
- let routes2;
452
- let routeConfig = [];
453
- if (skipRoutes) {
454
- routes2 = {};
455
- } else {
456
- let routeConfigFile = findEntry(appDirectory, "routes");
457
- try {
458
- if (!routeConfigFile) {
459
- let routeConfigDisplayPath = import_pathe3.default.relative(
460
- root,
461
- import_pathe3.default.join(appDirectory, "routes.ts")
462
- );
463
- return err(
464
- `Route config file not found at "${routeConfigDisplayPath}".`
465
- );
466
- }
467
- setAppDirectory(appDirectory);
468
- let routeConfigExport = (await viteNodeContext.runner.executeFile(
469
- import_pathe3.default.join(appDirectory, routeConfigFile)
470
- )).default;
471
- let result = validateRouteConfig({
472
- routeConfigFile,
473
- routeConfig: await routeConfigExport
474
- });
475
- if (!result.valid) {
476
- return err(result.message);
477
- }
478
- routeConfig = [
479
- {
480
- id: "root",
481
- path: "",
482
- file: import_pathe3.default.relative(appDirectory, rootRouteFile),
483
- children: result.routeConfig
484
- }
485
- ];
486
- routes2 = configRoutesToRouteManifest(appDirectory, routeConfig);
487
- } catch (error) {
488
- return err(
489
- [
490
- import_picocolors.default.red(`Route config in "${routeConfigFile}" is invalid.`),
491
- "",
492
- error.loc?.file && error.loc?.column && error.frame ? [
493
- import_pathe3.default.relative(appDirectory, error.loc.file) + ":" + error.loc.line + ":" + error.loc.column,
494
- error.frame.trim?.()
495
- ] : error.stack
496
- ].flat().join("\n")
497
- );
498
- }
499
- }
500
- let futureConfig = userAndPresetConfigs.future;
501
- if (futureConfig) {
502
- if ("unstable_splitRouteModules" in futureConfig) {
503
- return err(
504
- "The `future.unstable_splitRouteModules` flag has been stabilized as `future.v8_splitRouteModules`"
505
- );
506
- }
507
- if ("unstable_viteEnvironmentApi" in futureConfig) {
508
- return err(
509
- "The `future.unstable_viteEnvironmentApi` flag has been stabilized as `future.v8_viteEnvironmentApi`"
510
- );
511
- }
512
- if ("unstable_passThroughRequests" in futureConfig) {
513
- return err(
514
- "The `future.unstable_passThroughRequests` flag has been stabilized as `future.v8_passThroughRequests`"
515
- );
516
- }
517
- if ("unstable_subResourceIntegrity" in futureConfig) {
518
- return err(
519
- "The `future.unstable_subResourceIntegrity` flag has been stabilized and moved to a top-level `config.subResourceIntegrity` field"
520
- );
521
- }
522
- }
523
- let future = {
524
- unstable_optimizeDeps: userAndPresetConfigs.future?.unstable_optimizeDeps ?? false,
525
- v8_passThroughRequests: userAndPresetConfigs.future?.v8_passThroughRequests ?? false,
526
- unstable_trailingSlashAwareDataRequests: userAndPresetConfigs.future?.unstable_trailingSlashAwareDataRequests ?? false,
527
- unstable_previewServerPrerendering: userAndPresetConfigs.future?.unstable_previewServerPrerendering ?? false,
528
- v8_middleware: userAndPresetConfigs.future?.v8_middleware ?? false,
529
- v8_splitRouteModules: userAndPresetConfigs.future?.v8_splitRouteModules ?? false,
530
- v8_viteEnvironmentApi: (userAndPresetConfigs.future?.v8_viteEnvironmentApi || userAndPresetConfigs.future?.unstable_previewServerPrerendering) ?? false
531
- };
532
- let allowedActionOrigins = userAndPresetConfigs.allowedActionOrigins ?? false;
533
- let subResourceIntegrity = userAndPresetConfigs.subResourceIntegrity ?? false;
534
- let reactRouterConfig = deepFreeze({
535
- appDirectory,
536
- basename: basename3,
537
- buildDirectory,
538
- buildEnd,
539
- future,
540
- prerender: prerender2,
541
- routes: routes2,
542
- routeDiscovery,
543
- serverBuildFile,
544
- serverBundles,
545
- serverModuleFormat,
546
- ssr,
547
- subResourceIntegrity,
548
- allowedActionOrigins,
549
- unstable_routeConfig: routeConfig
550
- });
551
- for (let preset of reactRouterUserConfig.presets ?? []) {
552
- await preset.reactRouterConfigResolved?.({ reactRouterConfig });
553
- }
554
- return ok(reactRouterConfig);
555
- }
556
- async function createConfigLoader({
557
- rootDirectory: root,
558
- watch: watch2,
559
- mode,
560
- skipRoutes,
561
- validateConfig
562
- }) {
563
- root = import_pathe3.default.normalize(root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd());
564
- let vite2 = await import("vite");
565
- let viteNodeContext = await createContext({
566
- root,
567
- mode,
568
- // Filter out any info level logs from vite-node
569
- customLogger: vite2.createLogger("warn", {
570
- prefix: "[react-router]"
571
- })
572
- });
573
- let reactRouterConfigFile;
574
- let updateReactRouterConfigFile = () => {
575
- reactRouterConfigFile = findEntry(root, "react-router.config", {
576
- absolute: true
577
- });
578
- };
579
- updateReactRouterConfigFile();
580
- let getConfig = () => resolveConfig({
581
- root,
582
- viteNodeContext,
583
- reactRouterConfigFile,
584
- skipRoutes,
585
- validateConfig
586
- });
587
- let appDirectory;
588
- let initialConfigResult = await getConfig();
589
- if (!initialConfigResult.ok) {
590
- throw new Error(initialConfigResult.error);
591
- }
592
- appDirectory = import_pathe3.default.normalize(initialConfigResult.value.appDirectory);
593
- let currentConfig = initialConfigResult.value;
594
- let fsWatcher;
595
- let changeHandlers = [];
596
- return {
597
- getConfig,
598
- onChange: (handler) => {
599
- if (!watch2) {
600
- throw new Error(
601
- "onChange is not supported when watch mode is disabled"
602
- );
603
- }
604
- changeHandlers.push(handler);
605
- if (!fsWatcher) {
606
- fsWatcher = import_chokidar.default.watch([root, appDirectory], {
607
- ignoreInitial: true,
608
- ignored: (path10) => isIgnoredByWatcher(path10, { root, appDirectory })
609
- });
610
- fsWatcher.on("error", (error) => {
611
- let message = error instanceof Error ? error.message : String(error);
612
- console.warn(import_picocolors.default.yellow(`File watcher error: ${message}`));
613
- });
614
- fsWatcher.on("all", async (...args) => {
615
- let [event, rawFilepath] = args;
616
- let filepath = import_pathe3.default.normalize(rawFilepath);
617
- let fileAddedOrRemoved = event === "add" || event === "unlink";
618
- let appFileAddedOrRemoved = fileAddedOrRemoved && filepath.startsWith(import_pathe3.default.normalize(appDirectory));
619
- let rootRelativeFilepath = import_pathe3.default.relative(root, filepath);
620
- let configFileAddedOrRemoved = fileAddedOrRemoved && isEntryFile("react-router.config", rootRelativeFilepath);
621
- if (configFileAddedOrRemoved) {
622
- updateReactRouterConfigFile();
623
- }
624
- let moduleGraphChanged = configFileAddedOrRemoved || Boolean(
625
- viteNodeContext.devServer?.moduleGraph.getModuleById(filepath)
626
- );
627
- if (!moduleGraphChanged && !appFileAddedOrRemoved) {
628
- return;
629
- }
630
- viteNodeContext.devServer?.moduleGraph.invalidateAll();
631
- viteNodeContext.runner?.moduleCache.clear();
632
- let result = await getConfig();
633
- let prevAppDirectory = appDirectory;
634
- appDirectory = import_pathe3.default.normalize(
635
- (result.value ?? currentConfig).appDirectory
636
- );
637
- if (appDirectory !== prevAppDirectory) {
638
- fsWatcher.unwatch(prevAppDirectory);
639
- fsWatcher.add(appDirectory);
640
- }
641
- let configCodeChanged = configFileAddedOrRemoved || reactRouterConfigFile !== void 0 && isEntryFileDependency(
642
- viteNodeContext.devServer.moduleGraph,
643
- reactRouterConfigFile,
644
- filepath
645
- );
646
- let routeConfigFile = !skipRoutes ? findEntry(appDirectory, "routes", {
647
- absolute: true
648
- }) : void 0;
649
- let routeConfigCodeChanged = routeConfigFile !== void 0 && isEntryFileDependency(
650
- viteNodeContext.devServer.moduleGraph,
651
- routeConfigFile,
652
- filepath
653
- );
654
- let configChanged = result.ok && !(0, import_isEqual.default)(omitRoutes(currentConfig), omitRoutes(result.value));
655
- let routeConfigChanged = result.ok && !(0, import_isEqual.default)(currentConfig?.routes, result.value.routes);
656
- for (let handler2 of changeHandlers) {
657
- handler2({
658
- result,
659
- configCodeChanged,
660
- routeConfigCodeChanged,
661
- configChanged,
662
- routeConfigChanged,
663
- path: filepath,
664
- event
665
- });
666
- }
667
- if (result.ok) {
668
- currentConfig = result.value;
669
- }
670
- });
671
- }
672
- return () => {
673
- changeHandlers = changeHandlers.filter(
674
- (changeHandler) => changeHandler !== handler
675
- );
676
- };
677
- },
678
- close: async () => {
679
- changeHandlers = [];
680
- await viteNodeContext.devServer.close();
681
- await fsWatcher?.close();
682
- }
683
- };
684
- }
685
- async function loadConfig({
686
- rootDirectory,
687
- mode,
688
- skipRoutes
689
- }) {
690
- let configLoader = await createConfigLoader({
691
- rootDirectory,
692
- mode,
693
- skipRoutes,
694
- watch: false
695
- });
696
- let config = await configLoader.getConfig();
697
- await configLoader.close();
698
- return config;
699
- }
700
- function omitRoutes(config) {
701
- return {
702
- ...config,
703
- routes: {}
704
- };
705
- }
706
- function isEntryFile(entryBasename, filename2) {
707
- return entryExts.some((ext) => filename2 === `${entryBasename}${ext}`);
708
- }
709
- function findEntry(dir, basename3, options) {
710
- let currentDir = import_pathe3.default.resolve(dir);
711
- let { root } = import_pathe3.default.parse(currentDir);
712
- while (true) {
713
- for (let ext of options?.extensions ?? entryExts) {
714
- let file = import_pathe3.default.resolve(currentDir, basename3 + ext);
715
- if (import_node_fs.default.existsSync(file)) {
716
- return options?.absolute ?? false ? file : import_pathe3.default.relative(dir, file);
717
- }
718
- }
719
- if (!options?.walkParents) {
720
- return void 0;
721
- }
722
- let parentDir = import_pathe3.default.dirname(currentDir);
723
- if (currentDir === root || parentDir === currentDir) {
724
- return void 0;
725
- }
726
- currentDir = parentDir;
727
- }
728
- }
729
- function isEntryFileDependency(moduleGraph, entryFilepath, filepath, visited = /* @__PURE__ */ new Set()) {
730
- entryFilepath = import_pathe3.default.normalize(entryFilepath);
731
- filepath = import_pathe3.default.normalize(filepath);
732
- if (visited.has(filepath)) {
733
- return false;
734
- }
735
- visited.add(filepath);
736
- if (filepath === entryFilepath) {
737
- return true;
738
- }
739
- let mod = moduleGraph.getModuleById(filepath);
740
- if (!mod) {
741
- return false;
742
- }
743
- for (let importer of mod.importers) {
744
- if (!importer.id) {
745
- continue;
746
- }
747
- if (importer.id === entryFilepath || isEntryFileDependency(moduleGraph, entryFilepath, importer.id, visited)) {
748
- return true;
749
- }
750
- }
751
- return false;
752
- }
753
- function isIgnoredByWatcher(path10, { root, appDirectory }) {
754
- let dirname5 = import_pathe3.default.dirname(path10);
755
- let ignoredByPath = !dirname5.startsWith(appDirectory) && // Ensure we're only watching files outside of the app directory
756
- // that are at the root level, not nested in subdirectories
757
- path10 !== root && // Watch the root directory itself
758
- dirname5 !== root;
759
- if (ignoredByPath) {
760
- return true;
761
- }
762
- try {
763
- let stat = import_node_fs.default.statSync(path10, { throwIfNoEntry: false });
764
- if (stat && !stat.isFile() && !stat.isDirectory()) {
765
- return true;
766
- }
767
- } catch {
768
- return true;
769
- }
770
- return false;
771
- }
772
- var import_node_fs, import_node_child_process, import_pathe3, import_chokidar, import_picocolors, import_pick2, import_omit, import_cloneDeep, import_isEqual, excludedConfigPresetKeys, mergeReactRouterConfig, deepFreeze, entryExts;
773
- var init_config = __esm({
774
- "config/config.ts"() {
775
- "use strict";
776
- import_node_fs = __toESM(require("fs"));
777
- import_node_child_process = require("child_process");
778
- init_vite_node();
779
- import_pathe3 = __toESM(require("pathe"));
780
- import_chokidar = __toESM(require("chokidar"));
781
- import_picocolors = __toESM(require("picocolors"));
782
- import_pick2 = __toESM(require("lodash/pick"));
783
- import_omit = __toESM(require("lodash/omit"));
784
- import_cloneDeep = __toESM(require("lodash/cloneDeep"));
785
- import_isEqual = __toESM(require("lodash/isEqual"));
786
- init_routes();
787
- init_detectPackageManager();
788
- excludedConfigPresetKeys = ["presets"];
789
- mergeReactRouterConfig = (...configs) => {
790
- let reducer = (configA, configB) => {
791
- let mergeRequired = (key) => configA[key] !== void 0 && configB[key] !== void 0;
792
- return {
793
- ...configA,
794
- ...configB,
795
- ...mergeRequired("buildEnd") ? {
796
- buildEnd: async (...args) => {
797
- await Promise.all([
798
- configA.buildEnd?.(...args),
799
- configB.buildEnd?.(...args)
800
- ]);
801
- }
802
- } : {},
803
- ...mergeRequired("future") ? {
804
- future: {
805
- ...configA.future,
806
- ...configB.future
807
- }
808
- } : {},
809
- ...mergeRequired("presets") ? {
810
- presets: [...configA.presets ?? [], ...configB.presets ?? []]
811
- } : {}
812
- };
813
- };
814
- return configs.reduce(reducer, {});
815
- };
816
- deepFreeze = (o) => {
817
- Object.freeze(o);
818
- let oIsFunction = typeof o === "function";
819
- let hasOwnProp = Object.prototype.hasOwnProperty;
820
- Object.getOwnPropertyNames(o).forEach(function(prop) {
821
- 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])) {
822
- deepFreeze(o[prop]);
823
- }
824
- });
825
- return o;
826
- };
827
- entryExts = [".js", ".jsx", ".ts", ".tsx", ".mjs", ".mts"];
828
- }
829
- });
830
-
831
- // vite/profiler.ts
832
- var import_node_fs2, import_node_path, import_picocolors2, getSession, start, profileCount, stop;
833
- var init_profiler = __esm({
834
- "vite/profiler.ts"() {
835
- "use strict";
836
- import_node_fs2 = __toESM(require("fs"));
837
- import_node_path = __toESM(require("path"));
838
- import_picocolors2 = __toESM(require("picocolors"));
839
- getSession = () => global.__reactRouter_profile_session;
840
- start = async (callback) => {
841
- let inspector = await import("inspector").then((r) => r.default);
842
- let session = global.__reactRouter_profile_session = new inspector.Session();
843
- session.connect();
844
- session.post("Profiler.enable", () => {
845
- session.post("Profiler.start", callback);
846
- });
847
- };
848
- profileCount = 0;
849
- stop = (log) => {
850
- let session = getSession();
851
- if (!session) return;
852
- return new Promise((res, rej) => {
853
- session.post("Profiler.stop", (err2, { profile }) => {
854
- if (err2) return rej(err2);
855
- let outPath = import_node_path.default.resolve(`./react-router-${profileCount++}.cpuprofile`);
856
- import_node_fs2.default.writeFileSync(outPath, JSON.stringify(profile));
857
- log(
858
- import_picocolors2.default.yellow(
859
- `CPU profile written to ${import_picocolors2.default.white(import_picocolors2.default.dim(outPath))}`
860
- )
861
- );
862
- global.__reactRouter_profile_session = void 0;
863
- res();
864
- });
865
- });
866
- };
867
- }
868
- });
869
-
870
- // typegen/context.ts
871
- async function createContext2({
872
- rootDirectory,
873
- watch: watch2,
874
- mode,
875
- rsc
876
- }) {
877
- const configLoader = await createConfigLoader({ rootDirectory, mode, watch: watch2 });
878
- const configResult = await configLoader.getConfig();
879
- if (!configResult.ok) {
880
- throw new Error(configResult.error);
881
- }
882
- const config = configResult.value;
883
- return {
884
- configLoader,
885
- rootDirectory,
886
- config,
887
- rsc
888
- };
889
- }
890
- var init_context = __esm({
891
- "typegen/context.ts"() {
892
- "use strict";
893
- init_config();
894
- }
895
- });
896
-
897
- // vite/babel.ts
898
- var babel_exports = {};
899
- __export(babel_exports, {
900
- generate: () => generate,
901
- parse: () => import_parser.parse,
902
- t: () => t,
903
- traverse: () => traverse
904
- });
905
- var import_parser, t, traverse, generate;
906
- var init_babel = __esm({
907
- "vite/babel.ts"() {
908
- "use strict";
909
- import_parser = require("@babel/parser");
910
- t = __toESM(require("@babel/types"));
911
- traverse = require("@babel/traverse").default;
912
- generate = require("@babel/generator").default;
913
- }
914
- });
915
-
916
- // typegen/params.ts
917
- function parse2(fullpath2) {
918
- const result = {};
919
- let segments = fullpath2.split("/");
920
- segments.forEach((segment) => {
921
- const match = segment.match(/^:([\w-]+)(\?)?/);
922
- if (!match) return;
923
- const param = match[1];
924
- const isRequired = match[2] === void 0;
925
- result[param] ||= isRequired;
926
- return;
927
- });
928
- const hasSplat = segments.at(-1) === "*";
929
- if (hasSplat) result["*"] = true;
930
- return result;
931
- }
932
- var init_params = __esm({
933
- "typegen/params.ts"() {
934
- "use strict";
935
- }
936
- });
937
-
938
- // typegen/route.ts
939
- function lineage(routes2, route) {
940
- const result = [];
941
- while (route) {
942
- result.push(route);
943
- if (!route.parentId) break;
944
- route = routes2[route.parentId];
945
- }
946
- result.reverse();
947
- return result;
948
- }
949
- function fullpath(lineage2) {
950
- const route = lineage2.at(-1);
951
- if (lineage2.length === 1 && route?.id === "root") return "/";
952
- const isLayout = route && route.index !== true && route.path === void 0;
953
- if (isLayout) return void 0;
954
- return "/" + lineage2.map((route2) => route2.path?.replace(/^\//, "")?.replace(/\/$/, "")).filter((path10) => path10 !== void 0 && path10 !== "").join("/");
955
- }
956
- var init_route = __esm({
957
- "typegen/route.ts"() {
958
- "use strict";
959
- }
960
- });
961
-
962
- // typegen/generate.ts
963
- function typesDirectory(ctx) {
964
- return Path3.join(ctx.rootDirectory, ".react-router/types");
965
- }
966
- function generateFuture(ctx) {
967
- const filename2 = Path3.join(typesDirectory(ctx), "+future.ts");
968
- const content = import_dedent.default`
969
- // Generated by React Router
970
-
971
- import "react-router";
972
-
973
- declare module "react-router" {
974
- interface Future {
975
- v8_middleware: ${ctx.config.future.v8_middleware}
976
- }
977
- }
978
- `;
979
- return { filename: filename2, content };
980
- }
981
- function generateServerBuild(ctx) {
982
- const filename2 = Path3.join(typesDirectory(ctx), "+server-build.d.ts");
983
- const content = import_dedent.default`
984
- // Generated by React Router
985
-
986
- declare module "virtual:react-router/server-build" {
987
- import { ServerBuild } from "react-router";
988
- export const assets: ServerBuild["assets"];
989
- export const assetsBuildDirectory: ServerBuild["assetsBuildDirectory"];
990
- export const basename: ServerBuild["basename"];
991
- export const entry: ServerBuild["entry"];
992
- export const future: ServerBuild["future"];
993
- export const isSpaMode: ServerBuild["isSpaMode"];
994
- export const prerender: ServerBuild["prerender"];
995
- export const publicPath: ServerBuild["publicPath"];
996
- export const routeDiscovery: ServerBuild["routeDiscovery"];
997
- export const routes: ServerBuild["routes"];
998
- export const ssr: ServerBuild["ssr"];
999
- export const allowedActionOrigins: ServerBuild["allowedActionOrigins"];
1000
- export const unstable_getCriticalCss: ServerBuild["unstable_getCriticalCss"];
1001
- }
1002
- `;
1003
- return { filename: filename2, content };
1004
- }
1005
- function generateRoutes(ctx) {
1006
- const fileToRoutes = /* @__PURE__ */ new Map();
1007
- const lineages = /* @__PURE__ */ new Map();
1008
- const allPages = /* @__PURE__ */ new Set();
1009
- const routeToPages = /* @__PURE__ */ new Map();
1010
- for (const route of Object.values(ctx.config.routes)) {
1011
- let routeIds = fileToRoutes.get(route.file);
1012
- if (!routeIds) {
1013
- routeIds = /* @__PURE__ */ new Set();
1014
- fileToRoutes.set(route.file, routeIds);
1015
- }
1016
- routeIds.add(route.id);
1017
- const lineage2 = lineage(ctx.config.routes, route);
1018
- lineages.set(route.id, lineage2);
1019
- const fullpath2 = fullpath(lineage2);
1020
- if (!fullpath2) continue;
1021
- const pages = expand(fullpath2);
1022
- pages.forEach((page) => allPages.add(page));
1023
- lineage2.forEach(({ id }) => {
1024
- let routePages = routeToPages.get(id);
1025
- if (!routePages) {
1026
- routePages = /* @__PURE__ */ new Set();
1027
- routeToPages.set(id, routePages);
1028
- }
1029
- pages.forEach((page) => routePages.add(page));
1030
- });
1031
- }
1032
- const routesTs = {
1033
- filename: Path3.join(typesDirectory(ctx), "+routes.ts"),
1034
- content: import_dedent.default`
1035
- // Generated by React Router
1036
-
1037
- import "react-router"
1038
-
1039
- declare module "react-router" {
1040
- interface Register {
1041
- pages: Pages
1042
- routeFiles: RouteFiles
1043
- routeModules: RouteModules
1044
- }
1045
- }
1046
- ` + "\n\n" + generate(pagesType(allPages)).code + "\n\n" + generate(routeFilesType({ fileToRoutes, routeToPages })).code + "\n\n" + generate(routeModulesType(ctx)).code
1047
- };
1048
- const allAnnotations = Array.from(fileToRoutes.entries()).filter(([file]) => isInAppDirectory(ctx, file)).map(
1049
- ([file, routeIds]) => getRouteAnnotations({ ctx, file, routeIds, lineages })
1050
- );
1051
- return [routesTs, ...allAnnotations];
1052
- }
1053
- function pagesType(pages) {
1054
- return t2.tsTypeAliasDeclaration(
1055
- t2.identifier("Pages"),
1056
- null,
1057
- t2.tsTypeLiteral(
1058
- Array.from(pages).map((page) => {
1059
- return t2.tsPropertySignature(
1060
- t2.stringLiteral(page),
1061
- t2.tsTypeAnnotation(
1062
- t2.tsTypeLiteral([
1063
- t2.tsPropertySignature(
1064
- t2.identifier("params"),
1065
- t2.tsTypeAnnotation(paramsType(page))
1066
- )
1067
- ])
1068
- )
1069
- );
1070
- })
1071
- )
1072
- );
1073
- }
1074
- function routeFilesType({
1075
- fileToRoutes,
1076
- routeToPages
1077
- }) {
1078
- return t2.tsTypeAliasDeclaration(
1079
- t2.identifier("RouteFiles"),
1080
- null,
1081
- t2.tsTypeLiteral(
1082
- Array.from(fileToRoutes).map(
1083
- ([file, routeIds]) => t2.tsPropertySignature(
1084
- t2.stringLiteral(file),
1085
- t2.tsTypeAnnotation(
1086
- t2.tsUnionType(
1087
- Array.from(routeIds).map((routeId) => {
1088
- const pages = routeToPages.get(routeId) ?? /* @__PURE__ */ new Set();
1089
- return t2.tsTypeLiteral([
1090
- t2.tsPropertySignature(
1091
- t2.identifier("id"),
1092
- t2.tsTypeAnnotation(
1093
- t2.tsLiteralType(t2.stringLiteral(routeId))
1094
- )
1095
- ),
1096
- t2.tsPropertySignature(
1097
- t2.identifier("page"),
1098
- t2.tsTypeAnnotation(
1099
- pages.size > 0 ? t2.tsUnionType(
1100
- Array.from(pages).map(
1101
- (page) => t2.tsLiteralType(t2.stringLiteral(page))
1102
- )
1103
- ) : t2.tsNeverKeyword()
1104
- )
1105
- )
1106
- ]);
1107
- })
1108
- )
1109
- )
1110
- )
1111
- )
1112
- )
1113
- );
1114
- }
1115
- function routeModulesType(ctx) {
1116
- return t2.tsTypeAliasDeclaration(
1117
- t2.identifier("RouteModules"),
1118
- null,
1119
- t2.tsTypeLiteral(
1120
- Object.values(ctx.config.routes).map(
1121
- (route) => t2.tsPropertySignature(
1122
- t2.stringLiteral(route.id),
1123
- t2.tsTypeAnnotation(
1124
- isInAppDirectory(ctx, route.file) ? t2.tsTypeQuery(
1125
- t2.tsImportType(
1126
- t2.stringLiteral(
1127
- `./${Path3.relative(ctx.rootDirectory, ctx.config.appDirectory)}/${route.file}`
1128
- )
1129
- )
1130
- ) : t2.tsUnknownKeyword()
1131
- )
1132
- )
1133
- )
1134
- )
1135
- );
1136
- }
1137
- function isInAppDirectory(ctx, routeFile) {
1138
- const path10 = Path3.resolve(ctx.config.appDirectory, routeFile);
1139
- return path10.startsWith(ctx.config.appDirectory);
1140
- }
1141
- function getRouteAnnotations({
1142
- ctx,
1143
- file,
1144
- routeIds,
1145
- lineages
1146
- }) {
1147
- const filename2 = Path3.join(
1148
- typesDirectory(ctx),
1149
- Path3.relative(ctx.rootDirectory, ctx.config.appDirectory),
1150
- Path3.dirname(file),
1151
- "+types",
1152
- Pathe.filename(file) + ".ts"
1153
- );
1154
- const matchesType = t2.tsTypeAliasDeclaration(
1155
- t2.identifier("Matches"),
1156
- null,
1157
- t2.tsUnionType(
1158
- Array.from(routeIds).map((routeId) => {
1159
- const lineage2 = lineages.get(routeId);
1160
- return t2.tsTupleType(
1161
- lineage2.map(
1162
- (route) => t2.tsTypeLiteral([
1163
- t2.tsPropertySignature(
1164
- t2.identifier("id"),
1165
- t2.tsTypeAnnotation(t2.tsLiteralType(t2.stringLiteral(route.id)))
1166
- ),
1167
- t2.tsPropertySignature(
1168
- t2.identifier("module"),
1169
- t2.tsTypeAnnotation(
1170
- t2.tsTypeQuery(
1171
- t2.tsImportType(
1172
- t2.stringLiteral(
1173
- relativeImportSource(
1174
- rootDirsPath(ctx, filename2),
1175
- Path3.resolve(ctx.config.appDirectory, route.file)
1176
- )
1177
- )
1178
- )
1179
- )
1180
- )
1181
- )
1182
- ])
1183
- )
1184
- );
1185
- })
1186
- )
1187
- );
1188
- const routeImportSource = relativeImportSource(
1189
- rootDirsPath(ctx, filename2),
1190
- Path3.resolve(ctx.config.appDirectory, file)
1191
- );
1192
- const content = import_dedent.default`
1193
- // Generated by React Router
1194
-
1195
- import type { GetInfo, GetAnnotations } from "react-router/internal";
1196
-
1197
- type Module = typeof import("${routeImportSource}")
1198
-
1199
- type Info = GetInfo<{
1200
- file: "${file}",
1201
- module: Module
1202
- }>
1203
- ` + "\n\n" + generate(matchesType).code + "\n\n" + import_dedent.default`
1204
- type Annotations = GetAnnotations<Info & { module: Module, matches: Matches }>;
1205
-
1206
- export namespace Route {
1207
- // links
1208
- export type LinkDescriptors = Annotations["LinkDescriptors"];
1209
- export type LinksFunction = Annotations["LinksFunction"];
1210
-
1211
- // meta
1212
- export type MetaArgs = Annotations["MetaArgs"];
1213
- export type MetaDescriptors = Annotations["MetaDescriptors"];
1214
- export type MetaFunction = Annotations["MetaFunction"];
1215
-
1216
- // headers
1217
- export type HeadersArgs = Annotations["HeadersArgs"];
1218
- export type HeadersFunction = Annotations["HeadersFunction"];
1219
-
1220
- // middleware
1221
- export type MiddlewareFunction = Annotations["MiddlewareFunction"];
1222
-
1223
- // clientMiddleware
1224
- export type ClientMiddlewareFunction = Annotations["ClientMiddlewareFunction"];
1225
-
1226
- // loader
1227
- export type LoaderArgs = Annotations["LoaderArgs"];
1228
-
1229
- // clientLoader
1230
- export type ClientLoaderArgs = Annotations["ClientLoaderArgs"];
1231
-
1232
- // action
1233
- export type ActionArgs = Annotations["ActionArgs"];
1234
-
1235
- // clientAction
1236
- export type ClientActionArgs = Annotations["ClientActionArgs"];
1237
-
1238
- // HydrateFallback
1239
- export type HydrateFallbackProps = Annotations["HydrateFallbackProps"];
1240
-
1241
- // ServerHydrateFallback
1242
- export type ServerHydrateFallbackProps = Annotations["ServerHydrateFallbackProps"];
1243
-
1244
- // Component
1245
- export type ComponentProps = Annotations["ComponentProps"];
1246
-
1247
- // ServerComponent
1248
- export type ServerComponentProps = Annotations["ServerComponentProps"];
1249
-
1250
- // ErrorBoundary
1251
- export type ErrorBoundaryProps = Annotations["ErrorBoundaryProps"];
1252
-
1253
- // ServerErrorBoundary
1254
- export type ServerErrorBoundaryProps = Annotations["ServerErrorBoundaryProps"];
1255
- }
1256
- `;
1257
- return { filename: filename2, content };
1258
- }
1259
- function relativeImportSource(from, to) {
1260
- let path10 = Path3.relative(Path3.dirname(from), to);
1261
- let extension = Path3.extname(path10);
1262
- path10 = Path3.join(Path3.dirname(path10), Pathe.filename(path10));
1263
- if (!path10.startsWith("../")) path10 = "./" + path10;
1264
- if (!extension || /\.(js|ts)x?$/.test(extension)) {
1265
- extension = ".js";
1266
- }
1267
- return path10 + extension;
1268
- }
1269
- function rootDirsPath(ctx, typesPath) {
1270
- const rel = Path3.relative(typesDirectory(ctx), typesPath);
1271
- return Path3.join(ctx.rootDirectory, rel);
1272
- }
1273
- function paramsType(path10) {
1274
- const params = parse2(path10);
1275
- return t2.tsTypeLiteral(
1276
- Object.entries(params).map(([param, isRequired]) => {
1277
- const property = t2.tsPropertySignature(
1278
- t2.stringLiteral(param),
1279
- t2.tsTypeAnnotation(t2.tsStringKeyword())
1280
- );
1281
- property.optional = !isRequired;
1282
- return property;
1283
- })
1284
- );
1285
- }
1286
- function expand(fullpath2) {
1287
- function recurse(segments2, index) {
1288
- if (index === segments2.length) return [""];
1289
- const segment = segments2[index];
1290
- const isOptional = segment.endsWith("?");
1291
- const isDynamic = segment.startsWith(":");
1292
- const required = segment.replace(/\?$/, "");
1293
- const keep = !isOptional || isDynamic;
1294
- const kept = isDynamic ? segment : required;
1295
- const withoutSegment = recurse(segments2, index + 1);
1296
- const withSegment = withoutSegment.map((rest) => [kept, rest].join("/"));
1297
- if (keep) return withSegment;
1298
- return [...withoutSegment, ...withSegment];
1299
- }
1300
- const segments = fullpath2.split("/");
1301
- const expanded = /* @__PURE__ */ new Set();
1302
- for (let result of recurse(segments, 0)) {
1303
- if (result !== "/") result = result.replace(/\/$/, "");
1304
- expanded.add(result);
1305
- }
1306
- return expanded;
1307
- }
1308
- var import_dedent, Path3, Pathe, t2;
1309
- var init_generate = __esm({
1310
- "typegen/generate.ts"() {
1311
- "use strict";
1312
- import_dedent = __toESM(require("dedent"));
1313
- Path3 = __toESM(require("pathe"));
1314
- Pathe = __toESM(require("pathe/utils"));
1315
- init_babel();
1316
- init_params();
1317
- init_route();
1318
- ({ t: t2 } = babel_exports);
1319
- }
1320
- });
1321
-
1322
- // typegen/index.ts
1323
- async function clearRouteModuleAnnotations(ctx) {
1324
- await import_promises.default.rm(
1325
- Path4.join(typesDirectory(ctx), Path4.basename(ctx.config.appDirectory)),
1326
- { recursive: true, force: true }
1327
- );
1328
- }
1329
- async function write(...files) {
1330
- return Promise.all(
1331
- files.map(async ({ filename: filename2, content }) => {
1332
- await import_promises.default.mkdir(Path4.dirname(filename2), { recursive: true });
1333
- await import_promises.default.writeFile(filename2, content);
1334
- })
1335
- );
1336
- }
1337
- async function run(rootDirectory, { mode, rsc }) {
1338
- const ctx = await createContext2({ rootDirectory, mode, rsc, watch: false });
1339
- await import_promises.default.rm(typesDirectory(ctx), { recursive: true, force: true });
1340
- await write(
1341
- generateFuture(ctx),
1342
- generateServerBuild(ctx),
1343
- ...generateRoutes(ctx)
1344
- );
1345
- }
1346
- async function watch(rootDirectory, { mode, logger, rsc }) {
1347
- const ctx = await createContext2({ rootDirectory, mode, rsc, watch: true });
1348
- await import_promises.default.rm(typesDirectory(ctx), { recursive: true, force: true });
1349
- await write(
1350
- generateFuture(ctx),
1351
- generateServerBuild(ctx),
1352
- ...generateRoutes(ctx)
1353
- );
1354
- logger?.info((0, import_picocolors3.green)("generated types"), { timestamp: true, clear: true });
1355
- ctx.configLoader.onChange(
1356
- async ({ result, configChanged, routeConfigChanged }) => {
1357
- if (!result.ok) {
1358
- logger?.error((0, import_picocolors3.red)(result.error), { timestamp: true, clear: true });
1359
- return;
1360
- }
1361
- ctx.config = result.value;
1362
- if (configChanged) {
1363
- await write(generateFuture(ctx));
1364
- logger?.info((0, import_picocolors3.green)("regenerated types"), {
1365
- timestamp: true,
1366
- clear: true
1367
- });
1368
- }
1369
- if (routeConfigChanged) {
1370
- await clearRouteModuleAnnotations(ctx);
1371
- await write(...generateRoutes(ctx));
1372
- logger?.info((0, import_picocolors3.green)("regenerated types"), {
1373
- timestamp: true,
1374
- clear: true
1375
- });
1376
- }
1377
- }
1378
- );
1379
- return {
1380
- close: async () => await ctx.configLoader.close()
1381
- };
1382
- }
1383
- var import_promises, Path4, import_picocolors3;
1384
- var init_typegen = __esm({
1385
- "typegen/index.ts"() {
1386
- "use strict";
1387
- import_promises = __toESM(require("fs/promises"));
1388
- Path4 = __toESM(require("pathe"));
1389
- import_picocolors3 = require("picocolors");
1390
- init_context();
1391
- init_generate();
1392
- }
1393
- });
1394
-
1395
- // vite/has-rsc-plugin.ts
1396
- async function hasReactRouterRscPlugin({
1397
- root,
1398
- viteBuildOptions: { config, logLevel, mode }
1399
- }) {
1400
- await preloadVite();
1401
- const vite2 = getVite();
1402
- const viteConfig = await vite2.resolveConfig(
1403
- {
1404
- configFile: config,
1405
- logLevel,
1406
- mode: mode ?? "production",
1407
- root
1408
- },
1409
- "build",
1410
- // command
1411
- "production",
1412
- // default mode
1413
- "production"
1414
- // default NODE_ENV
1415
- );
1416
- return viteConfig.plugins.some(
1417
- (plugin) => plugin?.name === "react-router/rsc"
1418
- );
1419
- }
1420
- var init_has_rsc_plugin = __esm({
1421
- "vite/has-rsc-plugin.ts"() {
1422
- "use strict";
1423
- init_vite();
1424
- }
1425
- });
1426
-
1427
- // vite/node-adapter.ts
1428
- var init_node_adapter = __esm({
1429
- "vite/node-adapter.ts"() {
1430
- "use strict";
1431
- init_invariant();
1432
- }
1433
- });
1434
-
1435
- // vite/resolve-file-url.ts
1436
- var path4;
1437
- var init_resolve_file_url = __esm({
1438
- "vite/resolve-file-url.ts"() {
1439
- "use strict";
1440
- path4 = __toESM(require("path"));
1441
- init_vite();
1442
- }
1443
- });
1444
-
1445
- // vite/styles.ts
1446
- var path5, import_react_router, cssFileRegExp, cssModulesRegExp;
1447
- var init_styles = __esm({
1448
- "vite/styles.ts"() {
1449
- "use strict";
1450
- path5 = __toESM(require("path"));
1451
- import_react_router = require("react-router");
1452
- init_resolve_file_url();
1453
- init_babel();
1454
- cssFileRegExp = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
1455
- cssModulesRegExp = new RegExp(`\\.module${cssFileRegExp.source}`);
1456
- }
1457
- });
1458
-
1459
- // vite/virtual-module.ts
1460
- function create(name) {
1461
- let id = `virtual:react-router/${name}`;
1462
- return {
1463
- id,
1464
- resolvedId: `\0${id}`,
1465
- url: `/@id/__x00__${id}`
1466
- };
1467
- }
1468
- var init_virtual_module = __esm({
1469
- "vite/virtual-module.ts"() {
1470
- "use strict";
1471
- }
1472
- });
1473
-
1474
- // vite/resolve-relative-route-file-path.ts
1475
- var import_pathe4;
1476
- var init_resolve_relative_route_file_path = __esm({
1477
- "vite/resolve-relative-route-file-path.ts"() {
1478
- "use strict";
1479
- import_pathe4 = __toESM(require("pathe"));
1480
- init_vite();
1481
- }
1482
- });
1483
-
1484
- // vite/combine-urls.ts
1485
- var init_combine_urls = __esm({
1486
- "vite/combine-urls.ts"() {
1487
- "use strict";
1488
- }
1489
- });
1490
-
1491
- // vite/remove-exports.ts
1492
- var import_babel_dead_code_elimination;
1493
- var init_remove_exports = __esm({
1494
- "vite/remove-exports.ts"() {
1495
- "use strict";
1496
- import_babel_dead_code_elimination = require("babel-dead-code-elimination");
1497
- init_babel();
1498
- }
1499
- });
1500
-
1501
- // vite/has-dependency.ts
1502
- var init_has_dependency = __esm({
1503
- "vite/has-dependency.ts"() {
1504
- "use strict";
1505
- }
1506
- });
1507
-
1508
- // vite/cache.ts
1509
- var init_cache = __esm({
1510
- "vite/cache.ts"() {
1511
- "use strict";
1512
- }
1513
- });
1514
-
1515
- // vite/route-chunks.ts
1516
- function getRouteChunkModuleId(filePath, chunkName) {
1517
- return `${filePath}${routeChunkQueryStrings[chunkName]}`;
1518
- }
1519
- function isRouteChunkModuleId(id) {
1520
- return Object.values(routeChunkQueryStrings).some(
1521
- (queryString) => id.endsWith(queryString)
1522
- );
1523
- }
1524
- function isRouteChunkName(name) {
1525
- return name === mainChunkName || routeChunkExportNames.includes(name);
1526
- }
1527
- function getRouteChunkNameFromModuleId(id) {
1528
- if (!isRouteChunkModuleId(id)) {
1529
- return null;
1530
- }
1531
- let chunkName = id.split(routeChunkQueryStringPrefix)[1].split("&")[0];
1532
- if (!isRouteChunkName(chunkName)) {
1533
- return null;
1534
- }
1535
- return chunkName;
1536
- }
1537
- var routeChunkExportNames, mainChunkName, routeChunkNames, routeChunkQueryStringPrefix, routeChunkQueryStrings;
1538
- var init_route_chunks = __esm({
1539
- "vite/route-chunks.ts"() {
1540
- "use strict";
1541
- init_invariant();
1542
- init_cache();
1543
- init_babel();
1544
- routeChunkExportNames = [
1545
- "clientAction",
1546
- "clientLoader",
1547
- "clientMiddleware",
1548
- "HydrateFallback"
1549
- ];
1550
- mainChunkName = "main";
1551
- routeChunkNames = ["main", ...routeChunkExportNames];
1552
- routeChunkQueryStringPrefix = "?route-chunk=";
1553
- routeChunkQueryStrings = {
1554
- main: `${routeChunkQueryStringPrefix}main`,
1555
- clientAction: `${routeChunkQueryStringPrefix}clientAction`,
1556
- clientLoader: `${routeChunkQueryStringPrefix}clientLoader`,
1557
- clientMiddleware: `${routeChunkQueryStringPrefix}clientMiddleware`,
1558
- HydrateFallback: `${routeChunkQueryStringPrefix}HydrateFallback`
1559
- };
1560
- }
1561
- });
1562
-
1563
- // vite/optimize-deps-entries.ts
1564
- var import_tinyglobby;
1565
- var init_optimize_deps_entries = __esm({
1566
- "vite/optimize-deps-entries.ts"() {
1567
- "use strict";
1568
- import_tinyglobby = require("tinyglobby");
1569
- init_resolve_relative_route_file_path();
1570
- init_vite();
1571
- }
1572
- });
1573
-
1574
- // vite/with-props.ts
1575
- var init_with_props = __esm({
1576
- "vite/with-props.ts"() {
1577
- "use strict";
1578
- init_babel();
1579
- }
1580
- });
1581
-
1582
- // vite/load-dotenv.ts
1583
- var init_load_dotenv = __esm({
1584
- "vite/load-dotenv.ts"() {
1585
- "use strict";
1586
- }
1587
- });
1588
-
1589
- // vite/plugins/validate-plugin-order.ts
1590
- var init_validate_plugin_order = __esm({
1591
- "vite/plugins/validate-plugin-order.ts"() {
1592
- "use strict";
1593
- }
1594
- });
1595
-
1596
- // vite/plugins/warn-on-client-source-maps.ts
1597
- var import_picocolors4;
1598
- var init_warn_on_client_source_maps = __esm({
1599
- "vite/plugins/warn-on-client-source-maps.ts"() {
1600
- "use strict";
1601
- import_picocolors4 = __toESM(require("picocolors"));
1602
- init_invariant();
1603
- }
1604
- });
1605
-
1606
- // vite/plugins/prerender.ts
1607
- var import_promises2, import_node_path2;
1608
- var init_prerender = __esm({
1609
- "vite/plugins/prerender.ts"() {
1610
- "use strict";
1611
- import_promises2 = require("fs/promises");
1612
- import_node_path2 = __toESM(require("path"));
1613
- }
1614
- });
1615
-
1616
- // vite/plugin.ts
1617
- async function resolveViteConfig({
1618
- configFile,
1619
- mode,
1620
- root,
1621
- plugins
1622
- }) {
1623
- let vite2 = getVite();
1624
- let viteConfig = await vite2.resolveConfig(
1625
- { mode, configFile, root, plugins },
1626
- "build",
1627
- // command
1628
- "production",
1629
- // default mode
1630
- "production"
1631
- // default NODE_ENV
1632
- );
1633
- if (typeof viteConfig.build.manifest === "string") {
1634
- throw new Error("Custom Vite manifest paths are not supported");
1635
- }
1636
- return viteConfig;
1637
- }
1638
- function extractPluginContext(viteConfig) {
1639
- return viteConfig["__reactRouterPluginContext"];
1640
- }
1641
- function isSsrBundleEnvironmentName(name) {
1642
- return name.startsWith(SSR_BUNDLE_PREFIX);
1643
- }
1644
- function getServerEnvironmentEntries(ctx, record) {
1645
- return Object.entries(record).filter(
1646
- ([name]) => ctx.buildManifest?.serverBundles ? isSsrBundleEnvironmentName(name) : name === "ssr"
1647
- );
1648
- }
1649
- function getServerEnvironmentKeys(ctx, record) {
1650
- return getServerEnvironmentEntries(ctx, record).map(([key]) => key);
1651
- }
1652
- function getServerBundleIds(ctx) {
1653
- return ctx.buildManifest?.serverBundles ? Object.keys(ctx.buildManifest.serverBundles) : void 0;
1654
- }
1655
- async function cleanBuildDirectory(viteConfig, ctx) {
1656
- let buildDirectory = ctx.reactRouterConfig.buildDirectory;
1657
- let isWithinRoot = () => {
1658
- let relativePath = path8.relative(ctx.rootDirectory, buildDirectory);
1659
- return !relativePath.startsWith("..") && !path8.isAbsolute(relativePath);
1660
- };
1661
- if (viteConfig.build.emptyOutDir ?? isWithinRoot()) {
1662
- await (0, import_promises3.rm)(buildDirectory, { force: true, recursive: true });
1663
- }
1664
- }
1665
- async function cleanViteManifests(environmentsOptions, ctx) {
1666
- let viteManifestPaths = Object.entries(environmentsOptions).map(
1667
- ([environmentName, options]) => {
1668
- let outDir = options.build?.outDir;
1669
- invariant(outDir, `Expected build.outDir for ${environmentName}`);
1670
- return path8.join(outDir, ".vite/manifest.json");
1671
- }
1672
- );
1673
- await Promise.all(
1674
- viteManifestPaths.map(async (viteManifestPath) => {
1675
- let manifestExists = (0, import_node_fs3.existsSync)(viteManifestPath);
1676
- if (!manifestExists) return;
1677
- if (!ctx.viteManifestEnabled) {
1678
- await (0, import_promises3.rm)(viteManifestPath, { force: true, recursive: true });
1679
- }
1680
- let viteDir = path8.dirname(viteManifestPath);
1681
- let viteDirFiles = await (0, import_promises3.readdir)(viteDir, { recursive: true });
1682
- if (viteDirFiles.length === 0) {
1683
- await (0, import_promises3.rm)(viteDir, { force: true, recursive: true });
1684
- }
1685
- })
1686
- );
1687
- }
1688
- function mergeEnvironmentOptions(base, ...overrides) {
1689
- let vite2 = getVite();
1690
- return overrides.reduce(
1691
- (merged, override) => vite2.mergeConfig(merged, override, false),
1692
- base
1693
- );
1694
- }
1695
- async function getEnvironmentOptionsResolvers(ctx, viteCommand) {
1696
- let { serverBuildFile, serverModuleFormat } = ctx.reactRouterConfig;
1697
- let packageRoot = path8.dirname(
1698
- require.resolve("@react-router/dev/package.json")
1699
- );
1700
- let { moduleSyncEnabled } = await import(`file:///${path8.join(packageRoot, "module-sync-enabled/index.mjs")}`);
1701
- let vite2 = getVite();
1702
- function getBaseOptions({
1703
- viteUserConfig
1704
- }) {
1705
- const rollupOptions = {
1706
- preserveEntrySignatures: "exports-only",
1707
- // Silence Rollup "use client" warnings
1708
- // Adapted from https://github.com/vitejs/vite-plugin-react/pull/144
1709
- onwarn(warning, defaultHandler) {
1710
- if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
1711
- return;
1712
- }
1713
- let userHandler = viteUserConfig.build?.rollupOptions?.onwarn;
1714
- if (userHandler) {
1715
- userHandler(warning, defaultHandler);
1716
- } else {
1717
- defaultHandler(warning);
1718
- }
1719
- }
1720
- };
1721
- return {
1722
- build: {
1723
- cssMinify: viteUserConfig.build?.cssMinify ?? true,
1724
- manifest: true,
1725
- // The manifest is enabled for all builds to detect SSR-only assets
1726
- rollupOptions
1727
- }
1728
- };
1729
- }
1730
- function getBaseServerOptions({
1731
- viteUserConfig
1732
- }) {
1733
- let maybeModuleSyncConditions = [
1734
- ...moduleSyncEnabled ? ["module-sync"] : []
1735
- ];
1736
- let maybeDevelopmentConditions = viteCommand === "build" ? [] : ["development"];
1737
- let maybeDefaultServerConditions = vite2.defaultServerConditions || [];
1738
- let defaultExternalConditions = ["node"];
1739
- let baseConditions = [
1740
- ...maybeDevelopmentConditions,
1741
- ...maybeModuleSyncConditions
1742
- ];
1743
- return mergeEnvironmentOptions(getBaseOptions({ viteUserConfig }), {
1744
- resolve: {
1745
- external: (
1746
- // If `v8_viteEnvironmentApi` is `true`, `resolve.external` is set in the `configEnvironment` hook
1747
- ctx.reactRouterConfig.future.v8_viteEnvironmentApi ? void 0 : ssrExternals
1748
- ),
1749
- conditions: [...baseConditions, ...maybeDefaultServerConditions],
1750
- externalConditions: [...baseConditions, ...defaultExternalConditions]
1751
- },
1752
- build: {
1753
- // We move SSR-only assets to client assets. Note that the
1754
- // SSR build can also emit code-split JS files (e.g., by
1755
- // dynamic import) under the same assets directory
1756
- // regardless of "ssrEmitAssets" option, so we also need to
1757
- // keep these JS files to be kept as-is.
1758
- ssrEmitAssets: true,
1759
- copyPublicDir: false,
1760
- // The client only uses assets in the public directory
1761
- rollupOptions: {
1762
- input: (ctx.reactRouterConfig.future.v8_viteEnvironmentApi ? viteUserConfig.environments?.ssr?.build?.rollupOptions?.input : viteUserConfig.build?.rollupOptions?.input) ?? virtual.serverBuild.id,
1763
- output: {
1764
- entryFileNames: serverBuildFile,
1765
- format: serverModuleFormat
1766
- }
1767
- }
1768
- }
1769
- });
1770
- }
1771
- let environmentOptionsResolvers = {
1772
- client: ({ viteUserConfig }) => mergeEnvironmentOptions(getBaseOptions({ viteUserConfig }), {
1773
- build: {
1774
- rollupOptions: {
1775
- input: [
1776
- ctx.entryClientFilePath,
1777
- ...Object.values(ctx.reactRouterConfig.routes).flatMap(
1778
- (route) => {
1779
- let routeFilePath = path8.resolve(
1780
- ctx.reactRouterConfig.appDirectory,
1781
- route.file
1782
- );
1783
- let isRootRoute = route.file === ctx.reactRouterConfig.routes.root.file;
1784
- let code = (0, import_node_fs3.readFileSync)(routeFilePath, "utf-8");
1785
- return [
1786
- `${routeFilePath}${BUILD_CLIENT_ROUTE_QUERY_STRING}`,
1787
- ...ctx.reactRouterConfig.future.v8_splitRouteModules && !isRootRoute ? routeChunkExportNames.map(
1788
- (exportName) => code.includes(exportName) ? getRouteChunkModuleId(routeFilePath, exportName) : null
1789
- ) : []
1790
- ].filter(isNonNullable);
1791
- }
1792
- )
1793
- ],
1794
- output: (ctx.reactRouterConfig.future.v8_viteEnvironmentApi ? viteUserConfig?.environments?.client?.build?.rollupOptions?.output : viteUserConfig?.build?.rollupOptions?.output) ?? {
1795
- entryFileNames: ({ moduleIds }) => {
1796
- let routeChunkModuleId = moduleIds.find(isRouteChunkModuleId);
1797
- let routeChunkName = routeChunkModuleId ? getRouteChunkNameFromModuleId(routeChunkModuleId)?.replace(
1798
- "unstable_",
1799
- ""
1800
- ) : null;
1801
- let routeChunkSuffix = routeChunkName ? `-${(0, import_kebabCase.default)(routeChunkName)}` : "";
1802
- let assetsDir = (ctx.reactRouterConfig.future.v8_viteEnvironmentApi ? viteUserConfig?.environments?.client?.build?.assetsDir : null) ?? viteUserConfig?.build?.assetsDir ?? "assets";
1803
- return path8.posix.join(
1804
- assetsDir,
1805
- `[name]${routeChunkSuffix}-[hash].js`
1806
- );
1807
- }
1808
- }
1809
- },
1810
- outDir: getClientBuildDirectory(ctx.reactRouterConfig)
1811
- }
1812
- })
1813
- };
1814
- let serverBundleIds = getServerBundleIds(ctx);
1815
- if (serverBundleIds) {
1816
- for (let serverBundleId of serverBundleIds) {
1817
- const environmentName = `${SSR_BUNDLE_PREFIX}${serverBundleId}`;
1818
- environmentOptionsResolvers[environmentName] = ({ viteUserConfig }) => mergeEnvironmentOptions(
1819
- getBaseServerOptions({ viteUserConfig }),
1820
- {
1821
- build: {
1822
- outDir: getServerBuildDirectory(ctx.reactRouterConfig, {
1823
- serverBundleId
1824
- })
1825
- }
1826
- },
1827
- // Ensure server bundle environments extend the user's SSR
1828
- // environment config if it exists
1829
- viteUserConfig.environments?.ssr ?? {}
1830
- );
1831
- }
1832
- } else {
1833
- environmentOptionsResolvers.ssr = ({ viteUserConfig }) => mergeEnvironmentOptions(getBaseServerOptions({ viteUserConfig }), {
1834
- build: {
1835
- outDir: getServerBuildDirectory(ctx.reactRouterConfig)
1836
- }
1837
- });
1838
- }
1839
- return environmentOptionsResolvers;
1840
- }
1841
- function resolveEnvironmentsOptions(environmentResolvers, resolverOptions) {
1842
- let environmentOptions = {};
1843
- for (let [environmentName, resolver] of Object.entries(
1844
- environmentResolvers
1845
- )) {
1846
- environmentOptions[environmentName] = resolver(resolverOptions);
1847
- }
1848
- return environmentOptions;
1849
- }
1850
- function isNonNullable(x) {
1851
- return x != null;
1852
- }
1853
- var import_node_crypto, import_node_fs3, import_promises3, path8, url, babel2, import_react_router2, import_es_module_lexer, import_pick3, import_jsesc, import_picocolors5, import_kebabCase, CLIENT_NON_COMPONENT_EXPORTS, CLIENT_ROUTE_EXPORTS, BUILD_CLIENT_ROUTE_QUERY_STRING, SSR_BUNDLE_PREFIX, virtualHmrRuntime, virtualInjectHmrRuntime, virtual, getServerBuildDirectory, getClientBuildDirectory, defaultEntriesDir, defaultEntries, REACT_REFRESH_HEADER;
1854
- var init_plugin = __esm({
1855
- "vite/plugin.ts"() {
1856
- "use strict";
1857
- import_node_crypto = require("crypto");
1858
- import_node_fs3 = require("fs");
1859
- import_promises3 = require("fs/promises");
1860
- path8 = __toESM(require("path"));
1861
- url = __toESM(require("url"));
1862
- babel2 = __toESM(require("@babel/core"));
1863
- import_react_router2 = require("react-router");
1864
- import_es_module_lexer = require("es-module-lexer");
1865
- import_pick3 = __toESM(require("lodash/pick"));
1866
- import_jsesc = __toESM(require("jsesc"));
1867
- import_picocolors5 = __toESM(require("picocolors"));
1868
- import_kebabCase = __toESM(require("lodash/kebabCase"));
1869
- init_typegen();
1870
- init_invariant();
1871
- init_babel();
1872
- init_node_adapter();
1873
- init_styles();
1874
- init_virtual_module();
1875
- init_resolve_file_url();
1876
- init_resolve_relative_route_file_path();
1877
- init_combine_urls();
1878
- init_remove_exports();
1879
- init_ssr_externals();
1880
- init_has_dependency();
1881
- init_route_chunks();
1882
- init_vite();
1883
- init_config();
1884
- init_optimize_deps_entries();
1885
- init_with_props();
1886
- init_load_dotenv();
1887
- init_validate_plugin_order();
1888
- init_warn_on_client_source_maps();
1889
- init_prerender();
1890
- CLIENT_NON_COMPONENT_EXPORTS = [
1891
- "clientAction",
1892
- "clientLoader",
1893
- "clientMiddleware",
1894
- "handle",
1895
- "meta",
1896
- "links",
1897
- "shouldRevalidate"
1898
- ];
1899
- CLIENT_ROUTE_EXPORTS = [
1900
- ...CLIENT_NON_COMPONENT_EXPORTS,
1901
- "default",
1902
- "ErrorBoundary",
1903
- "HydrateFallback",
1904
- "Layout"
1905
- ];
1906
- BUILD_CLIENT_ROUTE_QUERY_STRING = "?__react-router-build-client-route";
1907
- SSR_BUNDLE_PREFIX = "ssrBundle_";
1908
- virtualHmrRuntime = create("hmr-runtime");
1909
- virtualInjectHmrRuntime = create("inject-hmr-runtime");
1910
- virtual = {
1911
- serverBuild: create("server-build"),
1912
- serverManifest: create("server-manifest"),
1913
- browserManifest: create("browser-manifest")
1914
- };
1915
- getServerBuildDirectory = (reactRouterConfig, { serverBundleId } = {}) => path8.join(
1916
- reactRouterConfig.buildDirectory,
1917
- "server",
1918
- ...serverBundleId ? [serverBundleId] : []
1919
- );
1920
- getClientBuildDirectory = (reactRouterConfig) => path8.join(reactRouterConfig.buildDirectory, "client");
1921
- defaultEntriesDir = path8.resolve(
1922
- path8.dirname(require.resolve("@react-router/dev/package.json")),
1923
- "dist",
1924
- "config",
1925
- "defaults"
1926
- );
1927
- defaultEntries = (0, import_node_fs3.readdirSync)(defaultEntriesDir).map(
1928
- (filename2) => path8.join(defaultEntriesDir, filename2)
1929
- );
1930
- invariant(defaultEntries.length > 0, "No default entries found");
1931
- REACT_REFRESH_HEADER = `
1932
- import RefreshRuntime from "${virtualHmrRuntime.id}";
1933
-
1934
- const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
1935
- let prevRefreshReg;
1936
- let prevRefreshSig;
1937
-
1938
- if (import.meta.hot && !inWebWorker) {
1939
- if (!window.__vite_plugin_react_preamble_installed__) {
1940
- throw new Error(
1941
- "React Router Vite plugin can't detect preamble. Something is wrong."
1942
- );
1943
- }
1944
-
1945
- prevRefreshReg = window.$RefreshReg$;
1946
- prevRefreshSig = window.$RefreshSig$;
1947
- window.$RefreshReg$ = (type, id) => {
1948
- RefreshRuntime.register(type, __SOURCE__ + " " + id)
1949
- };
1950
- window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
1951
- }`.replaceAll("\n", "");
1952
- }
1953
- });
1954
-
1955
- // vite/build.ts
1956
- var build_exports = {};
1957
- __export(build_exports, {
1958
- build: () => build
1959
- });
1960
- async function build(root, viteBuildOptions) {
1961
- await preloadVite();
1962
- let vite2 = getVite();
1963
- let configResult = await loadConfig({
1964
- rootDirectory: root,
1965
- mode: viteBuildOptions.mode ?? "production",
1966
- // In this scope we only need future flags, so we can skip evaluating
1967
- // routes.ts until we're within the Vite build context
1968
- skipRoutes: true
1969
- });
1970
- if (!configResult.ok) {
1971
- throw new Error(configResult.error);
1972
- }
1973
- let config = configResult.value;
1974
- let viteMajor = parseInt(vite2.version.split(".")[0], 10);
1975
- if (config.future.v8_viteEnvironmentApi && viteMajor === 5) {
1976
- throw new Error(
1977
- "The future.v8_viteEnvironmentApi option is not supported in Vite 5"
1978
- );
1979
- }
1980
- const useViteEnvironmentApi = config.future.v8_viteEnvironmentApi || await hasReactRouterRscPlugin({ root, viteBuildOptions });
1981
- return await (useViteEnvironmentApi ? viteAppBuild(root, viteBuildOptions) : viteBuild(root, viteBuildOptions));
1982
- }
1983
- async function viteAppBuild(root, {
1984
- assetsInlineLimit,
1985
- clearScreen,
1986
- config: configFile,
1987
- emptyOutDir,
1988
- force,
1989
- logLevel,
1990
- minify,
1991
- mode,
1992
- sourcemapClient,
1993
- sourcemapServer
1994
- }) {
1995
- let vite2 = getVite();
1996
- let builder = await vite2.createBuilder({
1997
- root,
1998
- mode,
1999
- configFile,
2000
- build: {
2001
- assetsInlineLimit,
2002
- emptyOutDir,
2003
- minify
2004
- },
2005
- optimizeDeps: { force },
2006
- clearScreen,
2007
- logLevel,
2008
- plugins: [
2009
- {
2010
- name: "react-router:cli-config",
2011
- configEnvironment(name) {
2012
- if (sourcemapClient && name === "client") {
2013
- return {
2014
- build: {
2015
- sourcemap: sourcemapClient
2016
- }
2017
- };
2018
- }
2019
- if (sourcemapServer && name !== "client") {
2020
- return {
2021
- build: {
2022
- sourcemap: sourcemapServer
2023
- }
2024
- };
2025
- }
2026
- },
2027
- configResolved(config) {
2028
- let hasReactRouterPlugin = config.plugins.find(
2029
- (plugin) => plugin.name === "react-router" || plugin.name === "react-router/rsc"
2030
- );
2031
- if (!hasReactRouterPlugin) {
2032
- throw new Error(
2033
- "React Router Vite plugin not found in Vite config"
2034
- );
2035
- }
2036
- }
2037
- }
2038
- ]
2039
- });
2040
- await builder.buildApp();
2041
- }
2042
- async function viteBuild(root, {
2043
- assetsInlineLimit,
2044
- clearScreen,
2045
- config: configFile,
2046
- emptyOutDir,
2047
- force,
2048
- logLevel,
2049
- minify,
2050
- mode,
2051
- sourcemapClient,
2052
- sourcemapServer
2053
- }) {
2054
- let viteUserConfig = {};
2055
- let viteConfig = await resolveViteConfig({
2056
- configFile,
2057
- mode,
2058
- root,
2059
- plugins: [
2060
- {
2061
- name: "react-router:extract-vite-user-config",
2062
- config(config) {
2063
- viteUserConfig = config;
2064
- }
2065
- }
2066
- ]
2067
- });
2068
- let ctx = extractPluginContext(viteConfig);
2069
- if (!ctx) {
2070
- console.error(
2071
- import_picocolors6.default.red("React Router Vite plugin not found in Vite config")
2072
- );
2073
- process.exit(1);
2074
- }
2075
- async function buildEnvironment(environmentName) {
2076
- let vite2 = getVite();
2077
- let ssr = environmentName !== "client";
2078
- let resolveOptions = environmentOptionsResolvers[environmentName];
2079
- invariant(resolveOptions);
2080
- let environmentBuildContext = {
2081
- name: environmentName,
2082
- resolveOptions
2083
- };
2084
- await vite2.build({
2085
- root,
2086
- mode,
2087
- configFile,
2088
- build: {
2089
- assetsInlineLimit,
2090
- emptyOutDir,
2091
- minify,
2092
- ssr,
2093
- sourcemap: ssr ? sourcemapServer : sourcemapClient
2094
- },
2095
- optimizeDeps: { force },
2096
- clearScreen,
2097
- logLevel,
2098
- ...{
2099
- __reactRouterPluginContext: ctx,
2100
- __reactRouterEnvironmentBuildContext: environmentBuildContext
2101
- }
2102
- });
2103
- }
2104
- let { reactRouterConfig, buildManifest } = ctx;
2105
- invariant(buildManifest, "Expected build manifest to be present");
2106
- let environmentOptionsResolvers = await getEnvironmentOptionsResolvers(
2107
- ctx,
2108
- "build"
2109
- );
2110
- let environmentsOptions = resolveEnvironmentsOptions(
2111
- environmentOptionsResolvers,
2112
- { viteUserConfig }
2113
- );
2114
- await cleanBuildDirectory(viteConfig, ctx);
2115
- await buildEnvironment("client");
2116
- let serverEnvironmentNames = getServerEnvironmentKeys(
2117
- ctx,
2118
- environmentOptionsResolvers
2119
- );
2120
- await Promise.all(serverEnvironmentNames.map(buildEnvironment));
2121
- await cleanViteManifests(environmentsOptions, ctx);
2122
- await reactRouterConfig.buildEnd?.({
2123
- buildManifest,
2124
- reactRouterConfig,
2125
- viteConfig
2126
- });
2127
- }
2128
- var import_picocolors6;
2129
- var init_build = __esm({
2130
- "vite/build.ts"() {
2131
- "use strict";
2132
- import_picocolors6 = __toESM(require("picocolors"));
2133
- init_config();
2134
- init_plugin();
2135
- init_invariant();
2136
- init_vite();
2137
- init_has_rsc_plugin();
2138
- }
2139
- });
2140
-
2141
- // vite/dev.ts
2142
- var dev_exports = {};
2143
- __export(dev_exports, {
2144
- dev: () => dev
2145
- });
2146
- async function dev(root, {
2147
- clearScreen,
2148
- config: configFile,
2149
- cors,
2150
- force,
2151
- host,
2152
- logLevel,
2153
- mode,
2154
- open,
2155
- port,
2156
- strictPort
2157
- }) {
2158
- await preloadVite();
2159
- let vite2 = getVite();
2160
- let server = await vite2.createServer({
2161
- root,
2162
- mode,
2163
- configFile,
2164
- server: { open, cors, host, port, strictPort },
2165
- optimizeDeps: { force },
2166
- clearScreen,
2167
- logLevel
2168
- });
2169
- if (!server.config.plugins.find(
2170
- (plugin) => plugin.name === "react-router" || plugin.name === "react-router/rsc"
2171
- )) {
2172
- console.error(
2173
- import_picocolors7.default.red("React Router Vite plugin not found in Vite config")
2174
- );
2175
- process.exit(1);
2176
- }
2177
- await server.listen();
2178
- server.printUrls();
2179
- let customShortcuts = [
2180
- {
2181
- key: "p",
2182
- description: "start/stop the profiler",
2183
- async action(server2) {
2184
- if (getSession()) {
2185
- await stop(server2.config.logger.info);
2186
- } else {
2187
- await start(() => {
2188
- server2.config.logger.info("Profiler started");
2189
- });
2190
- }
2191
- }
2192
- }
2193
- ];
2194
- server.bindCLIShortcuts({ print: true, customShortcuts });
2195
- }
2196
- var import_picocolors7;
2197
- var init_dev = __esm({
2198
- "vite/dev.ts"() {
2199
- "use strict";
2200
- import_picocolors7 = __toESM(require("picocolors"));
2201
- init_vite();
2202
- init_profiler();
2203
- }
2204
- });
2205
-
2206
- // cli/run.ts
2207
- var import_arg = __toESM(require("arg"));
2208
- var import_semver = __toESM(require("semver"));
2209
- var import_picocolors9 = __toESM(require("picocolors"));
2210
-
2211
- // cli/commands.ts
2212
- var import_node_fs4 = require("fs");
2213
- var import_promises4 = require("fs/promises");
2214
- var path9 = __toESM(require("path"));
2215
- var import_exit_hook = __toESM(require("exit-hook"));
2216
- var import_picocolors8 = __toESM(require("picocolors"));
2217
- var import_react_router3 = require("react-router");
2218
- init_config();
2219
-
2220
- // config/format.ts
12
+ import { g as preloadVite, h as getVite, l as loadConfig, n as watch, t as run$1 } from "../typegen-BLMwBSoM.js";
13
+ import { createRequire } from "node:module";
14
+ import fs, { existsSync } from "node:fs";
15
+ import * as path$1 from "node:path";
16
+ import path from "node:path";
17
+ import arg from "arg";
18
+ import semver from "semver";
19
+ import colors from "picocolors";
20
+ import { copyFile, readFile, writeFile } from "node:fs/promises";
21
+ import exitHook from "exit-hook";
22
+ import { readPackageJSON } from "pkg-types";
23
+ import "react-router";
24
+ import * as babel from "@babel/core";
25
+ import babelPluginSyntaxJSX from "@babel/plugin-syntax-jsx";
26
+ import babelPresetTypeScript from "@babel/preset-typescript";
27
+ import prettier from "prettier";
28
+ import packageJson from "@react-router/dev/package.json" with { type: "json" };
29
+ //#region config/format.ts
2221
30
  function formatRoutes(routeManifest, format) {
2222
- switch (format) {
2223
- case "json":
2224
- return formatRoutesAsJson(routeManifest);
2225
- case "jsx":
2226
- return formatRoutesAsJsx(routeManifest);
2227
- }
31
+ switch (format) {
32
+ case "json": return formatRoutesAsJson(routeManifest);
33
+ case "jsx": return formatRoutesAsJsx(routeManifest);
34
+ }
2228
35
  }
2229
36
  function formatRoutesAsJson(routeManifest) {
2230
- function handleRoutesRecursive(parentId) {
2231
- let routes2 = Object.values(routeManifest).filter(
2232
- (route) => route.parentId === parentId
2233
- );
2234
- let children = [];
2235
- for (let route of routes2) {
2236
- children.push({
2237
- id: route.id,
2238
- index: route.index,
2239
- path: route.path,
2240
- caseSensitive: route.caseSensitive,
2241
- file: route.file,
2242
- children: handleRoutesRecursive(route.id)
2243
- });
2244
- }
2245
- if (children.length > 0) {
2246
- return children;
2247
- }
2248
- return void 0;
2249
- }
2250
- return JSON.stringify(handleRoutesRecursive() || null, null, 2);
37
+ function handleRoutesRecursive(parentId) {
38
+ let routes = Object.values(routeManifest).filter((route) => route.parentId === parentId);
39
+ let children = [];
40
+ for (let route of routes) children.push({
41
+ id: route.id,
42
+ index: route.index,
43
+ path: route.path,
44
+ caseSensitive: route.caseSensitive,
45
+ file: route.file,
46
+ children: handleRoutesRecursive(route.id)
47
+ });
48
+ if (children.length > 0) return children;
49
+ }
50
+ return JSON.stringify(handleRoutesRecursive() || null, null, 2);
2251
51
  }
2252
52
  function formatRoutesAsJsx(routeManifest) {
2253
- let output = "<Routes>";
2254
- function handleRoutesRecursive(parentId, level = 1) {
2255
- let routes2 = Object.values(routeManifest).filter(
2256
- (route) => route.parentId === parentId
2257
- );
2258
- let indent = Array(level * 2).fill(" ").join("");
2259
- for (let route of routes2) {
2260
- output += "\n" + indent;
2261
- output += `<Route${route.path ? ` path=${JSON.stringify(route.path)}` : ""}${route.index ? " index" : ""}${route.file ? ` file=${JSON.stringify(route.file)}` : ""}>`;
2262
- if (handleRoutesRecursive(route.id, level + 1)) {
2263
- output += "\n" + indent;
2264
- output += "</Route>";
2265
- } else {
2266
- output = output.slice(0, -1) + " />";
2267
- }
2268
- }
2269
- return routes2.length > 0;
2270
- }
2271
- handleRoutesRecursive();
2272
- output += "\n</Routes>";
2273
- return output;
2274
- }
2275
-
2276
- // cli/useJavascript.ts
2277
- var babel = __toESM(require("@babel/core"));
2278
- var import_plugin_syntax_jsx = __toESM(require("@babel/plugin-syntax-jsx"));
2279
- var import_preset_typescript = __toESM(require("@babel/preset-typescript"));
2280
- var import_prettier = __toESM(require("prettier"));
53
+ let output = "<Routes>";
54
+ function handleRoutesRecursive(parentId, level = 1) {
55
+ let routes = Object.values(routeManifest).filter((route) => route.parentId === parentId);
56
+ let indent = Array(level * 2).fill(" ").join("");
57
+ for (let route of routes) {
58
+ output += "\n" + indent;
59
+ output += `<Route${route.path ? ` path=${JSON.stringify(route.path)}` : ""}${route.index ? " index" : ""}${route.file ? ` file=${JSON.stringify(route.file)}` : ""}>`;
60
+ if (handleRoutesRecursive(route.id, level + 1)) {
61
+ output += "\n" + indent;
62
+ output += "</Route>";
63
+ } else output = output.slice(0, -1) + " />";
64
+ }
65
+ return routes.length > 0;
66
+ }
67
+ handleRoutesRecursive();
68
+ output += "\n</Routes>";
69
+ return output;
70
+ }
71
+ //#endregion
72
+ //#region cli/useJavascript.ts
2281
73
  async function transpile(tsx, options = {}) {
2282
- let mjs = babel.transformSync(tsx, {
2283
- compact: false,
2284
- cwd: options.cwd,
2285
- filename: options.filename,
2286
- plugins: [import_plugin_syntax_jsx.default],
2287
- presets: [[import_preset_typescript.default, { jsx: "preserve" }]],
2288
- retainLines: true
2289
- });
2290
- if (!mjs || !mjs.code) throw new Error("Could not parse TypeScript");
2291
- return await import_prettier.default.format(mjs.code, { parser: "babel" });
2292
- }
2293
-
2294
- // cli/commands.ts
2295
- init_profiler();
2296
- init_typegen();
2297
- init_vite();
2298
- init_has_rsc_plugin();
74
+ let mjs = babel.transformSync(tsx, {
75
+ compact: false,
76
+ cwd: options.cwd,
77
+ filename: options.filename,
78
+ plugins: [babelPluginSyntaxJSX],
79
+ presets: [[babelPresetTypeScript, { jsx: "preserve" }]],
80
+ retainLines: true
81
+ });
82
+ if (!mjs || !mjs.code) throw new Error("Could not parse TypeScript");
83
+ /**
84
+ * Babel's `compact` and `retainLines` options are both bad at formatting code.
85
+ * Use Prettier for nicer formatting.
86
+ */
87
+ return await prettier.format(mjs.code, { parser: "babel" });
88
+ }
89
+ //#endregion
90
+ //#region vite/profiler.ts
91
+ const getSession = () => global.__reactRouter_profile_session;
92
+ const start = async (callback) => {
93
+ let inspector = await import("node:inspector").then((r) => r.default);
94
+ let session = global.__reactRouter_profile_session = new inspector.Session();
95
+ session.connect();
96
+ session.post("Profiler.enable", () => {
97
+ session.post("Profiler.start", callback);
98
+ });
99
+ };
100
+ let profileCount = 0;
101
+ const stop = (log) => {
102
+ let session = getSession();
103
+ if (!session) return;
104
+ return new Promise((res, rej) => {
105
+ session.post("Profiler.stop", (err, { profile }) => {
106
+ if (err) return rej(err);
107
+ let outPath = path.resolve(`./react-router-${profileCount++}.cpuprofile`);
108
+ fs.writeFileSync(outPath, JSON.stringify(profile));
109
+ log(colors.yellow(`CPU profile written to ${colors.white(colors.dim(outPath))}`));
110
+ global.__reactRouter_profile_session = void 0;
111
+ res();
112
+ });
113
+ });
114
+ };
115
+ //#endregion
116
+ //#region vite/has-rsc-plugin.ts
117
+ async function hasReactRouterRscPlugin({ root, viteBuildOptions: { config, logLevel, mode } }) {
118
+ await preloadVite();
119
+ return (await getVite().resolveConfig({
120
+ configFile: config,
121
+ logLevel,
122
+ mode: mode ?? "production",
123
+ root
124
+ }, "build", "production", "production")).plugins.some((plugin) => plugin?.name === "react-router/rsc");
125
+ }
126
+ //#endregion
127
+ //#region cli/commands.ts
128
+ const nodeRequire = createRequire(import.meta.url);
2299
129
  async function routes(rootDirectory, flags = {}) {
2300
- rootDirectory = resolveRootDirectory(rootDirectory, flags);
2301
- let configResult = await loadConfig({
2302
- rootDirectory,
2303
- mode: flags.mode ?? "production"
2304
- });
2305
- if (!configResult.ok) {
2306
- console.error(import_picocolors8.default.red(configResult.error));
2307
- process.exit(1);
2308
- }
2309
- let format = flags.json ? "json" : "jsx";
2310
- console.log(formatRoutes(configResult.value.routes, format));
2311
- }
2312
- async function build2(root, options = {}) {
2313
- root = resolveRootDirectory(root, options);
2314
- let { build: build3 } = await Promise.resolve().then(() => (init_build(), build_exports));
2315
- if (options.profile) {
2316
- await start();
2317
- }
2318
- try {
2319
- await build3(root, options);
2320
- } finally {
2321
- await stop(console.info);
2322
- }
2323
- }
2324
- async function dev2(root, options = {}) {
2325
- let { dev: dev3 } = await Promise.resolve().then(() => (init_dev(), dev_exports));
2326
- if (options.profile) {
2327
- await start();
2328
- }
2329
- (0, import_exit_hook.default)(() => stop(console.info));
2330
- root = resolveRootDirectory(root, options);
2331
- await dev3(root, options);
2332
- await new Promise(() => {
2333
- });
2334
- }
2335
- var clientEntries = ["entry.client.tsx", "entry.client.js", "entry.client.jsx"];
2336
- var serverEntries = ["entry.server.tsx", "entry.server.js", "entry.server.jsx"];
2337
- var entries = ["entry.client", "entry.server"];
2338
- var rscEntries = ["entry.client", "entry.rsc", "entry.ssr"];
2339
- var conjunctionListFormat = new Intl.ListFormat("en", {
2340
- style: "long",
2341
- type: "conjunction"
130
+ rootDirectory = resolveRootDirectory(rootDirectory, flags);
131
+ let configResult = await loadConfig({
132
+ rootDirectory,
133
+ mode: flags.mode ?? "production"
134
+ });
135
+ if (!configResult.ok) {
136
+ console.error(colors.red(configResult.error));
137
+ process.exit(1);
138
+ }
139
+ let format = flags.json ? "json" : "jsx";
140
+ console.log(formatRoutes(configResult.value.routes, format));
141
+ }
142
+ async function build(root, options = {}) {
143
+ root = resolveRootDirectory(root, options);
144
+ let { build } = await import("../build-DM91F_L-.js");
145
+ if (options.profile) await start();
146
+ try {
147
+ await build(root, options);
148
+ } finally {
149
+ await stop(console.info);
150
+ }
151
+ }
152
+ async function dev(root, options = {}) {
153
+ let { dev } = await import("../dev-CNEgIjT-.js");
154
+ if (options.profile) await start();
155
+ exitHook(() => stop(console.info));
156
+ root = resolveRootDirectory(root, options);
157
+ await dev(root, options);
158
+ await new Promise(() => {});
159
+ }
160
+ let clientEntries = [
161
+ "entry.client.tsx",
162
+ "entry.client.js",
163
+ "entry.client.jsx"
164
+ ];
165
+ let serverEntries = [
166
+ "entry.server.tsx",
167
+ "entry.server.js",
168
+ "entry.server.jsx"
169
+ ];
170
+ let entries = ["entry.client", "entry.server"];
171
+ let rscEntries = [
172
+ "entry.client",
173
+ "entry.rsc",
174
+ "entry.ssr"
175
+ ];
176
+ let conjunctionListFormat = new Intl.ListFormat("en", {
177
+ style: "long",
178
+ type: "conjunction"
2342
179
  });
2343
180
  async function generateEntry(entry, rootDirectory, flags = {}) {
2344
- rootDirectory = resolveRootDirectory(rootDirectory, flags);
2345
- let configDir = "defaults";
2346
- let entriesToUse = entries;
2347
- let isRsc = false;
2348
- if (await hasReactRouterRscPlugin({
2349
- root: rootDirectory,
2350
- viteBuildOptions: {
2351
- config: flags.config,
2352
- mode: flags.mode
2353
- }
2354
- })) {
2355
- if (!entry) {
2356
- await generateEntry("entry.client", rootDirectory, flags);
2357
- await generateEntry("entry.rsc", rootDirectory, flags);
2358
- await generateEntry("entry.ssr", rootDirectory, flags);
2359
- return;
2360
- }
2361
- configDir = "default-rsc-entries";
2362
- entriesToUse = rscEntries;
2363
- isRsc = true;
2364
- }
2365
- if (!entry) {
2366
- await generateEntry("entry.client", rootDirectory, flags);
2367
- await generateEntry("entry.server", rootDirectory, flags);
2368
- return;
2369
- }
2370
- let configResult = await loadConfig({
2371
- rootDirectory,
2372
- mode: flags.mode ?? "production"
2373
- });
2374
- if (!configResult.ok) {
2375
- console.error(import_picocolors8.default.red(configResult.error));
2376
- return;
2377
- }
2378
- let appDirectory = configResult.value.appDirectory;
2379
- if (!entriesToUse.includes(entry)) {
2380
- let entriesArray = Array.from(entriesToUse);
2381
- let list = conjunctionListFormat.format(entriesArray);
2382
- console.error(
2383
- import_picocolors8.default.red(`Invalid entry file. Valid entry files are ${list}`)
2384
- );
2385
- return;
2386
- }
2387
- let defaultsDirectory = path9.resolve(
2388
- path9.dirname(require.resolve("@react-router/dev/package.json")),
2389
- "dist",
2390
- "config",
2391
- configDir
2392
- );
2393
- let outputFile;
2394
- if (isRsc) {
2395
- let defaultEntry = path9.resolve(defaultsDirectory, `${entry}.tsx`);
2396
- outputFile = path9.resolve(appDirectory, `${entry}.tsx`);
2397
- if ((0, import_node_fs4.existsSync)(outputFile)) {
2398
- let relative7 = path9.relative(rootDirectory, outputFile);
2399
- console.error(import_picocolors8.default.red(`Entry file ${relative7} already exists.`));
2400
- return;
2401
- }
2402
- await (0, import_promises4.copyFile)(defaultEntry, outputFile);
2403
- } else {
2404
- let { readPackageJSON } = await import("pkg-types");
2405
- let pkgJson = await readPackageJSON(rootDirectory);
2406
- let deps = pkgJson.dependencies ?? {};
2407
- if (!deps["@react-router/node"]) {
2408
- console.error(import_picocolors8.default.red(`No default server entry detected.`));
2409
- return;
2410
- }
2411
- let defaultEntryClient = path9.resolve(
2412
- defaultsDirectory,
2413
- "entry.client.tsx"
2414
- );
2415
- let defaultEntryServer = path9.resolve(
2416
- defaultsDirectory,
2417
- `entry.server.node.tsx`
2418
- );
2419
- let isServerEntry = entry === "entry.server";
2420
- let contents = isServerEntry ? await createServerEntry(rootDirectory, appDirectory, defaultEntryServer) : await createClientEntry(
2421
- rootDirectory,
2422
- appDirectory,
2423
- defaultEntryClient
2424
- );
2425
- let useTypeScript = flags.typescript ?? true;
2426
- let outputExtension = useTypeScript ? "tsx" : "jsx";
2427
- let outputEntry = `${entry}.${outputExtension}`;
2428
- outputFile = path9.resolve(appDirectory, outputEntry);
2429
- if (!useTypeScript) {
2430
- let javascript = await transpile(contents, {
2431
- cwd: rootDirectory,
2432
- filename: isServerEntry ? defaultEntryServer : defaultEntryClient
2433
- });
2434
- await (0, import_promises4.writeFile)(outputFile, javascript, "utf-8");
2435
- } else {
2436
- await (0, import_promises4.writeFile)(outputFile, contents, "utf-8");
2437
- }
2438
- }
2439
- console.log(
2440
- import_picocolors8.default.blue(
2441
- `Entry file ${entry} created at ${path9.relative(
2442
- rootDirectory,
2443
- outputFile
2444
- )}.`
2445
- )
2446
- );
181
+ rootDirectory = resolveRootDirectory(rootDirectory, flags);
182
+ let configDir = "defaults";
183
+ let entriesToUse = entries;
184
+ let isRsc = false;
185
+ if (await hasReactRouterRscPlugin({
186
+ root: rootDirectory,
187
+ viteBuildOptions: {
188
+ config: flags.config,
189
+ mode: flags.mode
190
+ }
191
+ })) {
192
+ if (!entry) {
193
+ await generateEntry("entry.client", rootDirectory, flags);
194
+ await generateEntry("entry.rsc", rootDirectory, flags);
195
+ await generateEntry("entry.ssr", rootDirectory, flags);
196
+ return;
197
+ }
198
+ configDir = "default-rsc-entries";
199
+ entriesToUse = rscEntries;
200
+ isRsc = true;
201
+ }
202
+ if (!entry) {
203
+ await generateEntry("entry.client", rootDirectory, flags);
204
+ await generateEntry("entry.server", rootDirectory, flags);
205
+ return;
206
+ }
207
+ let configResult = await loadConfig({
208
+ rootDirectory,
209
+ mode: flags.mode ?? "production"
210
+ });
211
+ if (!configResult.ok) {
212
+ console.error(colors.red(configResult.error));
213
+ return;
214
+ }
215
+ let appDirectory = configResult.value.appDirectory;
216
+ if (!entriesToUse.includes(entry)) {
217
+ let entriesArray = Array.from(entriesToUse);
218
+ let list = conjunctionListFormat.format(entriesArray);
219
+ console.error(colors.red(`Invalid entry file. Valid entry files are ${list}`));
220
+ return;
221
+ }
222
+ let defaultsDirectory = path$1.resolve(path$1.dirname(nodeRequire.resolve("@react-router/dev/package.json")), "dist", "config", configDir);
223
+ let outputFile;
224
+ if (isRsc) {
225
+ let defaultEntry = path$1.resolve(defaultsDirectory, `${entry}.tsx`);
226
+ outputFile = path$1.resolve(appDirectory, `${entry}.tsx`);
227
+ if (existsSync(outputFile)) {
228
+ let relative = path$1.relative(rootDirectory, outputFile);
229
+ console.error(colors.red(`Entry file ${relative} already exists.`));
230
+ return;
231
+ }
232
+ await copyFile(defaultEntry, outputFile);
233
+ } else {
234
+ if (!((await readPackageJSON(rootDirectory)).dependencies ?? {})["@react-router/node"]) {
235
+ console.error(colors.red(`No default server entry detected.`));
236
+ return;
237
+ }
238
+ let defaultEntryClient = path$1.resolve(defaultsDirectory, "entry.client.tsx");
239
+ let defaultEntryServer = path$1.resolve(defaultsDirectory, `entry.server.node.tsx`);
240
+ let isServerEntry = entry === "entry.server";
241
+ let contents = isServerEntry ? await createServerEntry(rootDirectory, appDirectory, defaultEntryServer) : await createClientEntry(rootDirectory, appDirectory, defaultEntryClient);
242
+ let useTypeScript = flags.typescript ?? true;
243
+ let outputEntry = `${entry}.${useTypeScript ? "tsx" : "jsx"}`;
244
+ outputFile = path$1.resolve(appDirectory, outputEntry);
245
+ if (!useTypeScript) {
246
+ let javascript = await transpile(contents, {
247
+ cwd: rootDirectory,
248
+ filename: isServerEntry ? defaultEntryServer : defaultEntryClient
249
+ });
250
+ await writeFile(outputFile, javascript, "utf-8");
251
+ } else await writeFile(outputFile, contents, "utf-8");
252
+ }
253
+ console.log(colors.blue(`Entry file ${entry} created at ${path$1.relative(rootDirectory, outputFile)}.`));
2447
254
  }
2448
255
  function resolveRootDirectory(root, flags) {
2449
- if (root) {
2450
- return path9.resolve(root);
2451
- }
2452
- return process.env.REACT_ROUTER_ROOT || (flags?.config ? path9.dirname(path9.resolve(flags.config)) : process.cwd());
2453
- }
2454
- async function checkForEntry(rootDirectory, appDirectory, entries2) {
2455
- for (let entry of entries2) {
2456
- let entryPath = path9.resolve(appDirectory, entry);
2457
- let exists = (0, import_node_fs4.existsSync)(entryPath);
2458
- if (exists) {
2459
- let relative7 = path9.relative(rootDirectory, entryPath);
2460
- console.error(import_picocolors8.default.red(`Entry file ${relative7} already exists.`));
2461
- return process.exit(1);
2462
- }
2463
- }
256
+ if (root) return path$1.resolve(root);
257
+ return process.env.REACT_ROUTER_ROOT || (flags?.config ? path$1.dirname(path$1.resolve(flags.config)) : process.cwd());
258
+ }
259
+ async function checkForEntry(rootDirectory, appDirectory, entries) {
260
+ for (let entry of entries) {
261
+ let entryPath = path$1.resolve(appDirectory, entry);
262
+ if (existsSync(entryPath)) {
263
+ let relative = path$1.relative(rootDirectory, entryPath);
264
+ console.error(colors.red(`Entry file ${relative} already exists.`));
265
+ return process.exit(1);
266
+ }
267
+ }
2464
268
  }
2465
269
  async function createServerEntry(rootDirectory, appDirectory, inputFile) {
2466
- await checkForEntry(rootDirectory, appDirectory, serverEntries);
2467
- let contents = await (0, import_promises4.readFile)(inputFile, "utf-8");
2468
- return contents;
270
+ await checkForEntry(rootDirectory, appDirectory, serverEntries);
271
+ return await readFile(inputFile, "utf-8");
2469
272
  }
2470
273
  async function createClientEntry(rootDirectory, appDirectory, inputFile) {
2471
- await checkForEntry(rootDirectory, appDirectory, clientEntries);
2472
- let contents = await (0, import_promises4.readFile)(inputFile, "utf-8");
2473
- return contents;
274
+ await checkForEntry(rootDirectory, appDirectory, clientEntries);
275
+ return await readFile(inputFile, "utf-8");
2474
276
  }
2475
277
  async function typegen(root, flags) {
2476
- root = resolveRootDirectory(root, flags);
2477
- const rsc = await hasReactRouterRscPlugin({
2478
- root,
2479
- viteBuildOptions: {
2480
- config: flags.config,
2481
- mode: flags.mode
2482
- }
2483
- });
2484
- if (flags.watch) {
2485
- await preloadVite();
2486
- const vite2 = getVite();
2487
- const logger = vite2.createLogger("info", { prefix: "[react-router]" });
2488
- await watch(root, {
2489
- mode: flags.mode ?? "development",
2490
- rsc,
2491
- logger
2492
- });
2493
- await new Promise(() => {
2494
- });
2495
- return;
2496
- }
2497
- await run(root, {
2498
- mode: flags.mode ?? "production",
2499
- rsc
2500
- });
2501
- }
2502
-
2503
- // cli/run.ts
2504
- var helpText = `
2505
- ${import_picocolors9.default.blueBright("react-router")}
2506
-
2507
- ${import_picocolors9.default.underline("Usage")}:
2508
- $ react-router build [${import_picocolors9.default.yellowBright("projectDir")}]
2509
- $ react-router dev [${import_picocolors9.default.yellowBright("projectDir")}]
2510
- $ react-router routes [${import_picocolors9.default.yellowBright("projectDir")}]
2511
-
2512
- ${import_picocolors9.default.underline("Options")}:
278
+ root = resolveRootDirectory(root, flags);
279
+ const rsc = await hasReactRouterRscPlugin({
280
+ root,
281
+ viteBuildOptions: {
282
+ config: flags.config,
283
+ mode: flags.mode
284
+ }
285
+ });
286
+ if (flags.watch) {
287
+ await preloadVite();
288
+ const logger = getVite().createLogger("info", { prefix: "[react-router]" });
289
+ await watch(root, {
290
+ mode: flags.mode ?? "development",
291
+ rsc,
292
+ logger
293
+ });
294
+ await new Promise(() => {});
295
+ return;
296
+ }
297
+ await run$1(root, {
298
+ mode: flags.mode ?? "production",
299
+ rsc
300
+ });
301
+ }
302
+ //#endregion
303
+ //#region cli/run.ts
304
+ const helpText = `
305
+ ${colors.blueBright("react-router")}
306
+
307
+ ${colors.underline("Usage")}:
308
+ $ react-router build [${colors.yellowBright("projectDir")}]
309
+ $ react-router dev [${colors.yellowBright("projectDir")}]
310
+ $ react-router routes [${colors.yellowBright("projectDir")}]
311
+
312
+ ${colors.underline("Options")}:
2513
313
  --help, -h Print this help message and exit
2514
314
  --version, -v Print the CLI version and exit
2515
315
  --no-color Disable ANSI colors in console output
@@ -2545,22 +345,22 @@ ${import_picocolors9.default.blueBright("react-router")}
2545
345
  \`typegen\` Options:
2546
346
  --watch Automatically regenerate types whenever route config (\`routes.ts\`) or route modules change
2547
347
 
2548
- ${import_picocolors9.default.underline("Build your project")}:
348
+ ${colors.underline("Build your project")}:
2549
349
 
2550
350
  $ react-router build
2551
351
 
2552
- ${import_picocolors9.default.underline("Run your project locally in development")}:
352
+ ${colors.underline("Run your project locally in development")}:
2553
353
 
2554
354
  $ react-router dev
2555
355
 
2556
- ${import_picocolors9.default.underline("Show all routes in your app")}:
356
+ ${colors.underline("Show all routes in your app")}:
2557
357
 
2558
358
  $ react-router routes
2559
359
  $ react-router routes my-app
2560
360
  $ react-router routes --json
2561
361
  $ react-router routes --config vite.react-router.config.ts
2562
362
 
2563
- ${import_picocolors9.default.underline("Reveal the used entry point")}:
363
+ ${colors.underline("Reveal the used entry point")}:
2564
364
 
2565
365
  $ react-router reveal entry.client
2566
366
  $ react-router reveal entry.server
@@ -2568,109 +368,96 @@ ${import_picocolors9.default.blueBright("react-router")}
2568
368
  $ react-router reveal entry.server --no-typescript
2569
369
  $ react-router reveal entry.server --config vite.react-router.config.ts
2570
370
 
2571
- ${import_picocolors9.default.underline("Generate types for route modules")}:
371
+ ${colors.underline("Generate types for route modules")}:
2572
372
 
2573
373
  $ react-router typegen
2574
374
  $ react-router typegen --watch
2575
375
  `;
2576
- async function run2(argv = process.argv.slice(2)) {
2577
- let versions = process.versions;
2578
- let MINIMUM_NODE_VERSION = 20;
2579
- if (versions && versions.node && import_semver.default.major(versions.node) < MINIMUM_NODE_VERSION) {
2580
- console.warn(
2581
- `\uFE0F\u26A0\uFE0F Oops, Node v${versions.node} detected. react-router requires a Node version greater than ${MINIMUM_NODE_VERSION}.`
2582
- );
2583
- }
2584
- let isBooleanFlag = (arg2) => {
2585
- let index = argv.indexOf(arg2);
2586
- let nextArg = argv[index + 1];
2587
- return !nextArg || nextArg.startsWith("-");
2588
- };
2589
- let args = (0, import_arg.default)(
2590
- {
2591
- "--force": Boolean,
2592
- "--help": Boolean,
2593
- "-h": "--help",
2594
- "--json": Boolean,
2595
- "--token": String,
2596
- "--typescript": Boolean,
2597
- "--no-typescript": Boolean,
2598
- "--version": Boolean,
2599
- "-v": "--version",
2600
- "--port": Number,
2601
- "-p": "--port",
2602
- "--config": String,
2603
- "-c": "--config",
2604
- "--assetsInlineLimit": Number,
2605
- "--clearScreen": Boolean,
2606
- "--cors": Boolean,
2607
- "--emptyOutDir": Boolean,
2608
- "--host": isBooleanFlag("--host") ? Boolean : String,
2609
- "--logLevel": String,
2610
- "-l": "--logLevel",
2611
- "--minify": String,
2612
- "--mode": String,
2613
- "-m": "--mode",
2614
- "--open": isBooleanFlag("--open") ? Boolean : String,
2615
- "--strictPort": Boolean,
2616
- "--profile": Boolean,
2617
- "--sourcemapClient": isBooleanFlag("--sourcemapClient") ? Boolean : String,
2618
- "--sourcemapServer": isBooleanFlag("--sourcemapServer") ? Boolean : String,
2619
- "--watch": Boolean
2620
- },
2621
- {
2622
- argv
2623
- }
2624
- );
2625
- let input = args._;
2626
- let flags = Object.entries(args).reduce((acc, [key, value]) => {
2627
- key = key.replace(/^--/, "");
2628
- acc[key] = value;
2629
- return acc;
2630
- }, {});
2631
- if (flags.help) {
2632
- console.log(helpText);
2633
- return;
2634
- }
2635
- if (flags.version) {
2636
- let version = require("../../package.json").version;
2637
- console.log(version);
2638
- return;
2639
- }
2640
- flags.interactive = flags.interactive ?? require.main === module;
2641
- if (args["--no-typescript"]) {
2642
- flags.typescript = false;
2643
- }
2644
- let command = input[0];
2645
- switch (command) {
2646
- case "routes":
2647
- await routes(input[1], flags);
2648
- break;
2649
- case "build":
2650
- await build2(input[1], flags);
2651
- break;
2652
- case "reveal": {
2653
- await generateEntry(input[1], input[2], flags);
2654
- break;
2655
- }
2656
- case "dev":
2657
- await dev2(input[1], flags);
2658
- break;
2659
- case "typegen":
2660
- await typegen(input[1], flags);
2661
- break;
2662
- default:
2663
- await dev2(input[0], flags);
2664
- }
2665
- }
2666
-
2667
- // cli/index.ts
2668
- run2().then(
2669
- () => {
2670
- process.exit(0);
2671
- },
2672
- (error) => {
2673
- if (error) console.error(error);
2674
- process.exit(1);
2675
- }
2676
- );
376
+ /**
377
+ * Programmatic interface for running the react-router CLI with the given command line
378
+ * arguments.
379
+ */
380
+ async function run(argv = process.argv.slice(2), { isMain = false } = {}) {
381
+ let versions = process.versions;
382
+ let MINIMUM_NODE_VERSION = "22.12.0";
383
+ if (versions && versions.node && semver.lt(versions.node, MINIMUM_NODE_VERSION)) console.warn(`️⚠️ Oops, Node v${versions.node} detected. react-router requires a Node version greater than ${MINIMUM_NODE_VERSION}.`);
384
+ let isBooleanFlag = (arg) => {
385
+ let nextArg = argv[argv.indexOf(arg) + 1];
386
+ return !nextArg || nextArg.startsWith("-");
387
+ };
388
+ let args = arg({
389
+ "--force": Boolean,
390
+ "--help": Boolean,
391
+ "-h": "--help",
392
+ "--json": Boolean,
393
+ "--token": String,
394
+ "--typescript": Boolean,
395
+ "--no-typescript": Boolean,
396
+ "--version": Boolean,
397
+ "-v": "--version",
398
+ "--port": Number,
399
+ "-p": "--port",
400
+ "--config": String,
401
+ "-c": "--config",
402
+ "--assetsInlineLimit": Number,
403
+ "--clearScreen": Boolean,
404
+ "--cors": Boolean,
405
+ "--emptyOutDir": Boolean,
406
+ "--host": isBooleanFlag("--host") ? Boolean : String,
407
+ "--logLevel": String,
408
+ "-l": "--logLevel",
409
+ "--minify": String,
410
+ "--mode": String,
411
+ "-m": "--mode",
412
+ "--open": isBooleanFlag("--open") ? Boolean : String,
413
+ "--strictPort": Boolean,
414
+ "--profile": Boolean,
415
+ "--sourcemapClient": isBooleanFlag("--sourcemapClient") ? Boolean : String,
416
+ "--sourcemapServer": isBooleanFlag("--sourcemapServer") ? Boolean : String,
417
+ "--watch": Boolean
418
+ }, { argv });
419
+ let input = args._;
420
+ let flags = Object.entries(args).reduce((acc, [key, value]) => {
421
+ key = key.replace(/^--/, "");
422
+ acc[key] = value;
423
+ return acc;
424
+ }, {});
425
+ if (flags.help) {
426
+ console.log(helpText);
427
+ return;
428
+ }
429
+ if (flags.version) {
430
+ console.log(packageJson.version);
431
+ return;
432
+ }
433
+ flags.interactive = flags.interactive ?? isMain;
434
+ if (args["--no-typescript"]) flags.typescript = false;
435
+ switch (input[0]) {
436
+ case "routes":
437
+ await routes(input[1], flags);
438
+ break;
439
+ case "build":
440
+ await build(input[1], flags);
441
+ break;
442
+ case "reveal":
443
+ await generateEntry(input[1], input[2], flags);
444
+ break;
445
+ case "dev":
446
+ await dev(input[1], flags);
447
+ break;
448
+ case "typegen":
449
+ await typegen(input[1], flags);
450
+ break;
451
+ default: await dev(input[0], flags);
452
+ }
453
+ }
454
+ //#endregion
455
+ //#region cli/index.ts
456
+ run(void 0, { isMain: true }).then(() => {
457
+ process.exit(0);
458
+ }, (error) => {
459
+ if (error) console.error(error);
460
+ process.exit(1);
461
+ });
462
+ //#endregion
463
+ export { start as n, stop as r, getSession as t };