@react-router/dev 0.0.0-experimental-e1f760554 → 0.0.0-experimental-8d0ea8f67
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/bin.js +2 -4
- package/dist/cli/index.js +1396 -83
- package/dist/config/module-sync-enabled/false.cjs +1 -2
- package/dist/config/module-sync-enabled/index.mjs +4 -0
- package/dist/config.js +19 -1
- package/dist/routes.js +179 -12
- package/dist/vite/cloudflare.js +155 -17
- package/dist/vite.js +2739 -10
- package/package.json +7 -8
- package/dist/build-7TXNW2O3.js +0 -239
- package/dist/chunk-FJ4CMFCI.js +0 -49
- package/dist/chunk-OQBNE3LV.js +0 -219
- package/dist/chunk-PR3MIATB.js +0 -57
- package/dist/chunk-RXPOXUKM.js +0 -2626
- package/dist/chunk-SSBSSZ6H.js +0 -31
- package/dist/chunk-YZMCCARW.js +0 -81
- package/dist/dev-COP3AUB5.js +0 -74
- /package/dist/config/module-sync-enabled/{true.js → true.mjs} +0 -0
package/dist/vite.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @react-router/dev v0.0.0-experimental-
|
|
2
|
+
* @react-router/dev v0.0.0-experimental-8d0ea8f67
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Remix Software Inc.
|
|
5
5
|
*
|
|
@@ -8,13 +8,2742 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
11
|
+
"use strict";
|
|
12
|
+
var __create = Object.create;
|
|
13
|
+
var __defProp = Object.defineProperty;
|
|
14
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
15
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
16
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
17
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
18
|
+
var __export = (target, all) => {
|
|
19
|
+
for (var name in all)
|
|
20
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
20
21
|
};
|
|
22
|
+
var __copyProps = (to, from, except, desc) => {
|
|
23
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
24
|
+
for (let key of __getOwnPropNames(from))
|
|
25
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
26
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
27
|
+
}
|
|
28
|
+
return to;
|
|
29
|
+
};
|
|
30
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
31
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
32
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
33
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
34
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
35
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
36
|
+
mod
|
|
37
|
+
));
|
|
38
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
39
|
+
|
|
40
|
+
// vite.ts
|
|
41
|
+
var vite_exports = {};
|
|
42
|
+
__export(vite_exports, {
|
|
43
|
+
reactRouter: () => reactRouterVitePlugin
|
|
44
|
+
});
|
|
45
|
+
module.exports = __toCommonJS(vite_exports);
|
|
46
|
+
|
|
47
|
+
// vite/plugin.ts
|
|
48
|
+
var import_node_crypto = require("crypto");
|
|
49
|
+
var path6 = __toESM(require("path"));
|
|
50
|
+
var url = __toESM(require("url"));
|
|
51
|
+
var fse = __toESM(require("fs-extra"));
|
|
52
|
+
var babel = __toESM(require("@babel/core"));
|
|
53
|
+
var import_react_router2 = require("react-router");
|
|
54
|
+
var import_es_module_lexer = require("es-module-lexer");
|
|
55
|
+
var import_jsesc = __toESM(require("jsesc"));
|
|
56
|
+
var import_picocolors3 = __toESM(require("picocolors"));
|
|
57
|
+
|
|
58
|
+
// typegen/index.ts
|
|
59
|
+
var import_node_fs2 = __toESM(require("fs"));
|
|
60
|
+
var Path4 = __toESM(require("pathe"));
|
|
61
|
+
var import_picocolors2 = __toESM(require("picocolors"));
|
|
62
|
+
|
|
63
|
+
// config/config.ts
|
|
64
|
+
var import_node_fs = __toESM(require("fs"));
|
|
65
|
+
var import_node_child_process = require("child_process");
|
|
66
|
+
var import_package_json = __toESM(require("@npmcli/package-json"));
|
|
67
|
+
|
|
68
|
+
// vite/vite-node.ts
|
|
69
|
+
var import_server = require("vite-node/server");
|
|
70
|
+
var import_client = require("vite-node/client");
|
|
71
|
+
var import_source_map = require("vite-node/source-map");
|
|
72
|
+
|
|
73
|
+
// vite/vite.ts
|
|
74
|
+
var import_pathe2 = __toESM(require("pathe"));
|
|
75
|
+
|
|
76
|
+
// invariant.ts
|
|
77
|
+
function invariant(value, message) {
|
|
78
|
+
if (value === false || value === null || typeof value === "undefined") {
|
|
79
|
+
console.error(
|
|
80
|
+
"The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
|
|
81
|
+
);
|
|
82
|
+
throw new Error(message);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// config/is-react-router-repo.ts
|
|
87
|
+
var import_pathe = __toESM(require("pathe"));
|
|
88
|
+
function isReactRouterRepo() {
|
|
89
|
+
let serverRuntimePath = import_pathe.default.dirname(
|
|
90
|
+
require.resolve("@react-router/node/package.json")
|
|
91
|
+
);
|
|
92
|
+
let serverRuntimeParentDir = import_pathe.default.basename(
|
|
93
|
+
import_pathe.default.resolve(serverRuntimePath, "..")
|
|
94
|
+
);
|
|
95
|
+
return serverRuntimeParentDir === "packages";
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// vite/vite.ts
|
|
99
|
+
var vite;
|
|
100
|
+
var viteImportSpecifier = isReactRouterRepo() ? (
|
|
101
|
+
// Support testing against different versions of Vite by ensuring that Vite
|
|
102
|
+
// is resolved from the current working directory when running within this
|
|
103
|
+
// repo. If we don't do this, Vite will always be imported relative to this
|
|
104
|
+
// file, which means that it will always resolve to Vite 6.
|
|
105
|
+
`file:///${import_pathe2.default.normalize(
|
|
106
|
+
require.resolve("vite/package.json", { paths: [process.cwd()] })
|
|
107
|
+
).replace("package.json", "dist/node/index.js")}`
|
|
108
|
+
) : "vite";
|
|
109
|
+
async function preloadVite() {
|
|
110
|
+
vite = await import(viteImportSpecifier);
|
|
111
|
+
}
|
|
112
|
+
function getVite() {
|
|
113
|
+
invariant(vite, "getVite() called before preloadVite()");
|
|
114
|
+
return vite;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// vite/vite-node.ts
|
|
118
|
+
async function createContext(viteConfig = {}) {
|
|
119
|
+
await preloadVite();
|
|
120
|
+
const vite2 = getVite();
|
|
121
|
+
const devServer = await vite2.createServer(
|
|
122
|
+
vite2.mergeConfig(
|
|
123
|
+
{
|
|
124
|
+
server: {
|
|
125
|
+
preTransformRequests: false,
|
|
126
|
+
hmr: false
|
|
127
|
+
},
|
|
128
|
+
optimizeDeps: {
|
|
129
|
+
noDiscovery: true
|
|
130
|
+
},
|
|
131
|
+
configFile: false,
|
|
132
|
+
envFile: false,
|
|
133
|
+
plugins: []
|
|
134
|
+
},
|
|
135
|
+
viteConfig
|
|
136
|
+
)
|
|
137
|
+
);
|
|
138
|
+
await devServer.pluginContainer.buildStart({});
|
|
139
|
+
const server = new import_server.ViteNodeServer(devServer);
|
|
140
|
+
(0, import_source_map.installSourcemapsSupport)({
|
|
141
|
+
getSourceMap: (source) => server.getSourceMap(source)
|
|
142
|
+
});
|
|
143
|
+
const runner = new import_client.ViteNodeRunner({
|
|
144
|
+
root: devServer.config.root,
|
|
145
|
+
base: devServer.config.base,
|
|
146
|
+
fetchModule(id) {
|
|
147
|
+
return server.fetchModule(id);
|
|
148
|
+
},
|
|
149
|
+
resolveId(id, importer) {
|
|
150
|
+
return server.resolveId(id, importer);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
return { devServer, server, runner };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// config/config.ts
|
|
157
|
+
var import_pathe3 = __toESM(require("pathe"));
|
|
158
|
+
var import_chokidar = __toESM(require("chokidar"));
|
|
159
|
+
var import_picocolors = __toESM(require("picocolors"));
|
|
160
|
+
var import_pick2 = __toESM(require("lodash/pick"));
|
|
161
|
+
var import_omit = __toESM(require("lodash/omit"));
|
|
162
|
+
var import_cloneDeep = __toESM(require("lodash/cloneDeep"));
|
|
163
|
+
var import_isEqual = __toESM(require("lodash/isEqual"));
|
|
164
|
+
|
|
165
|
+
// config/routes.ts
|
|
166
|
+
var Path = __toESM(require("pathe"));
|
|
167
|
+
var v = __toESM(require("valibot"));
|
|
168
|
+
var import_pick = __toESM(require("lodash/pick"));
|
|
169
|
+
function setAppDirectory(directory) {
|
|
170
|
+
globalThis.__reactRouterAppDirectory = directory;
|
|
171
|
+
}
|
|
172
|
+
var routeConfigEntrySchema = v.pipe(
|
|
173
|
+
v.custom((value) => {
|
|
174
|
+
return !(typeof value === "object" && value !== null && "then" in value && "catch" in value);
|
|
175
|
+
}, "Invalid type: Expected object but received a promise. Did you forget to await?"),
|
|
176
|
+
v.object({
|
|
177
|
+
id: v.optional(v.string()),
|
|
178
|
+
path: v.optional(v.string()),
|
|
179
|
+
index: v.optional(v.boolean()),
|
|
180
|
+
caseSensitive: v.optional(v.boolean()),
|
|
181
|
+
file: v.string(),
|
|
182
|
+
children: v.optional(v.array(v.lazy(() => routeConfigEntrySchema)))
|
|
183
|
+
})
|
|
184
|
+
);
|
|
185
|
+
var resolvedRouteConfigSchema = v.array(routeConfigEntrySchema);
|
|
186
|
+
function validateRouteConfig({
|
|
187
|
+
routeConfigFile,
|
|
188
|
+
routeConfig
|
|
189
|
+
}) {
|
|
190
|
+
if (!routeConfig) {
|
|
191
|
+
return {
|
|
192
|
+
valid: false,
|
|
193
|
+
message: `Route config must be the default export in "${routeConfigFile}".`
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
if (!Array.isArray(routeConfig)) {
|
|
197
|
+
return {
|
|
198
|
+
valid: false,
|
|
199
|
+
message: `Route config in "${routeConfigFile}" must be an array.`
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
let { issues } = v.safeParse(resolvedRouteConfigSchema, routeConfig);
|
|
203
|
+
if (issues?.length) {
|
|
204
|
+
let { root, nested } = v.flatten(issues);
|
|
205
|
+
return {
|
|
206
|
+
valid: false,
|
|
207
|
+
message: [
|
|
208
|
+
`Route config in "${routeConfigFile}" is invalid.`,
|
|
209
|
+
root ? `${root}` : [],
|
|
210
|
+
nested ? Object.entries(nested).map(
|
|
211
|
+
([path7, message]) => `Path: routes.${path7}
|
|
212
|
+
${message}`
|
|
213
|
+
) : []
|
|
214
|
+
].flat().join("\n\n")
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
return { valid: true };
|
|
218
|
+
}
|
|
219
|
+
function configRoutesToRouteManifest(appDirectory, routes, rootId = "root") {
|
|
220
|
+
let routeManifest = {};
|
|
221
|
+
function walk(route, parentId) {
|
|
222
|
+
let id = route.id || createRouteId(route.file);
|
|
223
|
+
let manifestItem = {
|
|
224
|
+
id,
|
|
225
|
+
parentId,
|
|
226
|
+
file: Path.isAbsolute(route.file) ? Path.relative(appDirectory, route.file) : route.file,
|
|
227
|
+
path: route.path,
|
|
228
|
+
index: route.index,
|
|
229
|
+
caseSensitive: route.caseSensitive
|
|
230
|
+
};
|
|
231
|
+
if (routeManifest.hasOwnProperty(id)) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
`Unable to define routes with duplicate route id: "${id}"`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
routeManifest[id] = manifestItem;
|
|
237
|
+
if (route.children) {
|
|
238
|
+
for (let child of route.children) {
|
|
239
|
+
walk(child, id);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
for (let route of routes) {
|
|
244
|
+
walk(route, rootId);
|
|
245
|
+
}
|
|
246
|
+
return routeManifest;
|
|
247
|
+
}
|
|
248
|
+
function createRouteId(file) {
|
|
249
|
+
return Path.normalize(stripFileExtension(file));
|
|
250
|
+
}
|
|
251
|
+
function stripFileExtension(file) {
|
|
252
|
+
return file.replace(/\.[a-z0-9]+$/i, "");
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// cli/detectPackageManager.ts
|
|
256
|
+
var detectPackageManager = () => {
|
|
257
|
+
let { npm_config_user_agent } = process.env;
|
|
258
|
+
if (!npm_config_user_agent) return void 0;
|
|
259
|
+
try {
|
|
260
|
+
let pkgManager = npm_config_user_agent.split("/")[0];
|
|
261
|
+
if (pkgManager === "npm") return "npm";
|
|
262
|
+
if (pkgManager === "pnpm") return "pnpm";
|
|
263
|
+
if (pkgManager === "yarn") return "yarn";
|
|
264
|
+
if (pkgManager === "bun") return "bun";
|
|
265
|
+
return void 0;
|
|
266
|
+
} catch {
|
|
267
|
+
return void 0;
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
// config/config.ts
|
|
272
|
+
var excludedConfigPresetKeys = ["presets"];
|
|
273
|
+
var mergeReactRouterConfig = (...configs) => {
|
|
274
|
+
let reducer = (configA, configB) => {
|
|
275
|
+
let mergeRequired = (key) => configA[key] !== void 0 && configB[key] !== void 0;
|
|
276
|
+
return {
|
|
277
|
+
...configA,
|
|
278
|
+
...configB,
|
|
279
|
+
...mergeRequired("buildEnd") ? {
|
|
280
|
+
buildEnd: async (...args) => {
|
|
281
|
+
await Promise.all([
|
|
282
|
+
configA.buildEnd?.(...args),
|
|
283
|
+
configB.buildEnd?.(...args)
|
|
284
|
+
]);
|
|
285
|
+
}
|
|
286
|
+
} : {},
|
|
287
|
+
...mergeRequired("future") ? {
|
|
288
|
+
future: {
|
|
289
|
+
...configA.future,
|
|
290
|
+
...configB.future
|
|
291
|
+
}
|
|
292
|
+
} : {},
|
|
293
|
+
...mergeRequired("presets") ? {
|
|
294
|
+
presets: [...configA.presets ?? [], ...configB.presets ?? []]
|
|
295
|
+
} : {}
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
return configs.reduce(reducer, {});
|
|
299
|
+
};
|
|
300
|
+
var deepFreeze = (o) => {
|
|
301
|
+
Object.freeze(o);
|
|
302
|
+
let oIsFunction = typeof o === "function";
|
|
303
|
+
let hasOwnProp = Object.prototype.hasOwnProperty;
|
|
304
|
+
Object.getOwnPropertyNames(o).forEach(function(prop) {
|
|
305
|
+
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])) {
|
|
306
|
+
deepFreeze(o[prop]);
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
return o;
|
|
310
|
+
};
|
|
311
|
+
function ok(value) {
|
|
312
|
+
return { ok: true, value };
|
|
313
|
+
}
|
|
314
|
+
function err(error) {
|
|
315
|
+
return { ok: false, error };
|
|
316
|
+
}
|
|
317
|
+
async function resolveConfig({
|
|
318
|
+
root,
|
|
319
|
+
viteNodeContext,
|
|
320
|
+
reactRouterConfigFile
|
|
321
|
+
}) {
|
|
322
|
+
let reactRouterUserConfig = {};
|
|
323
|
+
if (reactRouterConfigFile) {
|
|
324
|
+
try {
|
|
325
|
+
if (!import_node_fs.default.existsSync(reactRouterConfigFile)) {
|
|
326
|
+
return err(`${reactRouterConfigFile} no longer exists`);
|
|
327
|
+
}
|
|
328
|
+
let configModule = await viteNodeContext.runner.executeFile(
|
|
329
|
+
reactRouterConfigFile
|
|
330
|
+
);
|
|
331
|
+
if (configModule.default === void 0) {
|
|
332
|
+
return err(`${reactRouterConfigFile} must provide a default export`);
|
|
333
|
+
}
|
|
334
|
+
if (typeof configModule.default !== "object") {
|
|
335
|
+
return err(`${reactRouterConfigFile} must export a config`);
|
|
336
|
+
}
|
|
337
|
+
reactRouterUserConfig = configModule.default;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
return err(`Error loading ${reactRouterConfigFile}: ${error}`);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
reactRouterUserConfig = deepFreeze((0, import_cloneDeep.default)(reactRouterUserConfig));
|
|
343
|
+
let presets = (await Promise.all(
|
|
344
|
+
(reactRouterUserConfig.presets ?? []).map(async (preset) => {
|
|
345
|
+
if (!preset.name) {
|
|
346
|
+
throw new Error(
|
|
347
|
+
"React Router presets must have a `name` property defined."
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
if (!preset.reactRouterConfig) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
let configPreset = (0, import_omit.default)(
|
|
354
|
+
await preset.reactRouterConfig({ reactRouterUserConfig }),
|
|
355
|
+
excludedConfigPresetKeys
|
|
356
|
+
);
|
|
357
|
+
return configPreset;
|
|
358
|
+
})
|
|
359
|
+
)).filter(function isNotNull(value) {
|
|
360
|
+
return value !== null;
|
|
361
|
+
});
|
|
362
|
+
let defaults = {
|
|
363
|
+
basename: "/",
|
|
364
|
+
buildDirectory: "build",
|
|
365
|
+
serverBuildFile: "index.js",
|
|
366
|
+
serverModuleFormat: "esm",
|
|
367
|
+
ssr: true
|
|
368
|
+
};
|
|
369
|
+
let {
|
|
370
|
+
appDirectory: userAppDirectory,
|
|
371
|
+
basename: basename2,
|
|
372
|
+
buildDirectory: userBuildDirectory,
|
|
373
|
+
buildEnd,
|
|
374
|
+
prerender,
|
|
375
|
+
serverBuildFile,
|
|
376
|
+
serverBundles,
|
|
377
|
+
serverModuleFormat,
|
|
378
|
+
ssr
|
|
379
|
+
} = {
|
|
380
|
+
...defaults,
|
|
381
|
+
// Default values should be completely overridden by user/preset config, not merged
|
|
382
|
+
...mergeReactRouterConfig(...presets, reactRouterUserConfig)
|
|
383
|
+
};
|
|
384
|
+
if (!ssr && serverBundles) {
|
|
385
|
+
serverBundles = void 0;
|
|
386
|
+
}
|
|
387
|
+
let isValidPrerenderConfig = prerender == null || typeof prerender === "boolean" || Array.isArray(prerender) || typeof prerender === "function";
|
|
388
|
+
if (!isValidPrerenderConfig) {
|
|
389
|
+
return err(
|
|
390
|
+
"The `prerender` config must be a boolean, an array of string paths, or a function returning a boolean or array of string paths"
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
let appDirectory = import_pathe3.default.resolve(root, userAppDirectory || "app");
|
|
394
|
+
let buildDirectory = import_pathe3.default.resolve(root, userBuildDirectory);
|
|
395
|
+
let rootRouteFile = findEntry(appDirectory, "root");
|
|
396
|
+
if (!rootRouteFile) {
|
|
397
|
+
let rootRouteDisplayPath = import_pathe3.default.relative(
|
|
398
|
+
root,
|
|
399
|
+
import_pathe3.default.join(appDirectory, "root.tsx")
|
|
400
|
+
);
|
|
401
|
+
return err(
|
|
402
|
+
`Could not find a root route module in the app directory as "${rootRouteDisplayPath}"`
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
let routes = {
|
|
406
|
+
root: { path: "", id: "root", file: rootRouteFile }
|
|
407
|
+
};
|
|
408
|
+
let routeConfigFile = findEntry(appDirectory, "routes");
|
|
409
|
+
try {
|
|
410
|
+
if (!routeConfigFile) {
|
|
411
|
+
let routeConfigDisplayPath = import_pathe3.default.relative(
|
|
412
|
+
root,
|
|
413
|
+
import_pathe3.default.join(appDirectory, "routes.ts")
|
|
414
|
+
);
|
|
415
|
+
return err(`Route config file not found at "${routeConfigDisplayPath}".`);
|
|
416
|
+
}
|
|
417
|
+
setAppDirectory(appDirectory);
|
|
418
|
+
let routeConfigExport = (await viteNodeContext.runner.executeFile(
|
|
419
|
+
import_pathe3.default.join(appDirectory, routeConfigFile)
|
|
420
|
+
)).default;
|
|
421
|
+
let routeConfig = await routeConfigExport;
|
|
422
|
+
let result = validateRouteConfig({
|
|
423
|
+
routeConfigFile,
|
|
424
|
+
routeConfig
|
|
425
|
+
});
|
|
426
|
+
if (!result.valid) {
|
|
427
|
+
return err(result.message);
|
|
428
|
+
}
|
|
429
|
+
routes = {
|
|
430
|
+
...routes,
|
|
431
|
+
...configRoutesToRouteManifest(appDirectory, routeConfig)
|
|
432
|
+
};
|
|
433
|
+
} catch (error) {
|
|
434
|
+
return err(
|
|
435
|
+
[
|
|
436
|
+
import_picocolors.default.red(`Route config in "${routeConfigFile}" is invalid.`),
|
|
437
|
+
"",
|
|
438
|
+
error.loc?.file && error.loc?.column && error.frame ? [
|
|
439
|
+
import_pathe3.default.relative(appDirectory, error.loc.file) + ":" + error.loc.line + ":" + error.loc.column,
|
|
440
|
+
error.frame.trim?.()
|
|
441
|
+
] : error.stack
|
|
442
|
+
].flat().join("\n")
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
let future = {
|
|
446
|
+
unstable_optimizeDeps: reactRouterUserConfig.future?.unstable_optimizeDeps ?? false
|
|
447
|
+
};
|
|
448
|
+
let reactRouterConfig = deepFreeze({
|
|
449
|
+
appDirectory,
|
|
450
|
+
basename: basename2,
|
|
451
|
+
buildDirectory,
|
|
452
|
+
buildEnd,
|
|
453
|
+
future,
|
|
454
|
+
prerender,
|
|
455
|
+
routes,
|
|
456
|
+
serverBuildFile,
|
|
457
|
+
serverBundles,
|
|
458
|
+
serverModuleFormat,
|
|
459
|
+
ssr
|
|
460
|
+
});
|
|
461
|
+
for (let preset of reactRouterUserConfig.presets ?? []) {
|
|
462
|
+
await preset.reactRouterConfigResolved?.({ reactRouterConfig });
|
|
463
|
+
}
|
|
464
|
+
return ok(reactRouterConfig);
|
|
465
|
+
}
|
|
466
|
+
async function createConfigLoader({
|
|
467
|
+
rootDirectory: root,
|
|
468
|
+
watch: watch2
|
|
469
|
+
}) {
|
|
470
|
+
root = root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
|
|
471
|
+
let viteNodeContext = await createContext({
|
|
472
|
+
root,
|
|
473
|
+
mode: watch2 ? "development" : "production",
|
|
474
|
+
server: !watch2 ? { watch: null } : {},
|
|
475
|
+
ssr: {
|
|
476
|
+
external: ssrExternals
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
let reactRouterConfigFile = findEntry(root, "react-router.config", {
|
|
480
|
+
absolute: true
|
|
481
|
+
});
|
|
482
|
+
let getConfig = () => resolveConfig({ root, viteNodeContext, reactRouterConfigFile });
|
|
483
|
+
let appDirectory;
|
|
484
|
+
let initialConfigResult = await getConfig();
|
|
485
|
+
if (!initialConfigResult.ok) {
|
|
486
|
+
throw new Error(initialConfigResult.error);
|
|
487
|
+
}
|
|
488
|
+
appDirectory = initialConfigResult.value.appDirectory;
|
|
489
|
+
let lastConfig = initialConfigResult.value;
|
|
490
|
+
let fsWatcher;
|
|
491
|
+
let changeHandlers = [];
|
|
492
|
+
return {
|
|
493
|
+
getConfig,
|
|
494
|
+
onChange: (handler) => {
|
|
495
|
+
if (!watch2) {
|
|
496
|
+
throw new Error(
|
|
497
|
+
"onChange is not supported when watch mode is disabled"
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
changeHandlers.push(handler);
|
|
501
|
+
if (!fsWatcher) {
|
|
502
|
+
fsWatcher = import_chokidar.default.watch(
|
|
503
|
+
[
|
|
504
|
+
...reactRouterConfigFile ? [reactRouterConfigFile] : [],
|
|
505
|
+
appDirectory
|
|
506
|
+
],
|
|
507
|
+
{ ignoreInitial: true }
|
|
508
|
+
);
|
|
509
|
+
fsWatcher.on("all", async (...args) => {
|
|
510
|
+
let [event, rawFilepath] = args;
|
|
511
|
+
let filepath = import_pathe3.default.normalize(rawFilepath);
|
|
512
|
+
let appFileAddedOrRemoved = appDirectory && (event === "add" || event === "unlink") && filepath.startsWith(import_pathe3.default.normalize(appDirectory));
|
|
513
|
+
let configCodeUpdated = Boolean(
|
|
514
|
+
viteNodeContext.devServer?.moduleGraph.getModuleById(filepath)
|
|
515
|
+
);
|
|
516
|
+
if (configCodeUpdated || appFileAddedOrRemoved) {
|
|
517
|
+
viteNodeContext.devServer?.moduleGraph.invalidateAll();
|
|
518
|
+
viteNodeContext.runner?.moduleCache.clear();
|
|
519
|
+
}
|
|
520
|
+
if (appFileAddedOrRemoved || configCodeUpdated) {
|
|
521
|
+
let result = await getConfig();
|
|
522
|
+
let configChanged = result.ok && !(0, import_isEqual.default)(lastConfig, result.value);
|
|
523
|
+
let routeConfigChanged = result.ok && !(0, import_isEqual.default)(lastConfig?.routes, result.value.routes);
|
|
524
|
+
for (let handler2 of changeHandlers) {
|
|
525
|
+
handler2({
|
|
526
|
+
result,
|
|
527
|
+
configCodeUpdated,
|
|
528
|
+
configChanged,
|
|
529
|
+
routeConfigChanged,
|
|
530
|
+
path: filepath,
|
|
531
|
+
event
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
if (result.ok) {
|
|
535
|
+
lastConfig = result.value;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
return () => {
|
|
541
|
+
changeHandlers = changeHandlers.filter(
|
|
542
|
+
(changeHandler) => changeHandler !== handler
|
|
543
|
+
);
|
|
544
|
+
};
|
|
545
|
+
},
|
|
546
|
+
close: async () => {
|
|
547
|
+
changeHandlers = [];
|
|
548
|
+
await viteNodeContext.devServer.close();
|
|
549
|
+
await fsWatcher?.close();
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
async function resolveEntryFiles({
|
|
554
|
+
rootDirectory,
|
|
555
|
+
reactRouterConfig
|
|
556
|
+
}) {
|
|
557
|
+
let { appDirectory } = reactRouterConfig;
|
|
558
|
+
let defaultsDirectory = import_pathe3.default.resolve(
|
|
559
|
+
import_pathe3.default.dirname(require.resolve("@react-router/dev/package.json")),
|
|
560
|
+
"dist",
|
|
561
|
+
"config",
|
|
562
|
+
"defaults"
|
|
563
|
+
);
|
|
564
|
+
let userEntryClientFile = findEntry(appDirectory, "entry.client");
|
|
565
|
+
let userEntryServerFile = findEntry(appDirectory, "entry.server");
|
|
566
|
+
let entryServerFile;
|
|
567
|
+
let entryClientFile = userEntryClientFile || "entry.client.tsx";
|
|
568
|
+
let pkgJson = await import_package_json.default.load(rootDirectory);
|
|
569
|
+
let deps = pkgJson.content.dependencies ?? {};
|
|
570
|
+
if (userEntryServerFile) {
|
|
571
|
+
entryServerFile = userEntryServerFile;
|
|
572
|
+
} else {
|
|
573
|
+
if (!deps["@react-router/node"]) {
|
|
574
|
+
throw new Error(
|
|
575
|
+
`Could not determine server runtime. Please install @react-router/node, or provide a custom entry.server.tsx/jsx file in your app directory.`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
if (!deps["isbot"]) {
|
|
579
|
+
console.log(
|
|
580
|
+
"adding `isbot@5` to your package.json, you should commit this change"
|
|
581
|
+
);
|
|
582
|
+
pkgJson.update({
|
|
583
|
+
dependencies: {
|
|
584
|
+
...pkgJson.content.dependencies,
|
|
585
|
+
isbot: "^5"
|
|
586
|
+
}
|
|
587
|
+
});
|
|
588
|
+
await pkgJson.save();
|
|
589
|
+
let packageManager = detectPackageManager() ?? "npm";
|
|
590
|
+
(0, import_node_child_process.execSync)(`${packageManager} install`, {
|
|
591
|
+
cwd: rootDirectory,
|
|
592
|
+
stdio: "inherit"
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
entryServerFile = `entry.server.node.tsx`;
|
|
596
|
+
}
|
|
597
|
+
let entryClientFilePath = userEntryClientFile ? import_pathe3.default.resolve(reactRouterConfig.appDirectory, userEntryClientFile) : import_pathe3.default.resolve(defaultsDirectory, entryClientFile);
|
|
598
|
+
let entryServerFilePath = userEntryServerFile ? import_pathe3.default.resolve(reactRouterConfig.appDirectory, userEntryServerFile) : import_pathe3.default.resolve(defaultsDirectory, entryServerFile);
|
|
599
|
+
return { entryClientFilePath, entryServerFilePath };
|
|
600
|
+
}
|
|
601
|
+
var ssrExternals = isReactRouterRepo() ? [
|
|
602
|
+
// This is only needed within this repo because these packages
|
|
603
|
+
// are linked to a directory outside of node_modules so Vite
|
|
604
|
+
// treats them as internal code by default.
|
|
605
|
+
"react-router",
|
|
606
|
+
"react-router-dom",
|
|
607
|
+
"@react-router/architect",
|
|
608
|
+
"@react-router/cloudflare",
|
|
609
|
+
"@react-router/dev",
|
|
610
|
+
"@react-router/express",
|
|
611
|
+
"@react-router/node",
|
|
612
|
+
"@react-router/serve"
|
|
613
|
+
] : void 0;
|
|
614
|
+
var entryExts = [".js", ".jsx", ".ts", ".tsx"];
|
|
615
|
+
function findEntry(dir, basename2, options) {
|
|
616
|
+
for (let ext of entryExts) {
|
|
617
|
+
let file = import_pathe3.default.resolve(dir, basename2 + ext);
|
|
618
|
+
if (import_node_fs.default.existsSync(file)) {
|
|
619
|
+
return options?.absolute ?? false ? file : import_pathe3.default.relative(dir, file);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return void 0;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// typegen/generate.ts
|
|
626
|
+
var import_dedent = __toESM(require("dedent"));
|
|
627
|
+
var Path3 = __toESM(require("pathe"));
|
|
628
|
+
var Pathe2 = __toESM(require("pathe/utils"));
|
|
629
|
+
|
|
630
|
+
// typegen/paths.ts
|
|
631
|
+
var Path2 = __toESM(require("pathe"));
|
|
632
|
+
var Pathe = __toESM(require("pathe/utils"));
|
|
633
|
+
function getTypesDir(ctx) {
|
|
634
|
+
return Path2.join(ctx.rootDirectory, ".react-router/types");
|
|
635
|
+
}
|
|
636
|
+
function getTypesPath(ctx, route) {
|
|
637
|
+
return Path2.join(
|
|
638
|
+
getTypesDir(ctx),
|
|
639
|
+
Path2.relative(ctx.rootDirectory, ctx.config.appDirectory),
|
|
640
|
+
Path2.dirname(route.file),
|
|
641
|
+
"+types/" + Pathe.filename(route.file) + ".ts"
|
|
642
|
+
);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// typegen/generate.ts
|
|
646
|
+
function generate(ctx, route) {
|
|
647
|
+
const lineage = getRouteLineage(ctx.config.routes, route);
|
|
648
|
+
const urlpath = lineage.map((route2) => route2.path).join("/");
|
|
649
|
+
const typesPath = getTypesPath(ctx, route);
|
|
650
|
+
const parents = lineage.slice(0, -1);
|
|
651
|
+
const parentTypeImports = parents.map((parent, i) => {
|
|
652
|
+
const rel = Path3.relative(
|
|
653
|
+
Path3.dirname(typesPath),
|
|
654
|
+
getTypesPath(ctx, parent)
|
|
655
|
+
);
|
|
656
|
+
const indent = i === 0 ? "" : " ".repeat(2);
|
|
657
|
+
let source = noExtension(rel);
|
|
658
|
+
if (!source.startsWith("../")) source = "./" + source;
|
|
659
|
+
return `${indent}import type { Info as Parent${i} } from "${source}.js"`;
|
|
660
|
+
}).join("\n");
|
|
661
|
+
return import_dedent.default`
|
|
662
|
+
// React Router generated types for route:
|
|
663
|
+
// ${route.file}
|
|
664
|
+
|
|
665
|
+
import type * as T from "react-router/route-module"
|
|
666
|
+
|
|
667
|
+
${parentTypeImports}
|
|
668
|
+
|
|
669
|
+
type Module = typeof import("../${Pathe2.filename(route.file)}.js")
|
|
670
|
+
|
|
671
|
+
export type Info = {
|
|
672
|
+
parents: [${parents.map((_, i) => `Parent${i}`).join(", ")}],
|
|
673
|
+
id: "${route.id}"
|
|
674
|
+
file: "${route.file}"
|
|
675
|
+
path: "${route.path}"
|
|
676
|
+
params: {${formatParamProperties(
|
|
677
|
+
urlpath
|
|
678
|
+
)}} & { [key: string]: string | undefined }
|
|
679
|
+
module: Module
|
|
680
|
+
loaderData: T.CreateLoaderData<Module>
|
|
681
|
+
actionData: T.CreateActionData<Module>
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
export namespace Route {
|
|
685
|
+
export type LinkDescriptors = T.LinkDescriptors
|
|
686
|
+
export type LinksFunction = () => LinkDescriptors
|
|
687
|
+
|
|
688
|
+
export type MetaArgs = T.CreateMetaArgs<Info>
|
|
689
|
+
export type MetaDescriptors = T.MetaDescriptors
|
|
690
|
+
export type MetaFunction = (args: MetaArgs) => MetaDescriptors
|
|
691
|
+
|
|
692
|
+
export type HeadersArgs = T.HeadersArgs
|
|
693
|
+
export type HeadersFunction = (args: HeadersArgs) => Headers | HeadersInit
|
|
694
|
+
|
|
695
|
+
export type LoaderArgs = T.CreateServerLoaderArgs<Info>
|
|
696
|
+
export type ClientLoaderArgs = T.CreateClientLoaderArgs<Info>
|
|
697
|
+
export type ActionArgs = T.CreateServerActionArgs<Info>
|
|
698
|
+
export type ClientActionArgs = T.CreateClientActionArgs<Info>
|
|
699
|
+
|
|
700
|
+
export type HydrateFallbackProps = T.CreateHydrateFallbackProps<Info>
|
|
701
|
+
export type ComponentProps = T.CreateComponentProps<Info>
|
|
702
|
+
export type ErrorBoundaryProps = T.CreateErrorBoundaryProps<Info>
|
|
703
|
+
}
|
|
704
|
+
`;
|
|
705
|
+
}
|
|
706
|
+
var noExtension = (path7) => Path3.join(Path3.dirname(path7), Pathe2.filename(path7));
|
|
707
|
+
function getRouteLineage(routes, route) {
|
|
708
|
+
const result = [];
|
|
709
|
+
while (route) {
|
|
710
|
+
result.push(route);
|
|
711
|
+
if (!route.parentId) break;
|
|
712
|
+
route = routes[route.parentId];
|
|
713
|
+
}
|
|
714
|
+
result.reverse();
|
|
715
|
+
return result;
|
|
716
|
+
}
|
|
717
|
+
function formatParamProperties(urlpath) {
|
|
718
|
+
const params = parseParams(urlpath);
|
|
719
|
+
const properties = Object.entries(params).map(([name, values]) => {
|
|
720
|
+
if (values.length === 1) {
|
|
721
|
+
const isOptional = values[0];
|
|
722
|
+
return isOptional ? `"${name}"?: string` : `"${name}": string`;
|
|
723
|
+
}
|
|
724
|
+
const items = values.map(
|
|
725
|
+
(isOptional) => isOptional ? "string | undefined" : "string"
|
|
726
|
+
);
|
|
727
|
+
return `"${name}": [${items.join(", ")}]`;
|
|
728
|
+
});
|
|
729
|
+
return properties.join("; ");
|
|
730
|
+
}
|
|
731
|
+
function parseParams(urlpath) {
|
|
732
|
+
const result = {};
|
|
733
|
+
let segments = urlpath.split("/");
|
|
734
|
+
segments.forEach((segment) => {
|
|
735
|
+
const match = segment.match(/^:([\w-]+)(\?)?/);
|
|
736
|
+
if (!match) return;
|
|
737
|
+
const param = match[1];
|
|
738
|
+
const isOptional = match[2] !== void 0;
|
|
739
|
+
result[param] ??= [];
|
|
740
|
+
result[param].push(isOptional);
|
|
741
|
+
return;
|
|
742
|
+
});
|
|
743
|
+
const hasSplat = segments.at(-1) === "*";
|
|
744
|
+
if (hasSplat) result["*"] = [false];
|
|
745
|
+
return result;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// typegen/index.ts
|
|
749
|
+
async function watch(rootDirectory, { logger } = {}) {
|
|
750
|
+
const ctx = await createContext2({ rootDirectory, watch: true });
|
|
751
|
+
await writeAll(ctx);
|
|
752
|
+
logger?.info(import_picocolors2.default.green("generated types"), { timestamp: true, clear: true });
|
|
753
|
+
ctx.configLoader.onChange(async ({ result, routeConfigChanged }) => {
|
|
754
|
+
if (!result.ok) {
|
|
755
|
+
logger?.error(import_picocolors2.default.red(result.error), { timestamp: true, clear: true });
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
ctx.config = result.value;
|
|
759
|
+
if (routeConfigChanged) {
|
|
760
|
+
await writeAll(ctx);
|
|
761
|
+
logger?.info(import_picocolors2.default.green("regenerated types"), {
|
|
762
|
+
timestamp: true,
|
|
763
|
+
clear: true
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
});
|
|
767
|
+
return {
|
|
768
|
+
close: async () => await ctx.configLoader.close()
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
async function createContext2({
|
|
772
|
+
rootDirectory,
|
|
773
|
+
watch: watch2
|
|
774
|
+
}) {
|
|
775
|
+
const configLoader = await createConfigLoader({ rootDirectory, watch: watch2 });
|
|
776
|
+
const configResult = await configLoader.getConfig();
|
|
777
|
+
if (!configResult.ok) {
|
|
778
|
+
throw new Error(configResult.error);
|
|
779
|
+
}
|
|
780
|
+
const config = configResult.value;
|
|
781
|
+
return {
|
|
782
|
+
configLoader,
|
|
783
|
+
rootDirectory,
|
|
784
|
+
config
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
async function writeAll(ctx) {
|
|
788
|
+
const typegenDir = getTypesDir(ctx);
|
|
789
|
+
import_node_fs2.default.rmSync(typegenDir, { recursive: true, force: true });
|
|
790
|
+
Object.values(ctx.config.routes).forEach((route) => {
|
|
791
|
+
const typesPath = getTypesPath(ctx, route);
|
|
792
|
+
const content = generate(ctx, route);
|
|
793
|
+
import_node_fs2.default.mkdirSync(Path4.dirname(typesPath), { recursive: true });
|
|
794
|
+
import_node_fs2.default.writeFileSync(typesPath, content);
|
|
795
|
+
});
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// vite/babel.ts
|
|
799
|
+
var import_parser = require("@babel/parser");
|
|
800
|
+
var t = __toESM(require("@babel/types"));
|
|
801
|
+
var traverse = require("@babel/traverse").default;
|
|
802
|
+
var generate2 = require("@babel/generator").default;
|
|
803
|
+
|
|
804
|
+
// vite/node-adapter.ts
|
|
805
|
+
var import_node_events = require("events");
|
|
806
|
+
var import_node_stream = require("stream");
|
|
807
|
+
var import_set_cookie_parser = require("set-cookie-parser");
|
|
808
|
+
var import_node = require("@react-router/node");
|
|
809
|
+
function fromNodeHeaders(nodeHeaders) {
|
|
810
|
+
let headers = new Headers();
|
|
811
|
+
for (let [key, values] of Object.entries(nodeHeaders)) {
|
|
812
|
+
if (values) {
|
|
813
|
+
if (Array.isArray(values)) {
|
|
814
|
+
for (let value of values) {
|
|
815
|
+
headers.append(key, value);
|
|
816
|
+
}
|
|
817
|
+
} else {
|
|
818
|
+
headers.set(key, values);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return headers;
|
|
823
|
+
}
|
|
824
|
+
function fromNodeRequest(nodeReq, nodeRes) {
|
|
825
|
+
let origin = nodeReq.headers.origin && "null" !== nodeReq.headers.origin ? nodeReq.headers.origin : `http://${nodeReq.headers.host}`;
|
|
826
|
+
invariant(
|
|
827
|
+
nodeReq.originalUrl,
|
|
828
|
+
"Expected `nodeReq.originalUrl` to be defined"
|
|
829
|
+
);
|
|
830
|
+
let url2 = new URL(nodeReq.originalUrl, origin);
|
|
831
|
+
let controller = new AbortController();
|
|
832
|
+
let init = {
|
|
833
|
+
method: nodeReq.method,
|
|
834
|
+
headers: fromNodeHeaders(nodeReq.headers),
|
|
835
|
+
signal: controller.signal
|
|
836
|
+
};
|
|
837
|
+
nodeRes.on("finish", () => controller = null);
|
|
838
|
+
nodeRes.on("close", () => controller?.abort());
|
|
839
|
+
if (nodeReq.method !== "GET" && nodeReq.method !== "HEAD") {
|
|
840
|
+
init.body = (0, import_node.createReadableStreamFromReadable)(nodeReq);
|
|
841
|
+
init.duplex = "half";
|
|
842
|
+
}
|
|
843
|
+
return new Request(url2.href, init);
|
|
844
|
+
}
|
|
845
|
+
async function toNodeRequest(res, nodeRes) {
|
|
846
|
+
nodeRes.statusCode = res.status;
|
|
847
|
+
nodeRes.statusMessage = res.statusText;
|
|
848
|
+
let cookiesStrings = [];
|
|
849
|
+
for (let [name, value] of res.headers) {
|
|
850
|
+
if (name === "set-cookie") {
|
|
851
|
+
cookiesStrings.push(...(0, import_set_cookie_parser.splitCookiesString)(value));
|
|
852
|
+
} else nodeRes.setHeader(name, value);
|
|
853
|
+
}
|
|
854
|
+
if (cookiesStrings.length) {
|
|
855
|
+
nodeRes.setHeader("set-cookie", cookiesStrings);
|
|
856
|
+
}
|
|
857
|
+
if (res.body) {
|
|
858
|
+
let responseBody = res.body;
|
|
859
|
+
let readable = import_node_stream.Readable.from(responseBody);
|
|
860
|
+
readable.pipe(nodeRes);
|
|
861
|
+
await (0, import_node_events.once)(readable, "end");
|
|
862
|
+
} else {
|
|
863
|
+
nodeRes.end();
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// vite/styles.ts
|
|
868
|
+
var path5 = __toESM(require("path"));
|
|
869
|
+
var import_react_router = require("react-router");
|
|
870
|
+
|
|
871
|
+
// vite/resolve-file-url.ts
|
|
872
|
+
var path4 = __toESM(require("path"));
|
|
873
|
+
var resolveFileUrl = ({ rootDirectory }, filePath) => {
|
|
874
|
+
let vite2 = getVite();
|
|
875
|
+
let relativePath = path4.relative(rootDirectory, filePath);
|
|
876
|
+
let isWithinRoot = !relativePath.startsWith("..") && !path4.isAbsolute(relativePath);
|
|
877
|
+
if (!isWithinRoot) {
|
|
878
|
+
return path4.posix.join("/@fs", vite2.normalizePath(filePath));
|
|
879
|
+
}
|
|
880
|
+
return "/" + vite2.normalizePath(relativePath);
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
// vite/styles.ts
|
|
884
|
+
var cssFileRegExp = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
|
|
885
|
+
var cssModulesRegExp = new RegExp(`\\.module${cssFileRegExp.source}`);
|
|
886
|
+
var isCssFile = (file) => cssFileRegExp.test(file);
|
|
887
|
+
var isCssModulesFile = (file) => cssModulesRegExp.test(file);
|
|
888
|
+
var cssUrlParamsWithoutSideEffects = ["url", "inline", "raw", "inline-css"];
|
|
889
|
+
var isCssUrlWithoutSideEffects = (url2) => {
|
|
890
|
+
let queryString = url2.split("?")[1];
|
|
891
|
+
if (!queryString) {
|
|
892
|
+
return false;
|
|
893
|
+
}
|
|
894
|
+
let params = new URLSearchParams(queryString);
|
|
895
|
+
for (let paramWithoutSideEffects of cssUrlParamsWithoutSideEffects) {
|
|
896
|
+
if (
|
|
897
|
+
// Parameter is blank and not explicitly set, i.e. "?url", not "?url="
|
|
898
|
+
params.get(paramWithoutSideEffects) === "" && !url2.includes(`?${paramWithoutSideEffects}=`) && !url2.includes(`&${paramWithoutSideEffects}=`)
|
|
899
|
+
) {
|
|
900
|
+
return true;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
return false;
|
|
904
|
+
};
|
|
905
|
+
var injectQuery = (url2, query) => url2.includes("?") ? url2.replace("?", `?${query}&`) : `${url2}?${query}`;
|
|
906
|
+
var getStylesForFiles = async ({
|
|
907
|
+
viteDevServer,
|
|
908
|
+
rootDirectory,
|
|
909
|
+
cssModulesManifest,
|
|
910
|
+
files
|
|
911
|
+
}) => {
|
|
912
|
+
let vite2 = getVite();
|
|
913
|
+
let viteMajor = parseInt(vite2.version.split(".")[0], 10);
|
|
914
|
+
let styles = {};
|
|
915
|
+
let deps = /* @__PURE__ */ new Set();
|
|
916
|
+
try {
|
|
917
|
+
for (let file of files) {
|
|
918
|
+
let normalizedPath = path5.resolve(rootDirectory, file).replace(/\\/g, "/");
|
|
919
|
+
let node = await viteDevServer.moduleGraph.getModuleById(normalizedPath);
|
|
920
|
+
if (!node) {
|
|
921
|
+
try {
|
|
922
|
+
await viteDevServer.transformRequest(
|
|
923
|
+
resolveFileUrl({ rootDirectory }, normalizedPath)
|
|
924
|
+
);
|
|
925
|
+
} catch (err2) {
|
|
926
|
+
console.error(err2);
|
|
927
|
+
}
|
|
928
|
+
node = await viteDevServer.moduleGraph.getModuleById(normalizedPath);
|
|
929
|
+
}
|
|
930
|
+
if (!node) {
|
|
931
|
+
console.log(`Could not resolve module for file: ${file}`);
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
934
|
+
await findDeps(viteDevServer, node, deps);
|
|
935
|
+
}
|
|
936
|
+
} catch (err2) {
|
|
937
|
+
console.error(err2);
|
|
938
|
+
}
|
|
939
|
+
for (let dep of deps) {
|
|
940
|
+
if (dep.file && isCssFile(dep.file) && !isCssUrlWithoutSideEffects(dep.url)) {
|
|
941
|
+
try {
|
|
942
|
+
let css = isCssModulesFile(dep.file) ? cssModulesManifest[dep.file] : (await viteDevServer.ssrLoadModule(
|
|
943
|
+
// We need the ?inline query in Vite v6 when loading CSS in SSR
|
|
944
|
+
// since it does not expose the default export for CSS in a
|
|
945
|
+
// server environment. This is to align with non-SSR
|
|
946
|
+
// environments. For backwards compatibility with v5 we keep
|
|
947
|
+
// using the URL without ?inline query because the HMR code was
|
|
948
|
+
// relying on the implicit SSR-client module graph relationship.
|
|
949
|
+
viteMajor >= 6 ? injectQuery(dep.url, "inline") : dep.url
|
|
950
|
+
)).default;
|
|
951
|
+
if (css === void 0) {
|
|
952
|
+
throw new Error();
|
|
953
|
+
}
|
|
954
|
+
styles[dep.url] = css;
|
|
955
|
+
} catch {
|
|
956
|
+
console.warn(`Could not load ${dep.file}`);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
return Object.entries(styles).map(([fileName, css], i) => [
|
|
961
|
+
`
|
|
962
|
+
/* ${fileName.replace(/\/\*/g, "/\\*").replace(/\*\//g, "*\\/")} */`,
|
|
963
|
+
css
|
|
964
|
+
]).flat().join("\n") || void 0;
|
|
965
|
+
};
|
|
966
|
+
var findDeps = async (vite2, node, deps) => {
|
|
967
|
+
let branches = [];
|
|
968
|
+
async function addFromNode(node2) {
|
|
969
|
+
if (!deps.has(node2)) {
|
|
970
|
+
deps.add(node2);
|
|
971
|
+
await findDeps(vite2, node2, deps);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
async function addFromUrl(url2) {
|
|
975
|
+
let node2 = await vite2.moduleGraph.getModuleByUrl(url2);
|
|
976
|
+
if (node2) {
|
|
977
|
+
await addFromNode(node2);
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
if (node.ssrTransformResult) {
|
|
981
|
+
if (node.ssrTransformResult.deps) {
|
|
982
|
+
node.ssrTransformResult.deps.forEach(
|
|
983
|
+
(url2) => branches.push(addFromUrl(url2))
|
|
984
|
+
);
|
|
985
|
+
}
|
|
986
|
+
} else {
|
|
987
|
+
node.importedModules.forEach((node2) => branches.push(addFromNode(node2)));
|
|
988
|
+
}
|
|
989
|
+
await Promise.all(branches);
|
|
990
|
+
};
|
|
991
|
+
var groupRoutesByParentId = (manifest) => {
|
|
992
|
+
let routes = {};
|
|
993
|
+
Object.values(manifest).forEach((route) => {
|
|
994
|
+
if (route) {
|
|
995
|
+
let parentId = route.parentId || "";
|
|
996
|
+
if (!routes[parentId]) {
|
|
997
|
+
routes[parentId] = [];
|
|
998
|
+
}
|
|
999
|
+
routes[parentId].push(route);
|
|
1000
|
+
}
|
|
1001
|
+
});
|
|
1002
|
+
return routes;
|
|
1003
|
+
};
|
|
1004
|
+
var createRoutes = (manifest, parentId = "", routesByParentId = groupRoutesByParentId(manifest)) => {
|
|
1005
|
+
return (routesByParentId[parentId] || []).map((route) => ({
|
|
1006
|
+
...route,
|
|
1007
|
+
children: createRoutes(manifest, route.id, routesByParentId)
|
|
1008
|
+
}));
|
|
1009
|
+
};
|
|
1010
|
+
var getStylesForUrl = async ({
|
|
1011
|
+
viteDevServer,
|
|
1012
|
+
rootDirectory,
|
|
1013
|
+
reactRouterConfig,
|
|
1014
|
+
entryClientFilePath,
|
|
1015
|
+
cssModulesManifest,
|
|
1016
|
+
build,
|
|
1017
|
+
url: url2
|
|
1018
|
+
}) => {
|
|
1019
|
+
if (url2 === void 0 || url2.includes("?_data=")) {
|
|
1020
|
+
return void 0;
|
|
1021
|
+
}
|
|
1022
|
+
let routes = createRoutes(build.routes);
|
|
1023
|
+
let appPath = path5.relative(process.cwd(), reactRouterConfig.appDirectory);
|
|
1024
|
+
let documentRouteFiles = (0, import_react_router.matchRoutes)(routes, url2, build.basename)?.map(
|
|
1025
|
+
(match) => path5.resolve(appPath, reactRouterConfig.routes[match.route.id].file)
|
|
1026
|
+
) ?? [];
|
|
1027
|
+
let styles = await getStylesForFiles({
|
|
1028
|
+
viteDevServer,
|
|
1029
|
+
rootDirectory,
|
|
1030
|
+
cssModulesManifest,
|
|
1031
|
+
files: [
|
|
1032
|
+
// Always include the client entry file when crawling the module graph for CSS
|
|
1033
|
+
path5.relative(rootDirectory, entryClientFilePath),
|
|
1034
|
+
// Then include any styles from the matched routes
|
|
1035
|
+
...documentRouteFiles
|
|
1036
|
+
]
|
|
1037
|
+
});
|
|
1038
|
+
return styles;
|
|
1039
|
+
};
|
|
1040
|
+
|
|
1041
|
+
// vite/virtual-module.ts
|
|
1042
|
+
function create(name) {
|
|
1043
|
+
let id = `virtual:react-router/${name}`;
|
|
1044
|
+
return {
|
|
1045
|
+
id,
|
|
1046
|
+
resolvedId: `\0${id}`,
|
|
1047
|
+
url: `/@id/__x00__${id}`
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// vite/combine-urls.ts
|
|
1052
|
+
function combineURLs(baseURL, relativeURL) {
|
|
1053
|
+
return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// vite/remove-exports.ts
|
|
1057
|
+
var import_babel_dead_code_elimination = require("babel-dead-code-elimination");
|
|
1058
|
+
var removeExports = (ast, exportsToRemove) => {
|
|
1059
|
+
let previouslyReferencedIdentifiers = (0, import_babel_dead_code_elimination.findReferencedIdentifiers)(ast);
|
|
1060
|
+
let exportsFiltered = false;
|
|
1061
|
+
let markedForRemoval = /* @__PURE__ */ new Set();
|
|
1062
|
+
traverse(ast, {
|
|
1063
|
+
ExportDeclaration(path7) {
|
|
1064
|
+
if (path7.node.type === "ExportNamedDeclaration") {
|
|
1065
|
+
if (path7.node.specifiers.length) {
|
|
1066
|
+
path7.node.specifiers = path7.node.specifiers.filter((specifier) => {
|
|
1067
|
+
if (specifier.type === "ExportSpecifier" && specifier.exported.type === "Identifier") {
|
|
1068
|
+
if (exportsToRemove.includes(specifier.exported.name)) {
|
|
1069
|
+
exportsFiltered = true;
|
|
1070
|
+
return false;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
return true;
|
|
1074
|
+
});
|
|
1075
|
+
if (path7.node.specifiers.length === 0) {
|
|
1076
|
+
markedForRemoval.add(path7);
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
if (path7.node.declaration?.type === "VariableDeclaration") {
|
|
1080
|
+
let declaration = path7.node.declaration;
|
|
1081
|
+
declaration.declarations = declaration.declarations.filter(
|
|
1082
|
+
(declaration2) => {
|
|
1083
|
+
if (declaration2.id.type === "Identifier" && exportsToRemove.includes(declaration2.id.name)) {
|
|
1084
|
+
exportsFiltered = true;
|
|
1085
|
+
return false;
|
|
1086
|
+
}
|
|
1087
|
+
if (declaration2.id.type === "ArrayPattern" || declaration2.id.type === "ObjectPattern") {
|
|
1088
|
+
validateDestructuredExports(declaration2.id, exportsToRemove);
|
|
1089
|
+
}
|
|
1090
|
+
return true;
|
|
1091
|
+
}
|
|
1092
|
+
);
|
|
1093
|
+
if (declaration.declarations.length === 0) {
|
|
1094
|
+
markedForRemoval.add(path7);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
if (path7.node.declaration?.type === "FunctionDeclaration") {
|
|
1098
|
+
let id = path7.node.declaration.id;
|
|
1099
|
+
if (id && exportsToRemove.includes(id.name)) {
|
|
1100
|
+
markedForRemoval.add(path7);
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
if (path7.node.declaration?.type === "ClassDeclaration") {
|
|
1104
|
+
let id = path7.node.declaration.id;
|
|
1105
|
+
if (id && exportsToRemove.includes(id.name)) {
|
|
1106
|
+
markedForRemoval.add(path7);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
if (path7.node.type === "ExportDefaultDeclaration" && exportsToRemove.includes("default")) {
|
|
1111
|
+
markedForRemoval.add(path7);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
});
|
|
1115
|
+
if (markedForRemoval.size > 0 || exportsFiltered) {
|
|
1116
|
+
for (let path7 of markedForRemoval) {
|
|
1117
|
+
path7.remove();
|
|
1118
|
+
}
|
|
1119
|
+
(0, import_babel_dead_code_elimination.deadCodeElimination)(ast, previouslyReferencedIdentifiers);
|
|
1120
|
+
}
|
|
1121
|
+
};
|
|
1122
|
+
function validateDestructuredExports(id, exportsToRemove) {
|
|
1123
|
+
if (id.type === "ArrayPattern") {
|
|
1124
|
+
for (let element of id.elements) {
|
|
1125
|
+
if (!element) {
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
if (element.type === "Identifier" && exportsToRemove.includes(element.name)) {
|
|
1129
|
+
throw invalidDestructureError(element.name);
|
|
1130
|
+
}
|
|
1131
|
+
if (element.type === "RestElement" && element.argument.type === "Identifier" && exportsToRemove.includes(element.argument.name)) {
|
|
1132
|
+
throw invalidDestructureError(element.argument.name);
|
|
1133
|
+
}
|
|
1134
|
+
if (element.type === "ArrayPattern" || element.type === "ObjectPattern") {
|
|
1135
|
+
validateDestructuredExports(element, exportsToRemove);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
if (id.type === "ObjectPattern") {
|
|
1140
|
+
for (let property of id.properties) {
|
|
1141
|
+
if (!property) {
|
|
1142
|
+
continue;
|
|
1143
|
+
}
|
|
1144
|
+
if (property.type === "ObjectProperty" && property.key.type === "Identifier") {
|
|
1145
|
+
if (property.value.type === "Identifier" && exportsToRemove.includes(property.value.name)) {
|
|
1146
|
+
throw invalidDestructureError(property.value.name);
|
|
1147
|
+
}
|
|
1148
|
+
if (property.value.type === "ArrayPattern" || property.value.type === "ObjectPattern") {
|
|
1149
|
+
validateDestructuredExports(property.value, exportsToRemove);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
if (property.type === "RestElement" && property.argument.type === "Identifier" && exportsToRemove.includes(property.argument.name)) {
|
|
1153
|
+
throw invalidDestructureError(property.argument.name);
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
function invalidDestructureError(name) {
|
|
1159
|
+
return new Error(`Cannot remove destructured export "${name}"`);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
// vite/with-props.ts
|
|
1163
|
+
var import_dedent2 = __toESM(require("dedent"));
|
|
1164
|
+
var vmod = create("with-props");
|
|
1165
|
+
var NAMED_COMPONENT_EXPORTS = ["HydrateFallback", "ErrorBoundary"];
|
|
1166
|
+
var plugin = {
|
|
1167
|
+
name: "react-router-with-props",
|
|
1168
|
+
enforce: "pre",
|
|
1169
|
+
resolveId(id) {
|
|
1170
|
+
if (id === vmod.id) return vmod.resolvedId;
|
|
1171
|
+
},
|
|
1172
|
+
async load(id) {
|
|
1173
|
+
if (id !== vmod.resolvedId) return;
|
|
1174
|
+
return import_dedent2.default`
|
|
1175
|
+
import { createElement as h } from "react";
|
|
1176
|
+
import { useActionData, useLoaderData, useMatches, useParams, useRouteError } from "react-router";
|
|
1177
|
+
|
|
1178
|
+
export function withComponentProps(Component) {
|
|
1179
|
+
return function Wrapped() {
|
|
1180
|
+
const props = {
|
|
1181
|
+
params: useParams(),
|
|
1182
|
+
loaderData: useLoaderData(),
|
|
1183
|
+
actionData: useActionData(),
|
|
1184
|
+
matches: useMatches(),
|
|
1185
|
+
};
|
|
1186
|
+
return h(Component, props);
|
|
1187
|
+
};
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
export function withHydrateFallbackProps(HydrateFallback) {
|
|
1191
|
+
return function Wrapped() {
|
|
1192
|
+
const props = {
|
|
1193
|
+
params: useParams(),
|
|
1194
|
+
};
|
|
1195
|
+
return h(HydrateFallback, props);
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
export function withErrorBoundaryProps(ErrorBoundary) {
|
|
1200
|
+
return function Wrapped() {
|
|
1201
|
+
const props = {
|
|
1202
|
+
params: useParams(),
|
|
1203
|
+
loaderData: useLoaderData(),
|
|
1204
|
+
actionData: useActionData(),
|
|
1205
|
+
error: useRouteError(),
|
|
1206
|
+
};
|
|
1207
|
+
return h(ErrorBoundary, props);
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
`;
|
|
1211
|
+
}
|
|
1212
|
+
};
|
|
1213
|
+
var transform = (ast) => {
|
|
1214
|
+
const hocs = [];
|
|
1215
|
+
function getHocUid(path7, hocName) {
|
|
1216
|
+
const uid = path7.scope.generateUidIdentifier(hocName);
|
|
1217
|
+
hocs.push([hocName, uid]);
|
|
1218
|
+
return uid;
|
|
1219
|
+
}
|
|
1220
|
+
traverse(ast, {
|
|
1221
|
+
ExportDeclaration(path7) {
|
|
1222
|
+
if (path7.isExportDefaultDeclaration()) {
|
|
1223
|
+
const declaration = path7.get("declaration");
|
|
1224
|
+
const expr = declaration.isExpression() ? declaration.node : declaration.isFunctionDeclaration() ? toFunctionExpression(declaration.node) : void 0;
|
|
1225
|
+
if (expr) {
|
|
1226
|
+
const uid = getHocUid(path7, "withComponentProps");
|
|
1227
|
+
declaration.replaceWith(t.callExpression(uid, [expr]));
|
|
1228
|
+
}
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (path7.isExportNamedDeclaration()) {
|
|
1232
|
+
const decl = path7.get("declaration");
|
|
1233
|
+
if (decl.isVariableDeclaration()) {
|
|
1234
|
+
decl.get("declarations").forEach((varDeclarator) => {
|
|
1235
|
+
const id = varDeclarator.get("id");
|
|
1236
|
+
const init = varDeclarator.get("init");
|
|
1237
|
+
const expr = init.node;
|
|
1238
|
+
if (!expr) return;
|
|
1239
|
+
if (!id.isIdentifier()) return;
|
|
1240
|
+
const { name } = id.node;
|
|
1241
|
+
if (!NAMED_COMPONENT_EXPORTS.includes(name)) return;
|
|
1242
|
+
const uid = getHocUid(path7, `with${name}Props`);
|
|
1243
|
+
init.replaceWith(t.callExpression(uid, [expr]));
|
|
1244
|
+
});
|
|
1245
|
+
return;
|
|
1246
|
+
}
|
|
1247
|
+
if (decl.isFunctionDeclaration()) {
|
|
1248
|
+
const { id } = decl.node;
|
|
1249
|
+
if (!id) return;
|
|
1250
|
+
const { name } = id;
|
|
1251
|
+
if (!NAMED_COMPONENT_EXPORTS.includes(name)) return;
|
|
1252
|
+
const uid = getHocUid(path7, `with${name}Props`);
|
|
1253
|
+
decl.replaceWith(
|
|
1254
|
+
t.variableDeclaration("const", [
|
|
1255
|
+
t.variableDeclarator(
|
|
1256
|
+
t.identifier(name),
|
|
1257
|
+
t.callExpression(uid, [toFunctionExpression(decl.node)])
|
|
1258
|
+
)
|
|
1259
|
+
])
|
|
1260
|
+
);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
});
|
|
1265
|
+
if (hocs.length > 0) {
|
|
1266
|
+
ast.program.body.unshift(
|
|
1267
|
+
t.importDeclaration(
|
|
1268
|
+
hocs.map(
|
|
1269
|
+
([name, identifier]) => t.importSpecifier(identifier, t.identifier(name))
|
|
1270
|
+
),
|
|
1271
|
+
t.stringLiteral(vmod.id)
|
|
1272
|
+
)
|
|
1273
|
+
);
|
|
1274
|
+
}
|
|
1275
|
+
};
|
|
1276
|
+
function toFunctionExpression(decl) {
|
|
1277
|
+
return t.functionExpression(
|
|
1278
|
+
decl.id,
|
|
1279
|
+
decl.params,
|
|
1280
|
+
decl.body,
|
|
1281
|
+
decl.generator,
|
|
1282
|
+
decl.async
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// vite/plugin.ts
|
|
1287
|
+
var SERVER_ONLY_ROUTE_EXPORTS = ["loader", "action", "headers"];
|
|
1288
|
+
var CLIENT_ROUTE_EXPORTS = [
|
|
1289
|
+
"clientAction",
|
|
1290
|
+
"clientLoader",
|
|
1291
|
+
"default",
|
|
1292
|
+
"ErrorBoundary",
|
|
1293
|
+
"handle",
|
|
1294
|
+
"HydrateFallback",
|
|
1295
|
+
"Layout",
|
|
1296
|
+
"links",
|
|
1297
|
+
"meta",
|
|
1298
|
+
"shouldRevalidate"
|
|
1299
|
+
];
|
|
1300
|
+
var BUILD_CLIENT_ROUTE_QUERY_STRING = "?__react-router-build-client-route";
|
|
1301
|
+
var virtualHmrRuntime = create("hmr-runtime");
|
|
1302
|
+
var virtualInjectHmrRuntime = create("inject-hmr-runtime");
|
|
1303
|
+
var resolveRelativeRouteFilePath = (route, reactRouterConfig) => {
|
|
1304
|
+
let vite2 = getVite();
|
|
1305
|
+
let file = route.file;
|
|
1306
|
+
let fullPath = path6.resolve(reactRouterConfig.appDirectory, file);
|
|
1307
|
+
return vite2.normalizePath(fullPath);
|
|
1308
|
+
};
|
|
1309
|
+
var virtual = {
|
|
1310
|
+
serverBuild: create("server-build"),
|
|
1311
|
+
serverManifest: create("server-manifest"),
|
|
1312
|
+
browserManifest: create("browser-manifest")
|
|
1313
|
+
};
|
|
1314
|
+
var invalidateVirtualModules = (viteDevServer) => {
|
|
1315
|
+
Object.values(virtual).forEach((vmod2) => {
|
|
1316
|
+
let mod = viteDevServer.moduleGraph.getModuleById(vmod2.resolvedId);
|
|
1317
|
+
if (mod) {
|
|
1318
|
+
viteDevServer.moduleGraph.invalidateModule(mod);
|
|
1319
|
+
}
|
|
1320
|
+
});
|
|
1321
|
+
};
|
|
1322
|
+
var getHash = (source, maxLength) => {
|
|
1323
|
+
let hash = (0, import_node_crypto.createHash)("sha256").update(source).digest("hex");
|
|
1324
|
+
return typeof maxLength === "number" ? hash.slice(0, maxLength) : hash;
|
|
1325
|
+
};
|
|
1326
|
+
var resolveChunk = (ctx, viteManifest, absoluteFilePath) => {
|
|
1327
|
+
let vite2 = getVite();
|
|
1328
|
+
let rootRelativeFilePath = vite2.normalizePath(
|
|
1329
|
+
path6.relative(ctx.rootDirectory, absoluteFilePath)
|
|
1330
|
+
);
|
|
1331
|
+
let entryChunk = viteManifest[rootRelativeFilePath + BUILD_CLIENT_ROUTE_QUERY_STRING] ?? viteManifest[rootRelativeFilePath];
|
|
1332
|
+
if (!entryChunk) {
|
|
1333
|
+
let knownManifestKeys = Object.keys(viteManifest).map((key) => '"' + key + '"').join(", ");
|
|
1334
|
+
throw new Error(
|
|
1335
|
+
`No manifest entry found for "${rootRelativeFilePath}". Known manifest keys: ${knownManifestKeys}`
|
|
1336
|
+
);
|
|
1337
|
+
}
|
|
1338
|
+
return entryChunk;
|
|
1339
|
+
};
|
|
1340
|
+
var getReactRouterManifestBuildAssets = (ctx, viteManifest, entryFilePath, prependedAssetFilePaths = []) => {
|
|
1341
|
+
let entryChunk = resolveChunk(ctx, viteManifest, entryFilePath);
|
|
1342
|
+
let prependedAssetChunks = prependedAssetFilePaths.map(
|
|
1343
|
+
(filePath) => resolveChunk(ctx, viteManifest, filePath)
|
|
1344
|
+
);
|
|
1345
|
+
let chunks = resolveDependantChunks(viteManifest, [
|
|
1346
|
+
...prependedAssetChunks,
|
|
1347
|
+
entryChunk
|
|
1348
|
+
]);
|
|
1349
|
+
return {
|
|
1350
|
+
module: `${ctx.publicPath}${entryChunk.file}`,
|
|
1351
|
+
imports: dedupe(chunks.flatMap((e) => e.imports ?? [])).map((imported) => {
|
|
1352
|
+
return `${ctx.publicPath}${viteManifest[imported].file}`;
|
|
1353
|
+
}) ?? [],
|
|
1354
|
+
css: dedupe(chunks.flatMap((e) => e.css ?? [])).map((href) => {
|
|
1355
|
+
return `${ctx.publicPath}${href}`;
|
|
1356
|
+
}) ?? []
|
|
1357
|
+
};
|
|
1358
|
+
};
|
|
1359
|
+
function resolveDependantChunks(viteManifest, entryChunks) {
|
|
1360
|
+
let chunks = /* @__PURE__ */ new Set();
|
|
1361
|
+
function walk(chunk) {
|
|
1362
|
+
if (chunks.has(chunk)) {
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
chunks.add(chunk);
|
|
1366
|
+
if (chunk.imports) {
|
|
1367
|
+
for (let importKey of chunk.imports) {
|
|
1368
|
+
walk(viteManifest[importKey]);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
for (let entryChunk of entryChunks) {
|
|
1373
|
+
walk(entryChunk);
|
|
1374
|
+
}
|
|
1375
|
+
return Array.from(chunks);
|
|
1376
|
+
}
|
|
1377
|
+
function dedupe(array2) {
|
|
1378
|
+
return [...new Set(array2)];
|
|
1379
|
+
}
|
|
1380
|
+
var writeFileSafe = async (file, contents) => {
|
|
1381
|
+
await fse.ensureDir(path6.dirname(file));
|
|
1382
|
+
await fse.writeFile(file, contents);
|
|
1383
|
+
};
|
|
1384
|
+
var getRouteManifestModuleExports = async (viteChildCompiler, ctx) => {
|
|
1385
|
+
let entries = await Promise.all(
|
|
1386
|
+
Object.entries(ctx.reactRouterConfig.routes).map(async ([key, route]) => {
|
|
1387
|
+
let sourceExports = await getRouteModuleExports(
|
|
1388
|
+
viteChildCompiler,
|
|
1389
|
+
ctx,
|
|
1390
|
+
route.file
|
|
1391
|
+
);
|
|
1392
|
+
return [key, sourceExports];
|
|
1393
|
+
})
|
|
1394
|
+
);
|
|
1395
|
+
return Object.fromEntries(entries);
|
|
1396
|
+
};
|
|
1397
|
+
var getRouteModuleExports = async (viteChildCompiler, ctx, routeFile, readRouteFile) => {
|
|
1398
|
+
if (!viteChildCompiler) {
|
|
1399
|
+
throw new Error("Vite child compiler not found");
|
|
1400
|
+
}
|
|
1401
|
+
let ssr = true;
|
|
1402
|
+
let { pluginContainer, moduleGraph } = viteChildCompiler;
|
|
1403
|
+
let routePath = path6.resolve(ctx.reactRouterConfig.appDirectory, routeFile);
|
|
1404
|
+
let url2 = resolveFileUrl(ctx, routePath);
|
|
1405
|
+
let resolveId = async () => {
|
|
1406
|
+
let result = await pluginContainer.resolveId(url2, void 0, { ssr });
|
|
1407
|
+
if (!result) throw new Error(`Could not resolve module ID for ${url2}`);
|
|
1408
|
+
return result.id;
|
|
1409
|
+
};
|
|
1410
|
+
let [id, code] = await Promise.all([
|
|
1411
|
+
resolveId(),
|
|
1412
|
+
readRouteFile?.() ?? fse.readFile(routePath, "utf-8"),
|
|
1413
|
+
// pluginContainer.transform(...) fails if we don't do this first:
|
|
1414
|
+
moduleGraph.ensureEntryFromUrl(url2, ssr)
|
|
1415
|
+
]);
|
|
1416
|
+
let transformed = await pluginContainer.transform(code, id, { ssr });
|
|
1417
|
+
let [, exports2] = (0, import_es_module_lexer.parse)(transformed.code);
|
|
1418
|
+
let exportNames = exports2.map((e) => e.n);
|
|
1419
|
+
return exportNames;
|
|
1420
|
+
};
|
|
1421
|
+
var getServerBundleBuildConfig = (viteUserConfig) => {
|
|
1422
|
+
if (!("__reactRouterServerBundleBuildConfig" in viteUserConfig) || !viteUserConfig.__reactRouterServerBundleBuildConfig) {
|
|
1423
|
+
return null;
|
|
1424
|
+
}
|
|
1425
|
+
return viteUserConfig.__reactRouterServerBundleBuildConfig;
|
|
1426
|
+
};
|
|
1427
|
+
var getServerBuildDirectory = (ctx) => path6.join(
|
|
1428
|
+
ctx.reactRouterConfig.buildDirectory,
|
|
1429
|
+
"server",
|
|
1430
|
+
...ctx.serverBundleBuildConfig ? [ctx.serverBundleBuildConfig.serverBundleId] : []
|
|
1431
|
+
);
|
|
1432
|
+
var getClientBuildDirectory = (reactRouterConfig) => path6.join(reactRouterConfig.buildDirectory, "client");
|
|
1433
|
+
var defaultEntriesDir = path6.resolve(
|
|
1434
|
+
path6.dirname(require.resolve("@react-router/dev/package.json")),
|
|
1435
|
+
"dist",
|
|
1436
|
+
"config",
|
|
1437
|
+
"defaults"
|
|
1438
|
+
);
|
|
1439
|
+
var defaultEntries = fse.readdirSync(defaultEntriesDir).map((filename3) => path6.join(defaultEntriesDir, filename3));
|
|
1440
|
+
invariant(defaultEntries.length > 0, "No default entries found");
|
|
1441
|
+
var reactRouterDevLoadContext = () => ({});
|
|
1442
|
+
var reactRouterVitePlugin = () => {
|
|
1443
|
+
let rootDirectory;
|
|
1444
|
+
let viteCommand;
|
|
1445
|
+
let viteUserConfig;
|
|
1446
|
+
let viteConfigEnv;
|
|
1447
|
+
let viteConfig;
|
|
1448
|
+
let cssModulesManifest = {};
|
|
1449
|
+
let viteChildCompiler = null;
|
|
1450
|
+
let reactRouterConfigLoader;
|
|
1451
|
+
let typegenWatcherPromise;
|
|
1452
|
+
let logger;
|
|
1453
|
+
let firstLoad = true;
|
|
1454
|
+
let ctx;
|
|
1455
|
+
let updatePluginContext = async () => {
|
|
1456
|
+
let reactRouterConfig;
|
|
1457
|
+
let reactRouterConfigResult = await reactRouterConfigLoader.getConfig();
|
|
1458
|
+
if (reactRouterConfigResult.ok) {
|
|
1459
|
+
reactRouterConfig = reactRouterConfigResult.value;
|
|
1460
|
+
} else {
|
|
1461
|
+
logger.error(reactRouterConfigResult.error);
|
|
1462
|
+
if (firstLoad) {
|
|
1463
|
+
process.exit(1);
|
|
1464
|
+
}
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
let { entryClientFilePath, entryServerFilePath } = await resolveEntryFiles({
|
|
1468
|
+
rootDirectory,
|
|
1469
|
+
reactRouterConfig
|
|
1470
|
+
});
|
|
1471
|
+
let publicPath = viteUserConfig.base ?? "/";
|
|
1472
|
+
if (reactRouterConfig.basename !== "/" && viteCommand === "serve" && !viteUserConfig.server?.middlewareMode && !reactRouterConfig.basename.startsWith(publicPath)) {
|
|
1473
|
+
logger.error(
|
|
1474
|
+
import_picocolors3.default.red(
|
|
1475
|
+
"When using the React Router `basename` and the Vite `base` config, the `basename` config must begin with `base` for the default Vite dev server."
|
|
1476
|
+
)
|
|
1477
|
+
);
|
|
1478
|
+
process.exit(1);
|
|
1479
|
+
}
|
|
1480
|
+
let viteManifestEnabled = viteUserConfig.build?.manifest === true;
|
|
1481
|
+
let ssrBuildCtx = viteConfigEnv.isSsrBuild && viteCommand === "build" ? {
|
|
1482
|
+
isSsrBuild: true,
|
|
1483
|
+
getReactRouterServerManifest: async () => (await generateReactRouterManifestsForBuild()).reactRouterServerManifest,
|
|
1484
|
+
serverBundleBuildConfig: getServerBundleBuildConfig(viteUserConfig)
|
|
1485
|
+
} : { isSsrBuild: false };
|
|
1486
|
+
firstLoad = false;
|
|
1487
|
+
ctx = {
|
|
1488
|
+
reactRouterConfig,
|
|
1489
|
+
rootDirectory,
|
|
1490
|
+
entryClientFilePath,
|
|
1491
|
+
entryServerFilePath,
|
|
1492
|
+
publicPath,
|
|
1493
|
+
viteManifestEnabled,
|
|
1494
|
+
...ssrBuildCtx
|
|
1495
|
+
};
|
|
1496
|
+
};
|
|
1497
|
+
let pluginIndex = (pluginName) => {
|
|
1498
|
+
invariant(viteConfig);
|
|
1499
|
+
return viteConfig.plugins.findIndex((plugin2) => plugin2.name === pluginName);
|
|
1500
|
+
};
|
|
1501
|
+
let getServerEntry = async () => {
|
|
1502
|
+
invariant(viteConfig, "viteconfig required to generate the server entry");
|
|
1503
|
+
let routes = ctx.serverBundleBuildConfig ? (
|
|
1504
|
+
// For server bundle builds, the server build should only import the
|
|
1505
|
+
// routes for this bundle rather than importing all routes
|
|
1506
|
+
ctx.serverBundleBuildConfig.routes
|
|
1507
|
+
) : (
|
|
1508
|
+
// Otherwise, all routes are imported as usual
|
|
1509
|
+
ctx.reactRouterConfig.routes
|
|
1510
|
+
);
|
|
1511
|
+
return `
|
|
1512
|
+
import * as entryServer from ${JSON.stringify(
|
|
1513
|
+
resolveFileUrl(ctx, ctx.entryServerFilePath)
|
|
1514
|
+
)};
|
|
1515
|
+
${Object.keys(routes).map((key, index) => {
|
|
1516
|
+
let route = routes[key];
|
|
1517
|
+
return `import * as route${index} from ${JSON.stringify(
|
|
1518
|
+
resolveFileUrl(
|
|
1519
|
+
ctx,
|
|
1520
|
+
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
|
|
1521
|
+
)
|
|
1522
|
+
)};`;
|
|
1523
|
+
}).join("\n")}
|
|
1524
|
+
export { default as assets } from ${JSON.stringify(
|
|
1525
|
+
virtual.serverManifest.id
|
|
1526
|
+
)};
|
|
1527
|
+
export const assetsBuildDirectory = ${JSON.stringify(
|
|
1528
|
+
path6.relative(
|
|
1529
|
+
ctx.rootDirectory,
|
|
1530
|
+
getClientBuildDirectory(ctx.reactRouterConfig)
|
|
1531
|
+
)
|
|
1532
|
+
)};
|
|
1533
|
+
export const basename = ${JSON.stringify(ctx.reactRouterConfig.basename)};
|
|
1534
|
+
export const future = ${JSON.stringify(ctx.reactRouterConfig.future)};
|
|
1535
|
+
export const isSpaMode = ${!ctx.reactRouterConfig.ssr && ctx.reactRouterConfig.prerender == null};
|
|
1536
|
+
export const publicPath = ${JSON.stringify(ctx.publicPath)};
|
|
1537
|
+
export const entry = { module: entryServer };
|
|
1538
|
+
export const routes = {
|
|
1539
|
+
${Object.keys(routes).map((key, index) => {
|
|
1540
|
+
let route = routes[key];
|
|
1541
|
+
return `${JSON.stringify(key)}: {
|
|
1542
|
+
id: ${JSON.stringify(route.id)},
|
|
1543
|
+
parentId: ${JSON.stringify(route.parentId)},
|
|
1544
|
+
path: ${JSON.stringify(route.path)},
|
|
1545
|
+
index: ${JSON.stringify(route.index)},
|
|
1546
|
+
caseSensitive: ${JSON.stringify(route.caseSensitive)},
|
|
1547
|
+
module: route${index}
|
|
1548
|
+
}`;
|
|
1549
|
+
}).join(",\n ")}
|
|
1550
|
+
};`;
|
|
1551
|
+
};
|
|
1552
|
+
let loadViteManifest = async (directory) => {
|
|
1553
|
+
let manifestContents = await fse.readFile(
|
|
1554
|
+
path6.resolve(directory, ".vite", "manifest.json"),
|
|
1555
|
+
"utf-8"
|
|
1556
|
+
);
|
|
1557
|
+
return JSON.parse(manifestContents);
|
|
1558
|
+
};
|
|
1559
|
+
let hasDependency = (name) => {
|
|
1560
|
+
try {
|
|
1561
|
+
return Boolean(require.resolve(name, { paths: [ctx.rootDirectory] }));
|
|
1562
|
+
} catch (err2) {
|
|
1563
|
+
return false;
|
|
1564
|
+
}
|
|
1565
|
+
};
|
|
1566
|
+
let getViteManifestAssetPaths = (viteManifest) => {
|
|
1567
|
+
let cssUrlPaths = Object.values(viteManifest).filter((chunk) => chunk.file.endsWith(".css")).map((chunk) => chunk.file);
|
|
1568
|
+
let chunkAssetPaths = Object.values(viteManifest).flatMap(
|
|
1569
|
+
(chunk) => chunk.assets ?? []
|
|
1570
|
+
);
|
|
1571
|
+
return /* @__PURE__ */ new Set([...cssUrlPaths, ...chunkAssetPaths]);
|
|
1572
|
+
};
|
|
1573
|
+
let generateReactRouterManifestsForBuild = async () => {
|
|
1574
|
+
invariant(viteConfig);
|
|
1575
|
+
let viteManifest = await loadViteManifest(
|
|
1576
|
+
getClientBuildDirectory(ctx.reactRouterConfig)
|
|
1577
|
+
);
|
|
1578
|
+
let entry = getReactRouterManifestBuildAssets(
|
|
1579
|
+
ctx,
|
|
1580
|
+
viteManifest,
|
|
1581
|
+
ctx.entryClientFilePath
|
|
1582
|
+
);
|
|
1583
|
+
let browserRoutes = {};
|
|
1584
|
+
let serverRoutes = {};
|
|
1585
|
+
let routeManifestExports = await getRouteManifestModuleExports(
|
|
1586
|
+
viteChildCompiler,
|
|
1587
|
+
ctx
|
|
1588
|
+
);
|
|
1589
|
+
for (let [key, route] of Object.entries(ctx.reactRouterConfig.routes)) {
|
|
1590
|
+
let routeFilePath = path6.join(
|
|
1591
|
+
ctx.reactRouterConfig.appDirectory,
|
|
1592
|
+
route.file
|
|
1593
|
+
);
|
|
1594
|
+
let sourceExports = routeManifestExports[key];
|
|
1595
|
+
let isRootRoute = route.parentId === void 0;
|
|
1596
|
+
let routeManifestEntry = {
|
|
1597
|
+
id: route.id,
|
|
1598
|
+
parentId: route.parentId,
|
|
1599
|
+
path: route.path,
|
|
1600
|
+
index: route.index,
|
|
1601
|
+
caseSensitive: route.caseSensitive,
|
|
1602
|
+
hasAction: sourceExports.includes("action"),
|
|
1603
|
+
hasLoader: sourceExports.includes("loader"),
|
|
1604
|
+
hasClientAction: sourceExports.includes("clientAction"),
|
|
1605
|
+
hasClientLoader: sourceExports.includes("clientLoader"),
|
|
1606
|
+
hasErrorBoundary: sourceExports.includes("ErrorBoundary"),
|
|
1607
|
+
...getReactRouterManifestBuildAssets(
|
|
1608
|
+
ctx,
|
|
1609
|
+
viteManifest,
|
|
1610
|
+
routeFilePath,
|
|
1611
|
+
// If this is the root route, we also need to include assets from the
|
|
1612
|
+
// client entry file as this is a common way for consumers to import
|
|
1613
|
+
// global reset styles, etc.
|
|
1614
|
+
isRootRoute ? [ctx.entryClientFilePath] : []
|
|
1615
|
+
)
|
|
1616
|
+
};
|
|
1617
|
+
browserRoutes[key] = routeManifestEntry;
|
|
1618
|
+
let serverBundleRoutes = ctx.serverBundleBuildConfig?.routes;
|
|
1619
|
+
if (!serverBundleRoutes || serverBundleRoutes[key]) {
|
|
1620
|
+
serverRoutes[key] = routeManifestEntry;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
let fingerprintedValues = { entry, routes: browserRoutes };
|
|
1624
|
+
let version = getHash(JSON.stringify(fingerprintedValues), 8);
|
|
1625
|
+
let manifestPath = path6.posix.join(
|
|
1626
|
+
viteConfig.build.assetsDir,
|
|
1627
|
+
`manifest-${version}.js`
|
|
1628
|
+
);
|
|
1629
|
+
let url2 = `${ctx.publicPath}${manifestPath}`;
|
|
1630
|
+
let nonFingerprintedValues = { url: url2, version };
|
|
1631
|
+
let reactRouterBrowserManifest = {
|
|
1632
|
+
...fingerprintedValues,
|
|
1633
|
+
...nonFingerprintedValues
|
|
1634
|
+
};
|
|
1635
|
+
await writeFileSafe(
|
|
1636
|
+
path6.join(getClientBuildDirectory(ctx.reactRouterConfig), manifestPath),
|
|
1637
|
+
`window.__reactRouterManifest=${JSON.stringify(
|
|
1638
|
+
reactRouterBrowserManifest
|
|
1639
|
+
)};`
|
|
1640
|
+
);
|
|
1641
|
+
let reactRouterServerManifest = {
|
|
1642
|
+
...reactRouterBrowserManifest,
|
|
1643
|
+
routes: serverRoutes
|
|
1644
|
+
};
|
|
1645
|
+
return {
|
|
1646
|
+
reactRouterBrowserManifest,
|
|
1647
|
+
reactRouterServerManifest
|
|
1648
|
+
};
|
|
1649
|
+
};
|
|
1650
|
+
let getReactRouterManifestForDev = async () => {
|
|
1651
|
+
let routes = {};
|
|
1652
|
+
let routeManifestExports = await getRouteManifestModuleExports(
|
|
1653
|
+
viteChildCompiler,
|
|
1654
|
+
ctx
|
|
1655
|
+
);
|
|
1656
|
+
for (let [key, route] of Object.entries(ctx.reactRouterConfig.routes)) {
|
|
1657
|
+
let sourceExports = routeManifestExports[key];
|
|
1658
|
+
routes[key] = {
|
|
1659
|
+
id: route.id,
|
|
1660
|
+
parentId: route.parentId,
|
|
1661
|
+
path: route.path,
|
|
1662
|
+
index: route.index,
|
|
1663
|
+
caseSensitive: route.caseSensitive,
|
|
1664
|
+
module: combineURLs(
|
|
1665
|
+
ctx.publicPath,
|
|
1666
|
+
resolveFileUrl(
|
|
1667
|
+
ctx,
|
|
1668
|
+
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
|
|
1669
|
+
)
|
|
1670
|
+
),
|
|
1671
|
+
hasAction: sourceExports.includes("action"),
|
|
1672
|
+
hasLoader: sourceExports.includes("loader"),
|
|
1673
|
+
hasClientAction: sourceExports.includes("clientAction"),
|
|
1674
|
+
hasClientLoader: sourceExports.includes("clientLoader"),
|
|
1675
|
+
hasErrorBoundary: sourceExports.includes("ErrorBoundary"),
|
|
1676
|
+
imports: []
|
|
1677
|
+
};
|
|
1678
|
+
}
|
|
1679
|
+
return {
|
|
1680
|
+
version: String(Math.random()),
|
|
1681
|
+
url: combineURLs(ctx.publicPath, virtual.browserManifest.url),
|
|
1682
|
+
hmr: {
|
|
1683
|
+
runtime: combineURLs(ctx.publicPath, virtualInjectHmrRuntime.url)
|
|
1684
|
+
},
|
|
1685
|
+
entry: {
|
|
1686
|
+
module: combineURLs(
|
|
1687
|
+
ctx.publicPath,
|
|
1688
|
+
resolveFileUrl(ctx, ctx.entryClientFilePath)
|
|
1689
|
+
),
|
|
1690
|
+
imports: []
|
|
1691
|
+
},
|
|
1692
|
+
routes
|
|
1693
|
+
};
|
|
1694
|
+
};
|
|
1695
|
+
return [
|
|
1696
|
+
{
|
|
1697
|
+
name: "react-router",
|
|
1698
|
+
config: async (_viteUserConfig, _viteConfigEnv) => {
|
|
1699
|
+
await preloadVite();
|
|
1700
|
+
let vite2 = getVite();
|
|
1701
|
+
viteUserConfig = _viteUserConfig;
|
|
1702
|
+
viteConfigEnv = _viteConfigEnv;
|
|
1703
|
+
viteCommand = viteConfigEnv.command;
|
|
1704
|
+
let viteClientConditions = [
|
|
1705
|
+
...vite2.defaultClientConditions ?? []
|
|
1706
|
+
];
|
|
1707
|
+
let { moduleSyncEnabled } = await import("../config/module-sync-enabled/index.mjs");
|
|
1708
|
+
let viteServerConditions = [
|
|
1709
|
+
...vite2.defaultServerConditions ?? [],
|
|
1710
|
+
...moduleSyncEnabled ? ["module-sync"] : []
|
|
1711
|
+
];
|
|
1712
|
+
logger = vite2.createLogger(viteUserConfig.logLevel, {
|
|
1713
|
+
prefix: "[react-router]"
|
|
1714
|
+
});
|
|
1715
|
+
rootDirectory = viteUserConfig.root ?? process.env.REACT_ROUTER_ROOT ?? process.cwd();
|
|
1716
|
+
if (viteCommand === "serve") {
|
|
1717
|
+
typegenWatcherPromise = watch(rootDirectory, {
|
|
1718
|
+
// ignore `info` logs from typegen since they are redundant when Vite plugin logs are active
|
|
1719
|
+
logger: vite2.createLogger("warn", { prefix: "[react-router]" })
|
|
1720
|
+
});
|
|
1721
|
+
}
|
|
1722
|
+
reactRouterConfigLoader = await createConfigLoader({
|
|
1723
|
+
rootDirectory,
|
|
1724
|
+
watch: viteCommand === "serve"
|
|
1725
|
+
});
|
|
1726
|
+
await updatePluginContext();
|
|
1727
|
+
Object.assign(
|
|
1728
|
+
process.env,
|
|
1729
|
+
vite2.loadEnv(
|
|
1730
|
+
viteConfigEnv.mode,
|
|
1731
|
+
ctx.rootDirectory,
|
|
1732
|
+
// We override default prefix of "VITE_" with a blank string since
|
|
1733
|
+
// we're targeting the server, so we want to load all environment
|
|
1734
|
+
// variables, not just those explicitly marked for the client
|
|
1735
|
+
""
|
|
1736
|
+
)
|
|
1737
|
+
);
|
|
1738
|
+
let baseRollupOptions = {
|
|
1739
|
+
// Silence Rollup "use client" warnings
|
|
1740
|
+
// Adapted from https://github.com/vitejs/vite-plugin-react/pull/144
|
|
1741
|
+
onwarn(warning, defaultHandler) {
|
|
1742
|
+
if (warning.code === "MODULE_LEVEL_DIRECTIVE" && warning.message.includes("use client")) {
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1745
|
+
if (viteUserConfig.build?.rollupOptions?.onwarn) {
|
|
1746
|
+
viteUserConfig.build.rollupOptions.onwarn(
|
|
1747
|
+
warning,
|
|
1748
|
+
defaultHandler
|
|
1749
|
+
);
|
|
1750
|
+
} else {
|
|
1751
|
+
defaultHandler(warning);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
return {
|
|
1756
|
+
__reactRouterPluginContext: ctx,
|
|
1757
|
+
appType: viteCommand === "serve" && viteConfigEnv.mode === "production" && ctx.reactRouterConfig.ssr === false ? "spa" : "custom",
|
|
1758
|
+
ssr: {
|
|
1759
|
+
external: ssrExternals,
|
|
1760
|
+
resolve: {
|
|
1761
|
+
conditions: viteCommand === "build" ? viteServerConditions : ["development", ...viteServerConditions],
|
|
1762
|
+
externalConditions: viteCommand === "build" ? viteServerConditions : ["development", ...viteServerConditions]
|
|
1763
|
+
}
|
|
1764
|
+
},
|
|
1765
|
+
optimizeDeps: {
|
|
1766
|
+
entries: ctx.reactRouterConfig.future.unstable_optimizeDeps ? [
|
|
1767
|
+
ctx.entryClientFilePath,
|
|
1768
|
+
...Object.values(ctx.reactRouterConfig.routes).map(
|
|
1769
|
+
(route) => path6.join(ctx.reactRouterConfig.appDirectory, route.file)
|
|
1770
|
+
)
|
|
1771
|
+
] : [],
|
|
1772
|
+
include: [
|
|
1773
|
+
// Pre-bundle React dependencies to avoid React duplicates,
|
|
1774
|
+
// even if React dependencies are not direct dependencies.
|
|
1775
|
+
// https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
|
|
1776
|
+
"react",
|
|
1777
|
+
"react/jsx-runtime",
|
|
1778
|
+
"react/jsx-dev-runtime",
|
|
1779
|
+
"react-dom",
|
|
1780
|
+
"react-dom/client",
|
|
1781
|
+
// Pre-bundle router dependencies to avoid router duplicates.
|
|
1782
|
+
// Mismatching routers cause `Error: You must render this element inside a <Remix> element`.
|
|
1783
|
+
"react-router",
|
|
1784
|
+
"react-router/dom",
|
|
1785
|
+
// Check to avoid "Failed to resolve dependency: react-router-dom, present in 'optimizeDeps.include'"
|
|
1786
|
+
...hasDependency("react-router-dom") ? ["react-router-dom"] : []
|
|
1787
|
+
]
|
|
1788
|
+
},
|
|
1789
|
+
esbuild: {
|
|
1790
|
+
jsx: "automatic",
|
|
1791
|
+
jsxDev: viteCommand !== "build"
|
|
1792
|
+
},
|
|
1793
|
+
resolve: {
|
|
1794
|
+
dedupe: [
|
|
1795
|
+
// https://react.dev/warnings/invalid-hook-call-warning#duplicate-react
|
|
1796
|
+
"react",
|
|
1797
|
+
"react-dom",
|
|
1798
|
+
// see description for `optimizeDeps.include`
|
|
1799
|
+
"react-router",
|
|
1800
|
+
"react-router/dom",
|
|
1801
|
+
"react-router-dom"
|
|
1802
|
+
],
|
|
1803
|
+
conditions: viteCommand === "build" ? viteClientConditions : ["development", ...viteClientConditions]
|
|
1804
|
+
},
|
|
1805
|
+
base: viteUserConfig.base,
|
|
1806
|
+
// When consumer provides an allow list for files that can be read by
|
|
1807
|
+
// the server, ensure that the default entry files are included.
|
|
1808
|
+
// If we don't do this and a default entry file is used, the server
|
|
1809
|
+
// will throw an error that the file is not allowed to be read.
|
|
1810
|
+
// https://vitejs.dev/config/server-options#server-fs-allow
|
|
1811
|
+
server: viteUserConfig.server?.fs?.allow ? { fs: { allow: defaultEntries } } : void 0,
|
|
1812
|
+
// Vite config options for building
|
|
1813
|
+
...viteCommand === "build" ? {
|
|
1814
|
+
build: {
|
|
1815
|
+
cssMinify: viteUserConfig.build?.cssMinify ?? true,
|
|
1816
|
+
...!viteConfigEnv.isSsrBuild ? {
|
|
1817
|
+
manifest: true,
|
|
1818
|
+
outDir: getClientBuildDirectory(ctx.reactRouterConfig),
|
|
1819
|
+
rollupOptions: {
|
|
1820
|
+
...baseRollupOptions,
|
|
1821
|
+
preserveEntrySignatures: "exports-only",
|
|
1822
|
+
input: [
|
|
1823
|
+
ctx.entryClientFilePath,
|
|
1824
|
+
...Object.values(ctx.reactRouterConfig.routes).map(
|
|
1825
|
+
(route) => `${path6.resolve(
|
|
1826
|
+
ctx.reactRouterConfig.appDirectory,
|
|
1827
|
+
route.file
|
|
1828
|
+
)}${BUILD_CLIENT_ROUTE_QUERY_STRING}`
|
|
1829
|
+
)
|
|
1830
|
+
]
|
|
1831
|
+
}
|
|
1832
|
+
} : {
|
|
1833
|
+
// We move SSR-only assets to client assets. Note that the
|
|
1834
|
+
// SSR build can also emit code-split JS files (e.g. by
|
|
1835
|
+
// dynamic import) under the same assets directory
|
|
1836
|
+
// regardless of "ssrEmitAssets" option, so we also need to
|
|
1837
|
+
// keep these JS files have to be kept as-is.
|
|
1838
|
+
ssrEmitAssets: true,
|
|
1839
|
+
copyPublicDir: false,
|
|
1840
|
+
// Assets in the public directory are only used by the client
|
|
1841
|
+
manifest: true,
|
|
1842
|
+
// We need the manifest to detect SSR-only assets
|
|
1843
|
+
outDir: getServerBuildDirectory(ctx),
|
|
1844
|
+
rollupOptions: {
|
|
1845
|
+
...baseRollupOptions,
|
|
1846
|
+
preserveEntrySignatures: "exports-only",
|
|
1847
|
+
input: viteUserConfig.build?.rollupOptions?.input ?? virtual.serverBuild.id,
|
|
1848
|
+
output: {
|
|
1849
|
+
entryFileNames: ctx.reactRouterConfig.serverBuildFile,
|
|
1850
|
+
format: ctx.reactRouterConfig.serverModuleFormat
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
} : void 0,
|
|
1856
|
+
// Vite config options for SPA preview mode
|
|
1857
|
+
...viteCommand === "serve" && ctx.reactRouterConfig.ssr === false ? {
|
|
1858
|
+
build: {
|
|
1859
|
+
manifest: true,
|
|
1860
|
+
outDir: getClientBuildDirectory(ctx.reactRouterConfig)
|
|
1861
|
+
}
|
|
1862
|
+
} : void 0
|
|
1863
|
+
};
|
|
1864
|
+
},
|
|
1865
|
+
async configResolved(resolvedViteConfig) {
|
|
1866
|
+
await import_es_module_lexer.init;
|
|
1867
|
+
viteConfig = resolvedViteConfig;
|
|
1868
|
+
invariant(viteConfig);
|
|
1869
|
+
if (!viteConfig.configFile) {
|
|
1870
|
+
throw new Error(
|
|
1871
|
+
"The React Router Vite plugin requires the use of a Vite config file"
|
|
1872
|
+
);
|
|
1873
|
+
}
|
|
1874
|
+
let vite2 = getVite();
|
|
1875
|
+
let childCompilerConfigFile = await vite2.loadConfigFromFile(
|
|
1876
|
+
{
|
|
1877
|
+
command: viteConfig.command,
|
|
1878
|
+
mode: viteConfig.mode,
|
|
1879
|
+
isSsrBuild: ctx.isSsrBuild
|
|
1880
|
+
},
|
|
1881
|
+
viteConfig.configFile
|
|
1882
|
+
);
|
|
1883
|
+
invariant(
|
|
1884
|
+
childCompilerConfigFile,
|
|
1885
|
+
"Vite config file was unable to be resolved for React Router child compiler"
|
|
1886
|
+
);
|
|
1887
|
+
let rollupPrePlugins = [
|
|
1888
|
+
{ pluginName: "@mdx-js/rollup", displayName: "@mdx-js/rollup" }
|
|
1889
|
+
];
|
|
1890
|
+
for (let prePlugin of rollupPrePlugins) {
|
|
1891
|
+
let prePluginIndex = pluginIndex(prePlugin.pluginName);
|
|
1892
|
+
if (prePluginIndex >= 0 && prePluginIndex > pluginIndex("react-router")) {
|
|
1893
|
+
throw new Error(
|
|
1894
|
+
`The "${prePlugin.displayName}" plugin should be placed before the React Router plugin in your Vite config file`
|
|
1895
|
+
);
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
viteChildCompiler = await vite2.createServer({
|
|
1899
|
+
...viteUserConfig,
|
|
1900
|
+
mode: viteConfig.mode,
|
|
1901
|
+
server: {
|
|
1902
|
+
watch: viteConfig.command === "build" ? null : void 0,
|
|
1903
|
+
preTransformRequests: false,
|
|
1904
|
+
hmr: false
|
|
1905
|
+
},
|
|
1906
|
+
configFile: false,
|
|
1907
|
+
envFile: false,
|
|
1908
|
+
plugins: [
|
|
1909
|
+
...(childCompilerConfigFile.config.plugins ?? []).flat().filter(
|
|
1910
|
+
(plugin2) => typeof plugin2 === "object" && plugin2 !== null && "name" in plugin2 && plugin2.name !== "react-router" && plugin2.name !== "react-router:route-exports" && plugin2.name !== "react-router:hmr-updates"
|
|
1911
|
+
)
|
|
1912
|
+
]
|
|
1913
|
+
});
|
|
1914
|
+
await viteChildCompiler.pluginContainer.buildStart({});
|
|
1915
|
+
},
|
|
1916
|
+
async transform(code, id) {
|
|
1917
|
+
if (isCssModulesFile(id)) {
|
|
1918
|
+
cssModulesManifest[id] = code;
|
|
1919
|
+
}
|
|
1920
|
+
},
|
|
1921
|
+
buildStart() {
|
|
1922
|
+
invariant(viteConfig);
|
|
1923
|
+
if (viteCommand === "build" && viteConfig.mode === "production" && !viteConfig.build.ssr && viteConfig.build.sourcemap) {
|
|
1924
|
+
viteConfig.logger.warn(
|
|
1925
|
+
import_picocolors3.default.yellow(
|
|
1926
|
+
"\n" + import_picocolors3.default.bold(" \u26A0\uFE0F Source maps are enabled in production\n") + [
|
|
1927
|
+
"This makes your server code publicly",
|
|
1928
|
+
"visible in the browser. This is highly",
|
|
1929
|
+
"discouraged! If you insist, ensure that",
|
|
1930
|
+
"you are using environment variables for",
|
|
1931
|
+
"secrets and not hard-coding them in",
|
|
1932
|
+
"your source code."
|
|
1933
|
+
].map((line) => " " + line).join("\n") + "\n"
|
|
1934
|
+
)
|
|
1935
|
+
);
|
|
1936
|
+
}
|
|
1937
|
+
},
|
|
1938
|
+
async configureServer(viteDevServer) {
|
|
1939
|
+
(0, import_react_router2.unstable_setDevServerHooks)({
|
|
1940
|
+
// Give the request handler access to the critical CSS in dev to avoid a
|
|
1941
|
+
// flash of unstyled content since Vite injects CSS file contents via JS
|
|
1942
|
+
getCriticalCss: async (build, url2) => {
|
|
1943
|
+
return getStylesForUrl({
|
|
1944
|
+
rootDirectory: ctx.rootDirectory,
|
|
1945
|
+
entryClientFilePath: ctx.entryClientFilePath,
|
|
1946
|
+
reactRouterConfig: ctx.reactRouterConfig,
|
|
1947
|
+
viteDevServer,
|
|
1948
|
+
cssModulesManifest,
|
|
1949
|
+
build,
|
|
1950
|
+
url: url2
|
|
1951
|
+
});
|
|
1952
|
+
},
|
|
1953
|
+
// If an error is caught within the request handler, let Vite fix the
|
|
1954
|
+
// stack trace so it maps back to the actual source code
|
|
1955
|
+
processRequestError: (error) => {
|
|
1956
|
+
if (error instanceof Error) {
|
|
1957
|
+
viteDevServer.ssrFixStacktrace(error);
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
});
|
|
1961
|
+
reactRouterConfigLoader.onChange(
|
|
1962
|
+
async ({
|
|
1963
|
+
result,
|
|
1964
|
+
configCodeUpdated,
|
|
1965
|
+
configChanged,
|
|
1966
|
+
routeConfigChanged
|
|
1967
|
+
}) => {
|
|
1968
|
+
if (!result.ok) {
|
|
1969
|
+
invalidateVirtualModules(viteDevServer);
|
|
1970
|
+
logger.error(result.error, {
|
|
1971
|
+
clear: true,
|
|
1972
|
+
timestamp: true
|
|
1973
|
+
});
|
|
1974
|
+
return;
|
|
1975
|
+
}
|
|
1976
|
+
if (routeConfigChanged) {
|
|
1977
|
+
logger.info(import_picocolors3.default.green("Route config changed."), {
|
|
1978
|
+
clear: true,
|
|
1979
|
+
timestamp: true
|
|
1980
|
+
});
|
|
1981
|
+
} else if (configCodeUpdated) {
|
|
1982
|
+
logger.info(import_picocolors3.default.green("Config updated."), {
|
|
1983
|
+
clear: true,
|
|
1984
|
+
timestamp: true
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
await updatePluginContext();
|
|
1988
|
+
if (configChanged) {
|
|
1989
|
+
invalidateVirtualModules(viteDevServer);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
);
|
|
1993
|
+
return () => {
|
|
1994
|
+
if (!viteDevServer.config.server.middlewareMode) {
|
|
1995
|
+
viteDevServer.middlewares.use(async (req, res, next) => {
|
|
1996
|
+
try {
|
|
1997
|
+
let build = await viteDevServer.ssrLoadModule(
|
|
1998
|
+
virtual.serverBuild.id
|
|
1999
|
+
);
|
|
2000
|
+
let handler = (0, import_react_router2.createRequestHandler)(build, "development");
|
|
2001
|
+
let nodeHandler = async (nodeReq, nodeRes) => {
|
|
2002
|
+
let req2 = fromNodeRequest(nodeReq, nodeRes);
|
|
2003
|
+
let res2 = await handler(
|
|
2004
|
+
req2,
|
|
2005
|
+
await reactRouterDevLoadContext(req2)
|
|
2006
|
+
);
|
|
2007
|
+
await toNodeRequest(res2, nodeRes);
|
|
2008
|
+
};
|
|
2009
|
+
await nodeHandler(req, res);
|
|
2010
|
+
} catch (error) {
|
|
2011
|
+
next(error);
|
|
2012
|
+
}
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
},
|
|
2017
|
+
writeBundle: {
|
|
2018
|
+
// After the SSR build is finished, we inspect the Vite manifest for
|
|
2019
|
+
// the SSR build and move server-only assets to client assets directory
|
|
2020
|
+
async handler() {
|
|
2021
|
+
if (!ctx.isSsrBuild) {
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
invariant(viteConfig);
|
|
2025
|
+
let clientBuildDirectory = getClientBuildDirectory(
|
|
2026
|
+
ctx.reactRouterConfig
|
|
2027
|
+
);
|
|
2028
|
+
let serverBuildDirectory = getServerBuildDirectory(ctx);
|
|
2029
|
+
let ssrViteManifest = await loadViteManifest(serverBuildDirectory);
|
|
2030
|
+
let ssrAssetPaths = getViteManifestAssetPaths(ssrViteManifest);
|
|
2031
|
+
let movedAssetPaths = [];
|
|
2032
|
+
for (let ssrAssetPath of ssrAssetPaths) {
|
|
2033
|
+
let src = path6.join(serverBuildDirectory, ssrAssetPath);
|
|
2034
|
+
let dest = path6.join(clientBuildDirectory, ssrAssetPath);
|
|
2035
|
+
if (!fse.existsSync(dest)) {
|
|
2036
|
+
await fse.move(src, dest);
|
|
2037
|
+
movedAssetPaths.push(dest);
|
|
2038
|
+
} else {
|
|
2039
|
+
await fse.remove(src);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
let ssrCssPaths = Object.values(ssrViteManifest).flatMap(
|
|
2043
|
+
(chunk) => chunk.css ?? []
|
|
2044
|
+
);
|
|
2045
|
+
await Promise.all(
|
|
2046
|
+
ssrCssPaths.map(
|
|
2047
|
+
(cssPath) => fse.remove(path6.join(serverBuildDirectory, cssPath))
|
|
2048
|
+
)
|
|
2049
|
+
);
|
|
2050
|
+
if (movedAssetPaths.length) {
|
|
2051
|
+
viteConfig.logger.info(
|
|
2052
|
+
[
|
|
2053
|
+
"",
|
|
2054
|
+
`${import_picocolors3.default.green("\u2713")} ${movedAssetPaths.length} asset${movedAssetPaths.length > 1 ? "s" : ""} moved from React Router server build to client assets.`,
|
|
2055
|
+
...movedAssetPaths.map(
|
|
2056
|
+
(movedAssetPath) => import_picocolors3.default.dim(path6.relative(ctx.rootDirectory, movedAssetPath))
|
|
2057
|
+
),
|
|
2058
|
+
""
|
|
2059
|
+
].join("\n")
|
|
2060
|
+
);
|
|
2061
|
+
}
|
|
2062
|
+
if (ctx.reactRouterConfig.prerender != null && ctx.reactRouterConfig.prerender !== false) {
|
|
2063
|
+
await handlePrerender(
|
|
2064
|
+
viteConfig,
|
|
2065
|
+
ctx.reactRouterConfig,
|
|
2066
|
+
serverBuildDirectory,
|
|
2067
|
+
clientBuildDirectory
|
|
2068
|
+
);
|
|
2069
|
+
}
|
|
2070
|
+
if (!ctx.reactRouterConfig.ssr) {
|
|
2071
|
+
await handleSpaMode(
|
|
2072
|
+
viteConfig,
|
|
2073
|
+
ctx.reactRouterConfig,
|
|
2074
|
+
serverBuildDirectory,
|
|
2075
|
+
clientBuildDirectory
|
|
2076
|
+
);
|
|
2077
|
+
}
|
|
2078
|
+
if (!ctx.reactRouterConfig.ssr) {
|
|
2079
|
+
viteConfig.logger.info(
|
|
2080
|
+
[
|
|
2081
|
+
"Removing the server build in",
|
|
2082
|
+
import_picocolors3.default.green(serverBuildDirectory),
|
|
2083
|
+
"due to ssr:false"
|
|
2084
|
+
].join(" ")
|
|
2085
|
+
);
|
|
2086
|
+
fse.removeSync(serverBuildDirectory);
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
},
|
|
2090
|
+
async buildEnd() {
|
|
2091
|
+
await viteChildCompiler?.close();
|
|
2092
|
+
await reactRouterConfigLoader.close();
|
|
2093
|
+
let typegenWatcher = await typegenWatcherPromise;
|
|
2094
|
+
await typegenWatcher?.close();
|
|
2095
|
+
}
|
|
2096
|
+
},
|
|
2097
|
+
{
|
|
2098
|
+
name: "react-router:build-client-route",
|
|
2099
|
+
enforce: "pre",
|
|
2100
|
+
async transform(_code, id, options) {
|
|
2101
|
+
if (!id.endsWith(BUILD_CLIENT_ROUTE_QUERY_STRING)) return;
|
|
2102
|
+
let routeModuleId = id.replace(BUILD_CLIENT_ROUTE_QUERY_STRING, "");
|
|
2103
|
+
let routeFileName = path6.basename(routeModuleId);
|
|
2104
|
+
let sourceExports = await getRouteModuleExports(
|
|
2105
|
+
viteChildCompiler,
|
|
2106
|
+
ctx,
|
|
2107
|
+
routeModuleId
|
|
2108
|
+
);
|
|
2109
|
+
let reexports = sourceExports.filter(
|
|
2110
|
+
(exportName) => options?.ssr && SERVER_ONLY_ROUTE_EXPORTS.includes(exportName) || CLIENT_ROUTE_EXPORTS.includes(exportName)
|
|
2111
|
+
).join(", ");
|
|
2112
|
+
return `export { ${reexports} } from "./${routeFileName}";`;
|
|
2113
|
+
}
|
|
2114
|
+
},
|
|
2115
|
+
{
|
|
2116
|
+
name: "react-router:virtual-modules",
|
|
2117
|
+
enforce: "pre",
|
|
2118
|
+
resolveId(id) {
|
|
2119
|
+
const vmod2 = Object.values(virtual).find((vmod3) => vmod3.id === id);
|
|
2120
|
+
if (vmod2) return vmod2.resolvedId;
|
|
2121
|
+
},
|
|
2122
|
+
async load(id) {
|
|
2123
|
+
switch (id) {
|
|
2124
|
+
case virtual.serverBuild.resolvedId: {
|
|
2125
|
+
return await getServerEntry();
|
|
2126
|
+
}
|
|
2127
|
+
case virtual.serverManifest.resolvedId: {
|
|
2128
|
+
let reactRouterManifest = ctx.isSsrBuild ? await ctx.getReactRouterServerManifest() : await getReactRouterManifestForDev();
|
|
2129
|
+
return `export default ${(0, import_jsesc.default)(reactRouterManifest, {
|
|
2130
|
+
es6: true
|
|
2131
|
+
})};`;
|
|
2132
|
+
}
|
|
2133
|
+
case virtual.browserManifest.resolvedId: {
|
|
2134
|
+
if (viteCommand === "build") {
|
|
2135
|
+
throw new Error("This module only exists in development");
|
|
2136
|
+
}
|
|
2137
|
+
let reactRouterManifest = await getReactRouterManifestForDev();
|
|
2138
|
+
let reactRouterManifestString = (0, import_jsesc.default)(reactRouterManifest, {
|
|
2139
|
+
es6: true
|
|
2140
|
+
});
|
|
2141
|
+
return `window.__reactRouterManifest=${reactRouterManifestString};`;
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
},
|
|
2146
|
+
{
|
|
2147
|
+
name: "react-router:dot-server",
|
|
2148
|
+
enforce: "pre",
|
|
2149
|
+
async resolveId(id, importer, options) {
|
|
2150
|
+
let isOptimizeDeps = viteCommand === "serve" && options?.scan === true;
|
|
2151
|
+
if (isOptimizeDeps || options?.ssr) return;
|
|
2152
|
+
let isResolving = options?.custom?.["react-router:dot-server"] ?? false;
|
|
2153
|
+
if (isResolving) return;
|
|
2154
|
+
options.custom = { ...options.custom, "react-router:dot-server": true };
|
|
2155
|
+
let resolved = await this.resolve(id, importer, options);
|
|
2156
|
+
if (!resolved) return;
|
|
2157
|
+
let serverFileRE = /\.server(\.[cm]?[jt]sx?)?$/;
|
|
2158
|
+
let serverDirRE = /\/\.server\//;
|
|
2159
|
+
let isDotServer = serverFileRE.test(resolved.id) || serverDirRE.test(resolved.id);
|
|
2160
|
+
if (!isDotServer) return;
|
|
2161
|
+
if (!importer) return;
|
|
2162
|
+
if (viteCommand !== "build" && importer.endsWith(".html")) {
|
|
2163
|
+
return;
|
|
2164
|
+
}
|
|
2165
|
+
let vite2 = getVite();
|
|
2166
|
+
let importerShort = vite2.normalizePath(
|
|
2167
|
+
path6.relative(ctx.rootDirectory, importer)
|
|
2168
|
+
);
|
|
2169
|
+
let isRoute = getRoute(ctx.reactRouterConfig, importer);
|
|
2170
|
+
if (isRoute) {
|
|
2171
|
+
let serverOnlyExports = SERVER_ONLY_ROUTE_EXPORTS.map(
|
|
2172
|
+
(xport) => `\`${xport}\``
|
|
2173
|
+
).join(", ");
|
|
2174
|
+
throw Error(
|
|
2175
|
+
[
|
|
2176
|
+
import_picocolors3.default.red(`Server-only module referenced by client`),
|
|
2177
|
+
"",
|
|
2178
|
+
` '${id}' imported by route '${importerShort}'`,
|
|
2179
|
+
"",
|
|
2180
|
+
` React Router automatically removes server-code from these exports:`,
|
|
2181
|
+
` ${serverOnlyExports}`,
|
|
2182
|
+
"",
|
|
2183
|
+
` But other route exports in '${importerShort}' depend on '${id}'.`,
|
|
2184
|
+
"",
|
|
2185
|
+
" See https://remix.run/docs/en/main/guides/vite#splitting-up-client-and-server-code",
|
|
2186
|
+
""
|
|
2187
|
+
].join("\n")
|
|
2188
|
+
);
|
|
2189
|
+
}
|
|
2190
|
+
throw Error(
|
|
2191
|
+
[
|
|
2192
|
+
import_picocolors3.default.red(`Server-only module referenced by client`),
|
|
2193
|
+
"",
|
|
2194
|
+
` '${id}' imported by '${importerShort}'`,
|
|
2195
|
+
"",
|
|
2196
|
+
" See https://remix.run/docs/en/main/guides/vite#splitting-up-client-and-server-code",
|
|
2197
|
+
""
|
|
2198
|
+
].join("\n")
|
|
2199
|
+
);
|
|
2200
|
+
}
|
|
2201
|
+
},
|
|
2202
|
+
{
|
|
2203
|
+
name: "react-router:dot-client",
|
|
2204
|
+
async transform(code, id, options) {
|
|
2205
|
+
if (!options?.ssr) return;
|
|
2206
|
+
let clientFileRE = /\.client(\.[cm]?[jt]sx?)?$/;
|
|
2207
|
+
let clientDirRE = /\/\.client\//;
|
|
2208
|
+
if (clientFileRE.test(id) || clientDirRE.test(id)) {
|
|
2209
|
+
let exports2 = (0, import_es_module_lexer.parse)(code)[1];
|
|
2210
|
+
return {
|
|
2211
|
+
code: exports2.map(
|
|
2212
|
+
({ n: name }) => name === "default" ? "export default undefined;" : `export const ${name} = undefined;`
|
|
2213
|
+
).join("\n"),
|
|
2214
|
+
map: null
|
|
2215
|
+
};
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
},
|
|
2219
|
+
plugin,
|
|
2220
|
+
{
|
|
2221
|
+
name: "react-router:route-exports",
|
|
2222
|
+
async transform(code, id, options) {
|
|
2223
|
+
let route = getRoute(ctx.reactRouterConfig, id);
|
|
2224
|
+
if (!route) return;
|
|
2225
|
+
if (!options?.ssr && !ctx.reactRouterConfig.ssr) {
|
|
2226
|
+
let serverOnlyExports = (0, import_es_module_lexer.parse)(code)[1].map((exp) => exp.n).filter((exp) => SERVER_ONLY_ROUTE_EXPORTS.includes(exp));
|
|
2227
|
+
if (serverOnlyExports.length > 0) {
|
|
2228
|
+
let str = serverOnlyExports.map((e) => `\`${e}\``).join(", ");
|
|
2229
|
+
let message = `SPA Mode: ${serverOnlyExports.length} invalid route export(s) in \`${route.file}\`: ${str}. See https://remix.run/guides/spa-mode for more information.`;
|
|
2230
|
+
throw Error(message);
|
|
2231
|
+
}
|
|
2232
|
+
if (route.id !== "root") {
|
|
2233
|
+
let hasHydrateFallback = (0, import_es_module_lexer.parse)(code)[1].map((exp) => exp.n).some((exp) => exp === "HydrateFallback");
|
|
2234
|
+
if (hasHydrateFallback) {
|
|
2235
|
+
let message = `SPA Mode: Invalid \`HydrateFallback\` export found in \`${route.file}\`. \`HydrateFallback\` is only permitted on the root route in SPA Mode. See https://remix.run/guides/spa-mode for more information.`;
|
|
2236
|
+
throw Error(message);
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
let [filepath] = id.split("?");
|
|
2241
|
+
let ast = (0, import_parser.parse)(code, { sourceType: "module" });
|
|
2242
|
+
if (!options?.ssr) {
|
|
2243
|
+
removeExports(ast, SERVER_ONLY_ROUTE_EXPORTS);
|
|
2244
|
+
}
|
|
2245
|
+
transform(ast);
|
|
2246
|
+
return generate2(ast, {
|
|
2247
|
+
sourceMaps: true,
|
|
2248
|
+
filename: id,
|
|
2249
|
+
sourceFileName: filepath
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
},
|
|
2253
|
+
{
|
|
2254
|
+
name: "react-router:inject-hmr-runtime",
|
|
2255
|
+
enforce: "pre",
|
|
2256
|
+
resolveId(id) {
|
|
2257
|
+
if (id === virtualInjectHmrRuntime.id) {
|
|
2258
|
+
return virtualInjectHmrRuntime.resolvedId;
|
|
2259
|
+
}
|
|
2260
|
+
},
|
|
2261
|
+
async load(id) {
|
|
2262
|
+
if (id !== virtualInjectHmrRuntime.resolvedId) return;
|
|
2263
|
+
return [
|
|
2264
|
+
`import RefreshRuntime from "${virtualHmrRuntime.id}"`,
|
|
2265
|
+
"RefreshRuntime.injectIntoGlobalHook(window)",
|
|
2266
|
+
"window.$RefreshReg$ = () => {}",
|
|
2267
|
+
"window.$RefreshSig$ = () => (type) => type",
|
|
2268
|
+
"window.__vite_plugin_react_preamble_installed__ = true"
|
|
2269
|
+
].join("\n");
|
|
2270
|
+
}
|
|
2271
|
+
},
|
|
2272
|
+
{
|
|
2273
|
+
name: "react-router:hmr-runtime",
|
|
2274
|
+
enforce: "pre",
|
|
2275
|
+
resolveId(id) {
|
|
2276
|
+
if (id === virtualHmrRuntime.id) return virtualHmrRuntime.resolvedId;
|
|
2277
|
+
},
|
|
2278
|
+
async load(id) {
|
|
2279
|
+
if (id !== virtualHmrRuntime.resolvedId) return;
|
|
2280
|
+
let reactRefreshDir = path6.dirname(
|
|
2281
|
+
require.resolve("react-refresh/package.json")
|
|
2282
|
+
);
|
|
2283
|
+
let reactRefreshRuntimePath = path6.join(
|
|
2284
|
+
reactRefreshDir,
|
|
2285
|
+
"cjs/react-refresh-runtime.development.js"
|
|
2286
|
+
);
|
|
2287
|
+
return [
|
|
2288
|
+
"const exports = {}",
|
|
2289
|
+
await fse.readFile(reactRefreshRuntimePath, "utf8"),
|
|
2290
|
+
await fse.readFile(
|
|
2291
|
+
require.resolve("./static/refresh-utils.cjs"),
|
|
2292
|
+
"utf8"
|
|
2293
|
+
),
|
|
2294
|
+
"export default exports"
|
|
2295
|
+
].join("\n");
|
|
2296
|
+
}
|
|
2297
|
+
},
|
|
2298
|
+
{
|
|
2299
|
+
name: "react-router:react-refresh-babel",
|
|
2300
|
+
async transform(code, id, options) {
|
|
2301
|
+
if (viteCommand !== "serve") return;
|
|
2302
|
+
if (id.includes("/node_modules/")) return;
|
|
2303
|
+
let [filepath] = id.split("?");
|
|
2304
|
+
let extensionsRE = /\.(jsx?|tsx?|mdx?)$/;
|
|
2305
|
+
if (!extensionsRE.test(filepath)) return;
|
|
2306
|
+
let devRuntime = "react/jsx-dev-runtime";
|
|
2307
|
+
let ssr = options?.ssr === true;
|
|
2308
|
+
let isJSX = filepath.endsWith("x");
|
|
2309
|
+
let useFastRefresh = !ssr && (isJSX || code.includes(devRuntime));
|
|
2310
|
+
if (!useFastRefresh) return;
|
|
2311
|
+
let result = await babel.transformAsync(code, {
|
|
2312
|
+
babelrc: false,
|
|
2313
|
+
configFile: false,
|
|
2314
|
+
filename: id,
|
|
2315
|
+
sourceFileName: filepath,
|
|
2316
|
+
parserOpts: {
|
|
2317
|
+
sourceType: "module",
|
|
2318
|
+
allowAwaitOutsideFunction: true
|
|
2319
|
+
},
|
|
2320
|
+
plugins: [[require("react-refresh/babel"), { skipEnvCheck: true }]],
|
|
2321
|
+
sourceMaps: true
|
|
2322
|
+
});
|
|
2323
|
+
if (result === null) return;
|
|
2324
|
+
code = result.code;
|
|
2325
|
+
let refreshContentRE = /\$Refresh(?:Reg|Sig)\$\(/;
|
|
2326
|
+
if (refreshContentRE.test(code)) {
|
|
2327
|
+
code = addRefreshWrapper(ctx.reactRouterConfig, code, id);
|
|
2328
|
+
}
|
|
2329
|
+
return { code, map: result.map };
|
|
2330
|
+
}
|
|
2331
|
+
},
|
|
2332
|
+
{
|
|
2333
|
+
name: "react-router:hmr-updates",
|
|
2334
|
+
async handleHotUpdate({ server, file, modules, read }) {
|
|
2335
|
+
let route = getRoute(ctx.reactRouterConfig, file);
|
|
2336
|
+
let hmrEventData = { route: null };
|
|
2337
|
+
if (route) {
|
|
2338
|
+
let serverManifest = (await server.ssrLoadModule(virtual.serverManifest.id)).default;
|
|
2339
|
+
let oldRouteMetadata = serverManifest.routes[route.id];
|
|
2340
|
+
let newRouteMetadata = await getRouteMetadata(
|
|
2341
|
+
ctx,
|
|
2342
|
+
viteChildCompiler,
|
|
2343
|
+
route,
|
|
2344
|
+
read
|
|
2345
|
+
);
|
|
2346
|
+
hmrEventData.route = newRouteMetadata;
|
|
2347
|
+
if (!oldRouteMetadata || [
|
|
2348
|
+
"hasLoader",
|
|
2349
|
+
"hasClientLoader",
|
|
2350
|
+
"hasAction",
|
|
2351
|
+
"hasClientAction",
|
|
2352
|
+
"hasErrorBoundary"
|
|
2353
|
+
].some((key) => oldRouteMetadata[key] !== newRouteMetadata[key])) {
|
|
2354
|
+
invalidateVirtualModules(server);
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
server.hot.send({
|
|
2358
|
+
type: "custom",
|
|
2359
|
+
event: "react-router:hmr",
|
|
2360
|
+
data: hmrEventData
|
|
2361
|
+
});
|
|
2362
|
+
return modules;
|
|
2363
|
+
}
|
|
2364
|
+
},
|
|
2365
|
+
{
|
|
2366
|
+
name: "react-router-server-change-trigger-client-hmr",
|
|
2367
|
+
// This hook is only available in Vite v6+ so this is a no-op in v5.
|
|
2368
|
+
// Previously the server and client modules were shared in a single module
|
|
2369
|
+
// graph. This meant that changes to server code automatically resulted in
|
|
2370
|
+
// client HMR updates. In Vite v6+ these module graphs are separate from
|
|
2371
|
+
// each other so we need to manually trigger client HMR updates if server
|
|
2372
|
+
// code has changed.
|
|
2373
|
+
hotUpdate({ server, modules }) {
|
|
2374
|
+
if (this.environment.name !== "ssr" && modules.length <= 0) {
|
|
2375
|
+
return;
|
|
2376
|
+
}
|
|
2377
|
+
let clientModules = uniqueNodes(
|
|
2378
|
+
modules.flatMap(
|
|
2379
|
+
(mod) => getParentClientNodes(server.environments.client.moduleGraph, mod)
|
|
2380
|
+
)
|
|
2381
|
+
);
|
|
2382
|
+
for (let clientModule of clientModules) {
|
|
2383
|
+
server.environments.client.reloadModule(clientModule);
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
];
|
|
2388
|
+
};
|
|
2389
|
+
function getParentClientNodes(clientModuleGraph, module2) {
|
|
2390
|
+
if (!module2.id) {
|
|
2391
|
+
return [];
|
|
2392
|
+
}
|
|
2393
|
+
let clientModule = clientModuleGraph.getModuleById(module2.id);
|
|
2394
|
+
if (clientModule) {
|
|
2395
|
+
return [clientModule];
|
|
2396
|
+
}
|
|
2397
|
+
return [...module2.importers].flatMap(
|
|
2398
|
+
(importer) => getParentClientNodes(clientModuleGraph, importer)
|
|
2399
|
+
);
|
|
2400
|
+
}
|
|
2401
|
+
function uniqueNodes(nodes) {
|
|
2402
|
+
let nodeUrls = /* @__PURE__ */ new Set();
|
|
2403
|
+
let unique = [];
|
|
2404
|
+
for (let node of nodes) {
|
|
2405
|
+
if (nodeUrls.has(node.url)) {
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
nodeUrls.add(node.url);
|
|
2409
|
+
unique.push(node);
|
|
2410
|
+
}
|
|
2411
|
+
return unique;
|
|
2412
|
+
}
|
|
2413
|
+
function addRefreshWrapper(reactRouterConfig, code, id) {
|
|
2414
|
+
let route = getRoute(reactRouterConfig, id);
|
|
2415
|
+
let acceptExports = route ? [
|
|
2416
|
+
"clientAction",
|
|
2417
|
+
"clientLoader",
|
|
2418
|
+
"handle",
|
|
2419
|
+
"meta",
|
|
2420
|
+
"links",
|
|
2421
|
+
"shouldRevalidate"
|
|
2422
|
+
] : [];
|
|
2423
|
+
return REACT_REFRESH_HEADER.replaceAll("__SOURCE__", JSON.stringify(id)) + code + REACT_REFRESH_FOOTER.replaceAll("__SOURCE__", JSON.stringify(id)).replaceAll("__ACCEPT_EXPORTS__", JSON.stringify(acceptExports)).replaceAll("__ROUTE_ID__", JSON.stringify(route?.id));
|
|
2424
|
+
}
|
|
2425
|
+
var REACT_REFRESH_HEADER = `
|
|
2426
|
+
import RefreshRuntime from "${virtualHmrRuntime.id}";
|
|
2427
|
+
|
|
2428
|
+
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
|
|
2429
|
+
let prevRefreshReg;
|
|
2430
|
+
let prevRefreshSig;
|
|
2431
|
+
|
|
2432
|
+
if (import.meta.hot && !inWebWorker) {
|
|
2433
|
+
if (!window.__vite_plugin_react_preamble_installed__) {
|
|
2434
|
+
throw new Error(
|
|
2435
|
+
"React Router Vite plugin can't detect preamble. Something is wrong."
|
|
2436
|
+
);
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
prevRefreshReg = window.$RefreshReg$;
|
|
2440
|
+
prevRefreshSig = window.$RefreshSig$;
|
|
2441
|
+
window.$RefreshReg$ = (type, id) => {
|
|
2442
|
+
RefreshRuntime.register(type, __SOURCE__ + " " + id)
|
|
2443
|
+
};
|
|
2444
|
+
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
|
|
2445
|
+
}`.replaceAll("\n", "");
|
|
2446
|
+
var REACT_REFRESH_FOOTER = `
|
|
2447
|
+
if (import.meta.hot && !inWebWorker) {
|
|
2448
|
+
window.$RefreshReg$ = prevRefreshReg;
|
|
2449
|
+
window.$RefreshSig$ = prevRefreshSig;
|
|
2450
|
+
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
|
|
2451
|
+
RefreshRuntime.registerExportsForReactRefresh(__SOURCE__, currentExports);
|
|
2452
|
+
import.meta.hot.accept((nextExports) => {
|
|
2453
|
+
if (!nextExports) return;
|
|
2454
|
+
__ROUTE_ID__ && window.__reactRouterRouteModuleUpdates.set(__ROUTE_ID__, nextExports);
|
|
2455
|
+
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(currentExports, nextExports, __ACCEPT_EXPORTS__);
|
|
2456
|
+
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
|
|
2457
|
+
});
|
|
2458
|
+
});
|
|
2459
|
+
}`;
|
|
2460
|
+
function getRoute(pluginConfig, file) {
|
|
2461
|
+
let vite2 = getVite();
|
|
2462
|
+
let routePath = vite2.normalizePath(
|
|
2463
|
+
path6.relative(pluginConfig.appDirectory, file)
|
|
2464
|
+
);
|
|
2465
|
+
let route = Object.values(pluginConfig.routes).find(
|
|
2466
|
+
(r) => vite2.normalizePath(r.file) === routePath
|
|
2467
|
+
);
|
|
2468
|
+
return route;
|
|
2469
|
+
}
|
|
2470
|
+
async function getRouteMetadata(ctx, viteChildCompiler, route, readRouteFile) {
|
|
2471
|
+
let sourceExports = await getRouteModuleExports(
|
|
2472
|
+
viteChildCompiler,
|
|
2473
|
+
ctx,
|
|
2474
|
+
route.file,
|
|
2475
|
+
readRouteFile
|
|
2476
|
+
);
|
|
2477
|
+
let info = {
|
|
2478
|
+
id: route.id,
|
|
2479
|
+
parentId: route.parentId,
|
|
2480
|
+
path: route.path,
|
|
2481
|
+
index: route.index,
|
|
2482
|
+
caseSensitive: route.caseSensitive,
|
|
2483
|
+
url: combineURLs(
|
|
2484
|
+
ctx.publicPath,
|
|
2485
|
+
"/" + path6.relative(
|
|
2486
|
+
ctx.rootDirectory,
|
|
2487
|
+
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
|
|
2488
|
+
)
|
|
2489
|
+
),
|
|
2490
|
+
module: combineURLs(
|
|
2491
|
+
ctx.publicPath,
|
|
2492
|
+
`${resolveFileUrl(
|
|
2493
|
+
ctx,
|
|
2494
|
+
resolveRelativeRouteFilePath(route, ctx.reactRouterConfig)
|
|
2495
|
+
)}?import`
|
|
2496
|
+
),
|
|
2497
|
+
// Ensure the Vite dev server responds with a JS module
|
|
2498
|
+
hasAction: sourceExports.includes("action"),
|
|
2499
|
+
hasClientAction: sourceExports.includes("clientAction"),
|
|
2500
|
+
hasLoader: sourceExports.includes("loader"),
|
|
2501
|
+
hasClientLoader: sourceExports.includes("clientLoader"),
|
|
2502
|
+
hasErrorBoundary: sourceExports.includes("ErrorBoundary"),
|
|
2503
|
+
imports: []
|
|
2504
|
+
};
|
|
2505
|
+
return info;
|
|
2506
|
+
}
|
|
2507
|
+
async function getPrerenderBuildAndHandler(viteConfig, reactRouterConfig, serverBuildDirectory) {
|
|
2508
|
+
let serverBuildPath = path6.join(
|
|
2509
|
+
serverBuildDirectory,
|
|
2510
|
+
reactRouterConfig.serverBuildFile
|
|
2511
|
+
);
|
|
2512
|
+
let build = await import(url.pathToFileURL(serverBuildPath).toString());
|
|
2513
|
+
let { createRequestHandler: createHandler } = await import("react-router");
|
|
2514
|
+
return {
|
|
2515
|
+
build,
|
|
2516
|
+
handler: createHandler(build, viteConfig.mode)
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
async function handleSpaMode(viteConfig, reactRouterConfig, serverBuildDirectory, clientBuildDirectory) {
|
|
2520
|
+
let { handler } = await getPrerenderBuildAndHandler(
|
|
2521
|
+
viteConfig,
|
|
2522
|
+
reactRouterConfig,
|
|
2523
|
+
serverBuildDirectory
|
|
2524
|
+
);
|
|
2525
|
+
let request = new Request(`http://localhost${reactRouterConfig.basename}`);
|
|
2526
|
+
let response = await handler(request);
|
|
2527
|
+
let html = await response.text();
|
|
2528
|
+
validatePrerenderedResponse(response, html, "SPA Mode", "/");
|
|
2529
|
+
validatePrerenderedHtml(html, "SPA Mode");
|
|
2530
|
+
await fse.writeFile(path6.join(clientBuildDirectory, "index.html"), html);
|
|
2531
|
+
viteConfig.logger.info(
|
|
2532
|
+
"SPA Mode: index.html has been written to your " + import_picocolors3.default.bold(path6.relative(process.cwd(), clientBuildDirectory)) + " directory"
|
|
2533
|
+
);
|
|
2534
|
+
}
|
|
2535
|
+
async function handlePrerender(viteConfig, reactRouterConfig, serverBuildDirectory, clientBuildDirectory) {
|
|
2536
|
+
let { build, handler } = await getPrerenderBuildAndHandler(
|
|
2537
|
+
viteConfig,
|
|
2538
|
+
reactRouterConfig,
|
|
2539
|
+
serverBuildDirectory
|
|
2540
|
+
);
|
|
2541
|
+
let routes = createPrerenderRoutes(build.routes);
|
|
2542
|
+
let routesToPrerender;
|
|
2543
|
+
if (typeof reactRouterConfig.prerender === "boolean") {
|
|
2544
|
+
invariant(reactRouterConfig.prerender, "Expected prerender:true");
|
|
2545
|
+
routesToPrerender = determineStaticPrerenderRoutes(
|
|
2546
|
+
routes,
|
|
2547
|
+
viteConfig,
|
|
2548
|
+
true
|
|
2549
|
+
);
|
|
2550
|
+
} else if (typeof reactRouterConfig.prerender === "function") {
|
|
2551
|
+
routesToPrerender = await reactRouterConfig.prerender({
|
|
2552
|
+
getStaticPaths: () => determineStaticPrerenderRoutes(routes, viteConfig, false)
|
|
2553
|
+
});
|
|
2554
|
+
} else {
|
|
2555
|
+
routesToPrerender = reactRouterConfig.prerender || ["/"];
|
|
2556
|
+
}
|
|
2557
|
+
let headers = {
|
|
2558
|
+
// Header that can be used in the loader to know if you're running at
|
|
2559
|
+
// build time or runtime
|
|
2560
|
+
"X-React-Router-Prerender": "yes"
|
|
2561
|
+
};
|
|
2562
|
+
for (let path7 of routesToPrerender) {
|
|
2563
|
+
let matches = (0, import_react_router2.matchRoutes)(routes, `/${path7}/`.replace(/^\/\/+/, "/"));
|
|
2564
|
+
let hasLoaders = matches?.some((m) => m.route.loader);
|
|
2565
|
+
let data;
|
|
2566
|
+
if (hasLoaders) {
|
|
2567
|
+
data = await prerenderData(
|
|
2568
|
+
handler,
|
|
2569
|
+
path7,
|
|
2570
|
+
clientBuildDirectory,
|
|
2571
|
+
reactRouterConfig,
|
|
2572
|
+
viteConfig,
|
|
2573
|
+
{ headers }
|
|
2574
|
+
);
|
|
2575
|
+
}
|
|
2576
|
+
let leafRoute = matches ? matches[matches.length - 1].route : null;
|
|
2577
|
+
let manifestRoute = leafRoute ? build.routes[leafRoute.id]?.module : null;
|
|
2578
|
+
let isResourceRoute = manifestRoute && !manifestRoute.default && !manifestRoute.ErrorBoundary && manifestRoute.loader;
|
|
2579
|
+
if (isResourceRoute) {
|
|
2580
|
+
await prerenderResourceRoute(
|
|
2581
|
+
handler,
|
|
2582
|
+
path7,
|
|
2583
|
+
clientBuildDirectory,
|
|
2584
|
+
reactRouterConfig,
|
|
2585
|
+
viteConfig,
|
|
2586
|
+
{ headers }
|
|
2587
|
+
);
|
|
2588
|
+
} else {
|
|
2589
|
+
await prerenderRoute(
|
|
2590
|
+
handler,
|
|
2591
|
+
path7,
|
|
2592
|
+
clientBuildDirectory,
|
|
2593
|
+
reactRouterConfig,
|
|
2594
|
+
viteConfig,
|
|
2595
|
+
data ? {
|
|
2596
|
+
headers: {
|
|
2597
|
+
...headers,
|
|
2598
|
+
"X-React-Router-Prerender-Data": encodeURI(data)
|
|
2599
|
+
}
|
|
2600
|
+
} : { headers }
|
|
2601
|
+
);
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
await prerenderManifest(
|
|
2605
|
+
build,
|
|
2606
|
+
clientBuildDirectory,
|
|
2607
|
+
reactRouterConfig,
|
|
2608
|
+
viteConfig
|
|
2609
|
+
);
|
|
2610
|
+
}
|
|
2611
|
+
function determineStaticPrerenderRoutes(routes, viteConfig, isBooleanUsage = false) {
|
|
2612
|
+
let paths = ["/"];
|
|
2613
|
+
let paramRoutes = [];
|
|
2614
|
+
function recurse(subtree, prefix = "") {
|
|
2615
|
+
for (let route of subtree) {
|
|
2616
|
+
let newPath = [prefix, route.path].join("/").replace(/\/\/+/g, "/");
|
|
2617
|
+
if (route.path) {
|
|
2618
|
+
let segments = route.path.split("/");
|
|
2619
|
+
if (segments.some((s) => s.startsWith(":") || s === "*")) {
|
|
2620
|
+
paramRoutes.push(route.path);
|
|
2621
|
+
} else {
|
|
2622
|
+
paths.push(newPath);
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
if (route.children) {
|
|
2626
|
+
recurse(route.children, newPath);
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
recurse(routes);
|
|
2631
|
+
if (isBooleanUsage && paramRoutes.length > 0) {
|
|
2632
|
+
viteConfig.logger.warn(
|
|
2633
|
+
[
|
|
2634
|
+
"\u26A0\uFE0F Paths with dynamic/splat params cannot be prerendered when using `prerender: true`.",
|
|
2635
|
+
"You may want to use the `prerender()` API to prerender the following paths:",
|
|
2636
|
+
...paramRoutes.map((p) => " - " + p)
|
|
2637
|
+
].join("\n")
|
|
2638
|
+
);
|
|
2639
|
+
}
|
|
2640
|
+
return paths.map((p) => p.replace(/\/\/+/g, "/").replace(/(.+)\/$/, "$1"));
|
|
2641
|
+
}
|
|
2642
|
+
async function prerenderData(handler, prerenderPath, clientBuildDirectory, reactRouterConfig, viteConfig, requestInit) {
|
|
2643
|
+
let normalizedPath = `${reactRouterConfig.basename}${prerenderPath === "/" ? "/_root.data" : `${prerenderPath.replace(/\/$/, "")}.data`}`.replace(/\/\/+/g, "/");
|
|
2644
|
+
let request = new Request(`http://localhost${normalizedPath}`, requestInit);
|
|
2645
|
+
let response = await handler(request);
|
|
2646
|
+
let data = await response.text();
|
|
2647
|
+
validatePrerenderedResponse(response, data, "Prerender", normalizedPath);
|
|
2648
|
+
let outdir = path6.relative(process.cwd(), clientBuildDirectory);
|
|
2649
|
+
let outfile = path6.join(outdir, ...normalizedPath.split("/"));
|
|
2650
|
+
await fse.ensureDir(path6.dirname(outfile));
|
|
2651
|
+
await fse.outputFile(outfile, data);
|
|
2652
|
+
viteConfig.logger.info(`Prerender: Generated ${import_picocolors3.default.bold(outfile)}`);
|
|
2653
|
+
return data;
|
|
2654
|
+
}
|
|
2655
|
+
async function prerenderRoute(handler, prerenderPath, clientBuildDirectory, reactRouterConfig, viteConfig, requestInit) {
|
|
2656
|
+
let normalizedPath = `${reactRouterConfig.basename}${prerenderPath}/`.replace(
|
|
2657
|
+
/\/\/+/g,
|
|
2658
|
+
"/"
|
|
2659
|
+
);
|
|
2660
|
+
let request = new Request(`http://localhost${normalizedPath}`, requestInit);
|
|
2661
|
+
let response = await handler(request);
|
|
2662
|
+
let html = await response.text();
|
|
2663
|
+
validatePrerenderedResponse(response, html, "Prerender", normalizedPath);
|
|
2664
|
+
if (!reactRouterConfig.ssr) {
|
|
2665
|
+
validatePrerenderedHtml(html, "Prerender");
|
|
2666
|
+
}
|
|
2667
|
+
let outdir = path6.relative(process.cwd(), clientBuildDirectory);
|
|
2668
|
+
let outfile = path6.join(outdir, ...normalizedPath.split("/"), "index.html");
|
|
2669
|
+
await fse.ensureDir(path6.dirname(outfile));
|
|
2670
|
+
await fse.outputFile(outfile, html);
|
|
2671
|
+
viteConfig.logger.info(`Prerender: Generated ${import_picocolors3.default.bold(outfile)}`);
|
|
2672
|
+
}
|
|
2673
|
+
async function prerenderResourceRoute(handler, prerenderPath, clientBuildDirectory, reactRouterConfig, viteConfig, requestInit) {
|
|
2674
|
+
let normalizedPath = `${reactRouterConfig.basename}${prerenderPath}/`.replace(/\/\/+/g, "/").replace(/\/$/g, "");
|
|
2675
|
+
let request = new Request(`http://localhost${normalizedPath}`, requestInit);
|
|
2676
|
+
let response = await handler(request);
|
|
2677
|
+
let text = await response.text();
|
|
2678
|
+
validatePrerenderedResponse(response, text, "Prerender", normalizedPath);
|
|
2679
|
+
let outdir = path6.relative(process.cwd(), clientBuildDirectory);
|
|
2680
|
+
let outfile = path6.join(outdir, ...normalizedPath.split("/"));
|
|
2681
|
+
await fse.ensureDir(path6.dirname(outfile));
|
|
2682
|
+
await fse.outputFile(outfile, text);
|
|
2683
|
+
viteConfig.logger.info(`Prerender: Generated ${import_picocolors3.default.bold(outfile)}`);
|
|
2684
|
+
}
|
|
2685
|
+
async function prerenderManifest(build, clientBuildDirectory, reactRouterConfig, viteConfig) {
|
|
2686
|
+
let normalizedPath = `${reactRouterConfig.basename}/__manifest`.replace(
|
|
2687
|
+
/\/\/+/g,
|
|
2688
|
+
"/"
|
|
2689
|
+
);
|
|
2690
|
+
let outdir = path6.relative(process.cwd(), clientBuildDirectory);
|
|
2691
|
+
let outfile = path6.join(outdir, ...normalizedPath.split("/"));
|
|
2692
|
+
await fse.ensureDir(path6.dirname(outfile));
|
|
2693
|
+
let manifestData = JSON.stringify(build.assets.routes);
|
|
2694
|
+
await fse.outputFile(outfile, manifestData);
|
|
2695
|
+
viteConfig.logger.info(`Prerender: Generated ${import_picocolors3.default.bold(outfile)}`);
|
|
2696
|
+
}
|
|
2697
|
+
function validatePrerenderedResponse(response, html, prefix, path7) {
|
|
2698
|
+
if (response.status !== 200) {
|
|
2699
|
+
throw new Error(
|
|
2700
|
+
`${prefix}: Received a ${response.status} status code from \`entry.server.tsx\` while prerendering the \`${path7}\` path.
|
|
2701
|
+
${html}`
|
|
2702
|
+
);
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
function validatePrerenderedHtml(html, prefix) {
|
|
2706
|
+
if (!html.includes("window.__reactRouterContext =") || !html.includes("window.__reactRouterRouteModules =")) {
|
|
2707
|
+
throw new Error(
|
|
2708
|
+
`${prefix}: Did you forget to include <Scripts/> in your root route? Your pre-rendered HTML files cannot hydrate without \`<Scripts />\`.`
|
|
2709
|
+
);
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
function groupRoutesByParentId2(manifest) {
|
|
2713
|
+
let routes = {};
|
|
2714
|
+
Object.values(manifest).forEach((route) => {
|
|
2715
|
+
if (route) {
|
|
2716
|
+
let parentId = route.parentId || "";
|
|
2717
|
+
if (!routes[parentId]) {
|
|
2718
|
+
routes[parentId] = [];
|
|
2719
|
+
}
|
|
2720
|
+
routes[parentId].push(route);
|
|
2721
|
+
}
|
|
2722
|
+
});
|
|
2723
|
+
return routes;
|
|
2724
|
+
}
|
|
2725
|
+
function createPrerenderRoutes(manifest, parentId = "", routesByParentId = groupRoutesByParentId2(manifest)) {
|
|
2726
|
+
return (routesByParentId[parentId] || []).map((route) => {
|
|
2727
|
+
let commonRoute = {
|
|
2728
|
+
// Always include root due to default boundaries
|
|
2729
|
+
hasErrorBoundary: route.id === "root" || route.module.ErrorBoundary != null,
|
|
2730
|
+
id: route.id,
|
|
2731
|
+
path: route.path,
|
|
2732
|
+
loader: route.module.loader ? () => null : void 0,
|
|
2733
|
+
action: void 0,
|
|
2734
|
+
handle: route.module.handle
|
|
2735
|
+
};
|
|
2736
|
+
return route.index ? {
|
|
2737
|
+
index: true,
|
|
2738
|
+
...commonRoute
|
|
2739
|
+
} : {
|
|
2740
|
+
caseSensitive: route.caseSensitive,
|
|
2741
|
+
children: createPrerenderRoutes(manifest, route.id, routesByParentId),
|
|
2742
|
+
...commonRoute
|
|
2743
|
+
};
|
|
2744
|
+
});
|
|
2745
|
+
}
|
|
2746
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2747
|
+
0 && (module.exports = {
|
|
2748
|
+
reactRouter
|
|
2749
|
+
});
|