react-router 0.0.0-experimental-1ebb6d403 → 0.0.0-experimental-e41ede670

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +0 -10
  2. package/dist/development/{chunk-5XVYBMAF.mjs → chunk-H3OBLXFX.mjs} +767 -514
  3. package/dist/development/dom-export.d.mts +13 -3
  4. package/dist/development/dom-export.d.ts +13 -3
  5. package/dist/development/dom-export.js +272 -108
  6. package/dist/development/dom-export.mjs +9 -6
  7. package/dist/{production/fog-of-war-7V7BguJA.d.ts → development/fog-of-war-Bt7PejVF.d.ts} +91 -6
  8. package/dist/development/{fog-of-war-NQCW9yWR.d.mts → fog-of-war-Dz4n-TU-.d.mts} +91 -6
  9. package/dist/development/index.d.mts +10 -19
  10. package/dist/development/index.d.ts +10 -19
  11. package/dist/development/index.js +767 -514
  12. package/dist/development/index.mjs +2 -2
  13. package/dist/development/lib/types/route-module.d.mts +6 -2
  14. package/dist/development/lib/types/route-module.d.ts +6 -2
  15. package/dist/development/lib/types/route-module.js +1 -1
  16. package/dist/development/lib/types/route-module.mjs +1 -1
  17. package/dist/development/{route-data-JFOfNyPS.d.ts → route-data-C96IyGKo.d.mts} +37 -15
  18. package/dist/{production/route-data-JFOfNyPS.d.mts → development/route-data-C96IyGKo.d.ts} +37 -15
  19. package/dist/production/{chunk-CKFZHSMW.mjs → chunk-YBZNESR7.mjs} +767 -514
  20. package/dist/production/dom-export.d.mts +13 -3
  21. package/dist/production/dom-export.d.ts +13 -3
  22. package/dist/production/dom-export.js +272 -108
  23. package/dist/production/dom-export.mjs +9 -6
  24. package/dist/{development/fog-of-war-7V7BguJA.d.ts → production/fog-of-war-Bt7PejVF.d.ts} +91 -6
  25. package/dist/production/{fog-of-war-NQCW9yWR.d.mts → fog-of-war-Dz4n-TU-.d.mts} +91 -6
  26. package/dist/production/index.d.mts +10 -19
  27. package/dist/production/index.d.ts +10 -19
  28. package/dist/production/index.js +767 -514
  29. package/dist/production/index.mjs +2 -2
  30. package/dist/production/lib/types/route-module.d.mts +6 -2
  31. package/dist/production/lib/types/route-module.d.ts +6 -2
  32. package/dist/production/lib/types/route-module.js +1 -1
  33. package/dist/production/lib/types/route-module.mjs +1 -1
  34. package/dist/production/{route-data-JFOfNyPS.d.ts → route-data-C96IyGKo.d.mts} +37 -15
  35. package/dist/{development/route-data-JFOfNyPS.d.mts → production/route-data-C96IyGKo.d.ts} +37 -15
  36. package/package.json +2 -17
  37. package/dist/development/server.d.mts +0 -988
  38. package/dist/development/server.d.ts +0 -988
  39. package/dist/development/server.js +0 -1429
  40. package/dist/development/server.mjs +0 -1406
  41. package/dist/production/server.d.mts +0 -988
  42. package/dist/production/server.d.ts +0 -988
  43. package/dist/production/server.js +0 -1405
  44. package/dist/production/server.mjs +0 -1382
@@ -1,1429 +0,0 @@
1
- 'use strict';
2
-
3
- var React = require('react');
4
-
5
- function _interopNamespace(e) {
6
- if (e && e.__esModule) return e;
7
- var n = Object.create(null);
8
- if (e) {
9
- Object.keys(e).forEach(function (k) {
10
- if (k !== 'default') {
11
- var d = Object.getOwnPropertyDescriptor(e, k);
12
- Object.defineProperty(n, k, d.get ? d : {
13
- enumerable: true,
14
- get: function () { return e[k]; }
15
- });
16
- }
17
- });
18
- }
19
- n.default = e;
20
- return Object.freeze(n);
21
- }
22
-
23
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
24
-
25
- /**
26
- * react-router v0.0.0-experimental-1ebb6d403
27
- *
28
- * Copyright (c) Remix Software Inc.
29
- *
30
- * This source code is licensed under the MIT license found in the
31
- * LICENSE.md file in the root directory of this source tree.
32
- *
33
- * @license MIT
34
- */
35
-
36
- // lib/router/history.ts
37
- function invariant(value, message) {
38
- if (value === false || value === null || typeof value === "undefined") {
39
- throw new Error(message);
40
- }
41
- }
42
- function warning(cond, message) {
43
- if (!cond) {
44
- if (typeof console !== "undefined") console.warn(message);
45
- try {
46
- throw new Error(message);
47
- } catch (e) {
48
- }
49
- }
50
- }
51
- function createKey() {
52
- return Math.random().toString(36).substring(2, 10);
53
- }
54
- function createLocation(current, to, state = null, key) {
55
- let location = {
56
- pathname: typeof current === "string" ? current : current.pathname,
57
- search: "",
58
- hash: "",
59
- ...typeof to === "string" ? parsePath(to) : to,
60
- state,
61
- // TODO: This could be cleaned up. push/replace should probably just take
62
- // full Locations now and avoid the need to run through this flow at all
63
- // But that's a pretty big refactor to the current test suite so going to
64
- // keep as is for the time being and just let any incoming keys take precedence
65
- key: to && to.key || key || createKey()
66
- };
67
- return location;
68
- }
69
- function createPath({
70
- pathname = "/",
71
- search = "",
72
- hash = ""
73
- }) {
74
- if (search && search !== "?")
75
- pathname += search.charAt(0) === "?" ? search : "?" + search;
76
- if (hash && hash !== "#")
77
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
78
- return pathname;
79
- }
80
- function parsePath(path) {
81
- let parsedPath = {};
82
- if (path) {
83
- let hashIndex = path.indexOf("#");
84
- if (hashIndex >= 0) {
85
- parsedPath.hash = path.substring(hashIndex);
86
- path = path.substring(0, hashIndex);
87
- }
88
- let searchIndex = path.indexOf("?");
89
- if (searchIndex >= 0) {
90
- parsedPath.search = path.substring(searchIndex);
91
- path = path.substring(0, searchIndex);
92
- }
93
- if (path) {
94
- parsedPath.pathname = path;
95
- }
96
- }
97
- return parsedPath;
98
- }
99
-
100
- // lib/router/utils.ts
101
- var immutableRouteKeys = /* @__PURE__ */ new Set([
102
- "lazy",
103
- "caseSensitive",
104
- "path",
105
- "id",
106
- "index",
107
- "children"
108
- ]);
109
- function isIndexRoute(route) {
110
- return route.index === true;
111
- }
112
- function convertRoutesToDataRoutes(routes, mapRouteProperties2, parentPath = [], manifest = {}) {
113
- return routes.map((route, index) => {
114
- let treePath = [...parentPath, String(index)];
115
- let id = typeof route.id === "string" ? route.id : treePath.join("-");
116
- invariant(
117
- route.index !== true || !route.children,
118
- `Cannot specify children on an index route`
119
- );
120
- invariant(
121
- !manifest[id],
122
- `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
123
- );
124
- if (isIndexRoute(route)) {
125
- let indexRoute = {
126
- ...route,
127
- ...mapRouteProperties2(route),
128
- id
129
- };
130
- manifest[id] = indexRoute;
131
- return indexRoute;
132
- } else {
133
- let pathOrLayoutRoute = {
134
- ...route,
135
- ...mapRouteProperties2(route),
136
- id,
137
- children: void 0
138
- };
139
- manifest[id] = pathOrLayoutRoute;
140
- if (route.children) {
141
- pathOrLayoutRoute.children = convertRoutesToDataRoutes(
142
- route.children,
143
- mapRouteProperties2,
144
- treePath,
145
- manifest
146
- );
147
- }
148
- return pathOrLayoutRoute;
149
- }
150
- });
151
- }
152
- function matchRoutes(routes, locationArg, basename = "/") {
153
- return matchRoutesImpl(routes, locationArg, basename, false);
154
- }
155
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
156
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
157
- let pathname = stripBasename(location.pathname || "/", basename);
158
- if (pathname == null) {
159
- return null;
160
- }
161
- let branches = flattenRoutes(routes);
162
- rankRouteBranches(branches);
163
- let matches = null;
164
- for (let i = 0; matches == null && i < branches.length; ++i) {
165
- let decoded = decodePath(pathname);
166
- matches = matchRouteBranch(
167
- branches[i],
168
- decoded,
169
- allowPartial
170
- );
171
- }
172
- return matches;
173
- }
174
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
175
- let flattenRoute = (route, index, relativePath) => {
176
- let meta = {
177
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
178
- caseSensitive: route.caseSensitive === true,
179
- childrenIndex: index,
180
- route
181
- };
182
- if (meta.relativePath.startsWith("/")) {
183
- invariant(
184
- meta.relativePath.startsWith(parentPath),
185
- `Absolute route path "${meta.relativePath}" nested under path "${parentPath}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`
186
- );
187
- meta.relativePath = meta.relativePath.slice(parentPath.length);
188
- }
189
- let path = joinPaths([parentPath, meta.relativePath]);
190
- let routesMeta = parentsMeta.concat(meta);
191
- if (route.children && route.children.length > 0) {
192
- invariant(
193
- // Our types know better, but runtime JS may not!
194
- // @ts-expect-error
195
- route.index !== true,
196
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
197
- );
198
- flattenRoutes(route.children, branches, routesMeta, path);
199
- }
200
- if (route.path == null && !route.index) {
201
- return;
202
- }
203
- branches.push({
204
- path,
205
- score: computeScore(path, route.index),
206
- routesMeta
207
- });
208
- };
209
- routes.forEach((route, index) => {
210
- if (route.path === "" || !route.path?.includes("?")) {
211
- flattenRoute(route, index);
212
- } else {
213
- for (let exploded of explodeOptionalSegments(route.path)) {
214
- flattenRoute(route, index, exploded);
215
- }
216
- }
217
- });
218
- return branches;
219
- }
220
- function explodeOptionalSegments(path) {
221
- let segments = path.split("/");
222
- if (segments.length === 0) return [];
223
- let [first, ...rest] = segments;
224
- let isOptional = first.endsWith("?");
225
- let required = first.replace(/\?$/, "");
226
- if (rest.length === 0) {
227
- return isOptional ? [required, ""] : [required];
228
- }
229
- let restExploded = explodeOptionalSegments(rest.join("/"));
230
- let result = [];
231
- result.push(
232
- ...restExploded.map(
233
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
234
- )
235
- );
236
- if (isOptional) {
237
- result.push(...restExploded);
238
- }
239
- return result.map(
240
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
241
- );
242
- }
243
- function rankRouteBranches(branches) {
244
- branches.sort(
245
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
246
- a.routesMeta.map((meta) => meta.childrenIndex),
247
- b.routesMeta.map((meta) => meta.childrenIndex)
248
- )
249
- );
250
- }
251
- var paramRe = /^:[\w-]+$/;
252
- var dynamicSegmentValue = 3;
253
- var indexRouteValue = 2;
254
- var emptySegmentValue = 1;
255
- var staticSegmentValue = 10;
256
- var splatPenalty = -2;
257
- var isSplat = (s) => s === "*";
258
- function computeScore(path, index) {
259
- let segments = path.split("/");
260
- let initialScore = segments.length;
261
- if (segments.some(isSplat)) {
262
- initialScore += splatPenalty;
263
- }
264
- if (index) {
265
- initialScore += indexRouteValue;
266
- }
267
- return segments.filter((s) => !isSplat(s)).reduce(
268
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
269
- initialScore
270
- );
271
- }
272
- function compareIndexes(a, b) {
273
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
274
- return siblings ? (
275
- // If two routes are siblings, we should try to match the earlier sibling
276
- // first. This allows people to have fine-grained control over the matching
277
- // behavior by simply putting routes with identical paths in the order they
278
- // want them tried.
279
- a[a.length - 1] - b[b.length - 1]
280
- ) : (
281
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
282
- // so they sort equally.
283
- 0
284
- );
285
- }
286
- function matchRouteBranch(branch, pathname, allowPartial = false) {
287
- let { routesMeta } = branch;
288
- let matchedParams = {};
289
- let matchedPathname = "/";
290
- let matches = [];
291
- for (let i = 0; i < routesMeta.length; ++i) {
292
- let meta = routesMeta[i];
293
- let end = i === routesMeta.length - 1;
294
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
295
- let match = matchPath(
296
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
297
- remainingPathname
298
- );
299
- let route = meta.route;
300
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
301
- match = matchPath(
302
- {
303
- path: meta.relativePath,
304
- caseSensitive: meta.caseSensitive,
305
- end: false
306
- },
307
- remainingPathname
308
- );
309
- }
310
- if (!match) {
311
- return null;
312
- }
313
- Object.assign(matchedParams, match.params);
314
- matches.push({
315
- // TODO: Can this as be avoided?
316
- params: matchedParams,
317
- pathname: joinPaths([matchedPathname, match.pathname]),
318
- pathnameBase: normalizePathname(
319
- joinPaths([matchedPathname, match.pathnameBase])
320
- ),
321
- route
322
- });
323
- if (match.pathnameBase !== "/") {
324
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
325
- }
326
- }
327
- return matches;
328
- }
329
- function matchPath(pattern, pathname) {
330
- if (typeof pattern === "string") {
331
- pattern = { path: pattern, caseSensitive: false, end: true };
332
- }
333
- let [matcher, compiledParams] = compilePath(
334
- pattern.path,
335
- pattern.caseSensitive,
336
- pattern.end
337
- );
338
- let match = pathname.match(matcher);
339
- if (!match) return null;
340
- let matchedPathname = match[0];
341
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
342
- let captureGroups = match.slice(1);
343
- let params = compiledParams.reduce(
344
- (memo, { paramName, isOptional }, index) => {
345
- if (paramName === "*") {
346
- let splatValue = captureGroups[index] || "";
347
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
348
- }
349
- const value = captureGroups[index];
350
- if (isOptional && !value) {
351
- memo[paramName] = void 0;
352
- } else {
353
- memo[paramName] = (value || "").replace(/%2F/g, "/");
354
- }
355
- return memo;
356
- },
357
- {}
358
- );
359
- return {
360
- params,
361
- pathname: matchedPathname,
362
- pathnameBase,
363
- pattern
364
- };
365
- }
366
- function compilePath(path, caseSensitive = false, end = true) {
367
- warning(
368
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
369
- `Route path "${path}" will be treated as if it were "${path.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${path.replace(/\*$/, "/*")}".`
370
- );
371
- let params = [];
372
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
373
- /\/:([\w-]+)(\?)?/g,
374
- (_, paramName, isOptional) => {
375
- params.push({ paramName, isOptional: isOptional != null });
376
- return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
377
- }
378
- );
379
- if (path.endsWith("*")) {
380
- params.push({ paramName: "*" });
381
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
382
- } else if (end) {
383
- regexpSource += "\\/*$";
384
- } else if (path !== "" && path !== "/") {
385
- regexpSource += "(?:(?=\\/|$))";
386
- } else ;
387
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
388
- return [matcher, params];
389
- }
390
- function decodePath(value) {
391
- try {
392
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
393
- } catch (error) {
394
- warning(
395
- false,
396
- `The URL path "${value}" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
397
- );
398
- return value;
399
- }
400
- }
401
- function stripBasename(pathname, basename) {
402
- if (basename === "/") return pathname;
403
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
404
- return null;
405
- }
406
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
407
- let nextChar = pathname.charAt(startIndex);
408
- if (nextChar && nextChar !== "/") {
409
- return null;
410
- }
411
- return pathname.slice(startIndex) || "/";
412
- }
413
- function resolvePath(to, fromPathname = "/") {
414
- let {
415
- pathname: toPathname,
416
- search = "",
417
- hash = ""
418
- } = typeof to === "string" ? parsePath(to) : to;
419
- let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
420
- return {
421
- pathname,
422
- search: normalizeSearch(search),
423
- hash: normalizeHash(hash)
424
- };
425
- }
426
- function resolvePathname(relativePath, fromPathname) {
427
- let segments = fromPathname.replace(/\/+$/, "").split("/");
428
- let relativeSegments = relativePath.split("/");
429
- relativeSegments.forEach((segment) => {
430
- if (segment === "..") {
431
- if (segments.length > 1) segments.pop();
432
- } else if (segment !== ".") {
433
- segments.push(segment);
434
- }
435
- });
436
- return segments.length > 1 ? segments.join("/") : "/";
437
- }
438
- function getInvalidPathError(char, field, dest, path) {
439
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
440
- path
441
- )}]. Please separate it out to the \`to.${dest}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`;
442
- }
443
- function getPathContributingMatches(matches) {
444
- return matches.filter(
445
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
446
- );
447
- }
448
- function getResolveToMatches(matches) {
449
- let pathMatches = getPathContributingMatches(matches);
450
- return pathMatches.map(
451
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
452
- );
453
- }
454
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
455
- let to;
456
- if (typeof toArg === "string") {
457
- to = parsePath(toArg);
458
- } else {
459
- to = { ...toArg };
460
- invariant(
461
- !to.pathname || !to.pathname.includes("?"),
462
- getInvalidPathError("?", "pathname", "search", to)
463
- );
464
- invariant(
465
- !to.pathname || !to.pathname.includes("#"),
466
- getInvalidPathError("#", "pathname", "hash", to)
467
- );
468
- invariant(
469
- !to.search || !to.search.includes("#"),
470
- getInvalidPathError("#", "search", "hash", to)
471
- );
472
- }
473
- let isEmptyPath = toArg === "" || to.pathname === "";
474
- let toPathname = isEmptyPath ? "/" : to.pathname;
475
- let from;
476
- if (toPathname == null) {
477
- from = locationPathname;
478
- } else {
479
- let routePathnameIndex = routePathnames.length - 1;
480
- if (!isPathRelative && toPathname.startsWith("..")) {
481
- let toSegments = toPathname.split("/");
482
- while (toSegments[0] === "..") {
483
- toSegments.shift();
484
- routePathnameIndex -= 1;
485
- }
486
- to.pathname = toSegments.join("/");
487
- }
488
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
489
- }
490
- let path = resolvePath(to, from);
491
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
492
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
493
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
494
- path.pathname += "/";
495
- }
496
- return path;
497
- }
498
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
499
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
500
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
501
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
502
- var ErrorResponseImpl = class {
503
- constructor(status, statusText, data, internal = false) {
504
- this.status = status;
505
- this.statusText = statusText || "";
506
- this.internal = internal;
507
- if (data instanceof Error) {
508
- this.data = data.toString();
509
- this.error = data;
510
- } else {
511
- this.data = data;
512
- }
513
- }
514
- };
515
- function isRouteErrorResponse(error) {
516
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
517
- }
518
-
519
- // lib/router/router.ts
520
- var validMutationMethodsArr = [
521
- "POST",
522
- "PUT",
523
- "PATCH",
524
- "DELETE"
525
- ];
526
- var validMutationMethods = new Set(
527
- validMutationMethodsArr
528
- );
529
- var validRequestMethodsArr = [
530
- "GET",
531
- ...validMutationMethodsArr
532
- ];
533
- var validRequestMethods = new Set(validRequestMethodsArr);
534
- var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
535
- var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
536
- var defaultMapRouteProperties = (route) => ({
537
- hasErrorBoundary: Boolean(route.hasErrorBoundary)
538
- });
539
- var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
540
- function createStaticHandler(routes, opts) {
541
- invariant(
542
- routes.length > 0,
543
- "You must provide a non-empty routes array to createStaticHandler"
544
- );
545
- let manifest = {};
546
- let basename = (opts ? opts.basename : null) || "/";
547
- let mapRouteProperties2 = opts?.mapRouteProperties || defaultMapRouteProperties;
548
- let dataRoutes = convertRoutesToDataRoutes(
549
- routes,
550
- mapRouteProperties2,
551
- void 0,
552
- manifest
553
- );
554
- async function query(request, {
555
- requestContext,
556
- skipLoaderErrorBubbling,
557
- dataStrategy
558
- } = {}) {
559
- let url = new URL(request.url);
560
- let method = request.method;
561
- let location = createLocation("", createPath(url), null, "default");
562
- let matches = matchRoutes(dataRoutes, location, basename);
563
- if (!isValidMethod(method) && method !== "HEAD") {
564
- let error = getInternalRouterError(405, { method });
565
- let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
566
- return {
567
- basename,
568
- location,
569
- matches: methodNotAllowedMatches,
570
- loaderData: {},
571
- actionData: null,
572
- errors: {
573
- [route.id]: error
574
- },
575
- statusCode: error.status,
576
- loaderHeaders: {},
577
- actionHeaders: {}
578
- };
579
- } else if (!matches) {
580
- let error = getInternalRouterError(404, { pathname: location.pathname });
581
- let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
582
- return {
583
- basename,
584
- location,
585
- matches: notFoundMatches,
586
- loaderData: {},
587
- actionData: null,
588
- errors: {
589
- [route.id]: error
590
- },
591
- statusCode: error.status,
592
- loaderHeaders: {},
593
- actionHeaders: {}
594
- };
595
- }
596
- let result = await queryImpl(
597
- request,
598
- location,
599
- matches,
600
- requestContext,
601
- dataStrategy || null,
602
- skipLoaderErrorBubbling === true,
603
- null
604
- );
605
- if (isResponse(result)) {
606
- return result;
607
- }
608
- return { location, basename, ...result };
609
- }
610
- async function queryRoute(request, {
611
- routeId,
612
- requestContext,
613
- dataStrategy
614
- } = {}) {
615
- let url = new URL(request.url);
616
- let method = request.method;
617
- let location = createLocation("", createPath(url), null, "default");
618
- let matches = matchRoutes(dataRoutes, location, basename);
619
- if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
620
- throw getInternalRouterError(405, { method });
621
- } else if (!matches) {
622
- throw getInternalRouterError(404, { pathname: location.pathname });
623
- }
624
- let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
625
- if (routeId && !match) {
626
- throw getInternalRouterError(403, {
627
- pathname: location.pathname,
628
- routeId
629
- });
630
- } else if (!match) {
631
- throw getInternalRouterError(404, { pathname: location.pathname });
632
- }
633
- let result = await queryImpl(
634
- request,
635
- location,
636
- matches,
637
- requestContext,
638
- dataStrategy || null,
639
- false,
640
- match
641
- );
642
- if (isResponse(result)) {
643
- return result;
644
- }
645
- let error = result.errors ? Object.values(result.errors)[0] : void 0;
646
- if (error !== void 0) {
647
- throw error;
648
- }
649
- if (result.actionData) {
650
- return Object.values(result.actionData)[0];
651
- }
652
- if (result.loaderData) {
653
- return Object.values(result.loaderData)[0];
654
- }
655
- return void 0;
656
- }
657
- async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch) {
658
- invariant(
659
- request.signal,
660
- "query()/queryRoute() requests must contain an AbortController signal"
661
- );
662
- try {
663
- if (isMutationMethod(request.method)) {
664
- let result2 = await submit(
665
- request,
666
- matches,
667
- routeMatch || getTargetMatch(matches, location),
668
- requestContext,
669
- dataStrategy,
670
- skipLoaderErrorBubbling,
671
- routeMatch != null
672
- );
673
- return result2;
674
- }
675
- let result = await loadRouteData(
676
- request,
677
- matches,
678
- requestContext,
679
- dataStrategy,
680
- skipLoaderErrorBubbling,
681
- routeMatch
682
- );
683
- return isResponse(result) ? result : {
684
- ...result,
685
- actionData: null,
686
- actionHeaders: {}
687
- };
688
- } catch (e) {
689
- if (isDataStrategyResult(e) && isResponse(e.result)) {
690
- if (e.type === "error" /* error */) {
691
- throw e.result;
692
- }
693
- return e.result;
694
- }
695
- if (isRedirectResponse(e)) {
696
- return e;
697
- }
698
- throw e;
699
- }
700
- }
701
- async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {
702
- let result;
703
- if (!actionMatch.route.action && !actionMatch.route.lazy) {
704
- let error = getInternalRouterError(405, {
705
- method: request.method,
706
- pathname: new URL(request.url).pathname,
707
- routeId: actionMatch.route.id
708
- });
709
- if (isRouteRequest) {
710
- throw error;
711
- }
712
- result = {
713
- type: "error" /* error */,
714
- error
715
- };
716
- } else {
717
- let results = await callDataStrategy(
718
- "action",
719
- request,
720
- [actionMatch],
721
- matches,
722
- isRouteRequest,
723
- requestContext,
724
- dataStrategy
725
- );
726
- result = results[actionMatch.route.id];
727
- if (request.signal.aborted) {
728
- throwStaticHandlerAbortedError(request, isRouteRequest);
729
- }
730
- }
731
- if (isRedirectResult(result)) {
732
- throw new Response(null, {
733
- status: result.response.status,
734
- headers: {
735
- Location: result.response.headers.get("Location")
736
- }
737
- });
738
- }
739
- if (isRouteRequest) {
740
- if (isErrorResult(result)) {
741
- throw result.error;
742
- }
743
- return {
744
- matches: [actionMatch],
745
- loaderData: {},
746
- actionData: { [actionMatch.route.id]: result.data },
747
- errors: null,
748
- // Note: statusCode + headers are unused here since queryRoute will
749
- // return the raw Response or value
750
- statusCode: 200,
751
- loaderHeaders: {},
752
- actionHeaders: {}
753
- };
754
- }
755
- let loaderRequest = new Request(request.url, {
756
- headers: request.headers,
757
- redirect: request.redirect,
758
- signal: request.signal
759
- });
760
- if (isErrorResult(result)) {
761
- let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
762
- let context2 = await loadRouteData(
763
- loaderRequest,
764
- matches,
765
- requestContext,
766
- dataStrategy,
767
- skipLoaderErrorBubbling,
768
- null,
769
- [boundaryMatch.route.id, result]
770
- );
771
- return {
772
- ...context2,
773
- statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
774
- actionData: null,
775
- actionHeaders: {
776
- ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
777
- }
778
- };
779
- }
780
- let context = await loadRouteData(
781
- loaderRequest,
782
- matches,
783
- requestContext,
784
- dataStrategy,
785
- skipLoaderErrorBubbling,
786
- null
787
- );
788
- return {
789
- ...context,
790
- actionData: {
791
- [actionMatch.route.id]: result.data
792
- },
793
- // action status codes take precedence over loader status codes
794
- ...result.statusCode ? { statusCode: result.statusCode } : {},
795
- actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
796
- };
797
- }
798
- async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {
799
- let isRouteRequest = routeMatch != null;
800
- if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
801
- throw getInternalRouterError(400, {
802
- method: request.method,
803
- pathname: new URL(request.url).pathname,
804
- routeId: routeMatch?.route.id
805
- });
806
- }
807
- let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;
808
- let matchesToLoad = requestMatches.filter(
809
- (m) => m.route.loader || m.route.lazy
810
- );
811
- if (matchesToLoad.length === 0) {
812
- return {
813
- matches,
814
- // Add a null for all matched routes for proper revalidation on the client
815
- loaderData: matches.reduce(
816
- (acc, m) => Object.assign(acc, { [m.route.id]: null }),
817
- {}
818
- ),
819
- errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
820
- [pendingActionResult[0]]: pendingActionResult[1].error
821
- } : null,
822
- statusCode: 200,
823
- loaderHeaders: {}
824
- };
825
- }
826
- let results = await callDataStrategy(
827
- "loader",
828
- request,
829
- matchesToLoad,
830
- matches,
831
- isRouteRequest,
832
- requestContext,
833
- dataStrategy
834
- );
835
- if (request.signal.aborted) {
836
- throwStaticHandlerAbortedError(request, isRouteRequest);
837
- }
838
- let context = processRouteLoaderData(
839
- matches,
840
- results,
841
- pendingActionResult,
842
- true,
843
- skipLoaderErrorBubbling
844
- );
845
- let executedLoaders = new Set(
846
- matchesToLoad.map((match) => match.route.id)
847
- );
848
- matches.forEach((match) => {
849
- if (!executedLoaders.has(match.route.id)) {
850
- context.loaderData[match.route.id] = null;
851
- }
852
- });
853
- return {
854
- ...context,
855
- matches
856
- };
857
- }
858
- async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, dataStrategy) {
859
- let results = await callDataStrategyImpl(
860
- dataStrategy || defaultDataStrategy,
861
- type,
862
- null,
863
- request,
864
- matchesToLoad,
865
- matches,
866
- null,
867
- manifest,
868
- mapRouteProperties2,
869
- requestContext
870
- );
871
- let dataResults = {};
872
- await Promise.all(
873
- matches.map(async (match) => {
874
- if (!(match.route.id in results)) {
875
- return;
876
- }
877
- let result = results[match.route.id];
878
- if (isRedirectDataStrategyResult(result)) {
879
- let response = result.result;
880
- throw normalizeRelativeRoutingRedirectResponse(
881
- response,
882
- request,
883
- match.route.id,
884
- matches,
885
- basename
886
- );
887
- }
888
- if (isResponse(result.result) && isRouteRequest) {
889
- throw result;
890
- }
891
- dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
892
- })
893
- );
894
- return dataResults;
895
- }
896
- return {
897
- dataRoutes,
898
- query,
899
- queryRoute
900
- };
901
- }
902
- function throwStaticHandlerAbortedError(request, isRouteRequest) {
903
- if (request.signal.reason !== void 0) {
904
- throw request.signal.reason;
905
- }
906
- let method = isRouteRequest ? "queryRoute" : "query";
907
- throw new Error(
908
- `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
909
- );
910
- }
911
- function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
912
- let contextualMatches;
913
- let activeRouteMatch;
914
- {
915
- contextualMatches = matches;
916
- activeRouteMatch = matches[matches.length - 1];
917
- }
918
- let path = resolveTo(
919
- to ? to : ".",
920
- getResolveToMatches(contextualMatches),
921
- stripBasename(location.pathname, basename) || location.pathname,
922
- relative === "path"
923
- );
924
- if (to == null) {
925
- path.search = location.search;
926
- path.hash = location.hash;
927
- }
928
- if ((to == null || to === "" || to === ".") && activeRouteMatch) {
929
- let nakedIndex = hasNakedIndexQuery(path.search);
930
- if (activeRouteMatch.route.index && !nakedIndex) {
931
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
932
- } else if (!activeRouteMatch.route.index && nakedIndex) {
933
- let params = new URLSearchParams(path.search);
934
- let indexValues = params.getAll("index");
935
- params.delete("index");
936
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
937
- let qs = params.toString();
938
- path.search = qs ? `?${qs}` : "";
939
- }
940
- }
941
- if (basename !== "/") {
942
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
943
- }
944
- return createPath(path);
945
- }
946
- function getLoaderMatchesUntilBoundary(matches, boundaryId, includeBoundary = false) {
947
- let index = matches.findIndex((m) => m.route.id === boundaryId);
948
- if (index >= 0) {
949
- return matches.slice(0, includeBoundary ? index + 1 : index);
950
- }
951
- return matches;
952
- }
953
- async function loadLazyRouteModule(route, mapRouteProperties2, manifest) {
954
- if (!route.lazy) {
955
- return;
956
- }
957
- let lazyRoute = await route.lazy();
958
- if (!route.lazy) {
959
- return;
960
- }
961
- let routeToUpdate = manifest[route.id];
962
- invariant(routeToUpdate, "No route found in manifest");
963
- let routeUpdates = {};
964
- for (let lazyRouteProperty in lazyRoute) {
965
- let staticRouteValue = routeToUpdate[lazyRouteProperty];
966
- let isPropertyStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
967
- // on the route updates
968
- lazyRouteProperty !== "hasErrorBoundary";
969
- warning(
970
- !isPropertyStaticallyDefined,
971
- `Route "${routeToUpdate.id}" has a static property "${lazyRouteProperty}" defined but its lazy function is also returning a value for this property. The lazy route property "${lazyRouteProperty}" will be ignored.`
972
- );
973
- if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {
974
- routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];
975
- }
976
- }
977
- Object.assign(routeToUpdate, routeUpdates);
978
- Object.assign(routeToUpdate, {
979
- // To keep things framework agnostic, we use the provided `mapRouteProperties`
980
- // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
981
- // since the logic will differ between frameworks.
982
- ...mapRouteProperties2(routeToUpdate),
983
- lazy: void 0
984
- });
985
- }
986
- async function defaultDataStrategy({
987
- matches
988
- }) {
989
- let matchesToLoad = matches.filter((m) => m.shouldLoad);
990
- let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
991
- return results.reduce(
992
- (acc, result, i) => Object.assign(acc, { [matchesToLoad[i].route.id]: result }),
993
- {}
994
- );
995
- }
996
- async function callDataStrategyImpl(dataStrategyImpl, type, state, request, matchesToLoad, matches, fetcherKey, manifest, mapRouteProperties2, requestContext) {
997
- let loadRouteDefinitionsPromises = matches.map(
998
- (m) => m.route.lazy ? loadLazyRouteModule(m.route, mapRouteProperties2, manifest) : void 0
999
- );
1000
- let dsMatches = matches.map((match, i) => {
1001
- let loadRoutePromise = loadRouteDefinitionsPromises[i];
1002
- let shouldLoad = matchesToLoad.some((m) => m.route.id === match.route.id);
1003
- let resolve = async (handlerOverride) => {
1004
- if (handlerOverride && request.method === "GET" && (match.route.lazy || match.route.loader)) {
1005
- shouldLoad = true;
1006
- }
1007
- return shouldLoad ? callLoaderOrAction(
1008
- type,
1009
- request,
1010
- match,
1011
- loadRoutePromise,
1012
- handlerOverride,
1013
- requestContext
1014
- ) : Promise.resolve({ type: "data" /* data */, result: void 0 });
1015
- };
1016
- return {
1017
- ...match,
1018
- shouldLoad,
1019
- resolve
1020
- };
1021
- });
1022
- let results = await dataStrategyImpl({
1023
- matches: dsMatches,
1024
- request,
1025
- params: matches[0].params,
1026
- fetcherKey,
1027
- context: requestContext
1028
- });
1029
- try {
1030
- await Promise.all(loadRouteDefinitionsPromises);
1031
- } catch (e) {
1032
- }
1033
- return results;
1034
- }
1035
- async function callLoaderOrAction(type, request, match, loadRoutePromise, handlerOverride, staticContext) {
1036
- let result;
1037
- let onReject;
1038
- let runHandler = (handler) => {
1039
- let reject;
1040
- let abortPromise = new Promise((_, r) => reject = r);
1041
- onReject = () => reject();
1042
- request.signal.addEventListener("abort", onReject);
1043
- let actualHandler = (ctx) => {
1044
- if (typeof handler !== "function") {
1045
- return Promise.reject(
1046
- new Error(
1047
- `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
1048
- )
1049
- );
1050
- }
1051
- return handler(
1052
- {
1053
- request,
1054
- params: match.params,
1055
- context: staticContext
1056
- },
1057
- ...ctx !== void 0 ? [ctx] : []
1058
- );
1059
- };
1060
- let handlerPromise = (async () => {
1061
- try {
1062
- let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
1063
- return { type: "data", result: val };
1064
- } catch (e) {
1065
- return { type: "error", result: e };
1066
- }
1067
- })();
1068
- return Promise.race([handlerPromise, abortPromise]);
1069
- };
1070
- try {
1071
- let handler = match.route[type];
1072
- if (loadRoutePromise) {
1073
- if (handler) {
1074
- let handlerError;
1075
- let [value] = await Promise.all([
1076
- // If the handler throws, don't let it immediately bubble out,
1077
- // since we need to let the lazy() execution finish so we know if this
1078
- // route has a boundary that can handle the error
1079
- runHandler(handler).catch((e) => {
1080
- handlerError = e;
1081
- }),
1082
- loadRoutePromise
1083
- ]);
1084
- if (handlerError !== void 0) {
1085
- throw handlerError;
1086
- }
1087
- result = value;
1088
- } else {
1089
- await loadRoutePromise;
1090
- handler = match.route[type];
1091
- if (handler) {
1092
- result = await runHandler(handler);
1093
- } else if (type === "action") {
1094
- let url = new URL(request.url);
1095
- let pathname = url.pathname + url.search;
1096
- throw getInternalRouterError(405, {
1097
- method: request.method,
1098
- pathname,
1099
- routeId: match.route.id
1100
- });
1101
- } else {
1102
- return { type: "data" /* data */, result: void 0 };
1103
- }
1104
- }
1105
- } else if (!handler) {
1106
- let url = new URL(request.url);
1107
- let pathname = url.pathname + url.search;
1108
- throw getInternalRouterError(404, {
1109
- pathname
1110
- });
1111
- } else {
1112
- result = await runHandler(handler);
1113
- }
1114
- } catch (e) {
1115
- return { type: "error" /* error */, result: e };
1116
- } finally {
1117
- if (onReject) {
1118
- request.signal.removeEventListener("abort", onReject);
1119
- }
1120
- }
1121
- return result;
1122
- }
1123
- async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1124
- let { result, type } = dataStrategyResult;
1125
- if (isResponse(result)) {
1126
- let data;
1127
- try {
1128
- let contentType = result.headers.get("Content-Type");
1129
- if (contentType && /\bapplication\/json\b/.test(contentType)) {
1130
- if (result.body == null) {
1131
- data = null;
1132
- } else {
1133
- data = await result.json();
1134
- }
1135
- } else {
1136
- data = await result.text();
1137
- }
1138
- } catch (e) {
1139
- return { type: "error" /* error */, error: e };
1140
- }
1141
- if (type === "error" /* error */) {
1142
- return {
1143
- type: "error" /* error */,
1144
- error: new ErrorResponseImpl(result.status, result.statusText, data),
1145
- statusCode: result.status,
1146
- headers: result.headers
1147
- };
1148
- }
1149
- return {
1150
- type: "data" /* data */,
1151
- data,
1152
- statusCode: result.status,
1153
- headers: result.headers
1154
- };
1155
- }
1156
- if (type === "error" /* error */) {
1157
- if (isDataWithResponseInit(result)) {
1158
- if (result.data instanceof Error) {
1159
- return {
1160
- type: "error" /* error */,
1161
- error: result.data,
1162
- statusCode: result.init?.status
1163
- };
1164
- }
1165
- result = new ErrorResponseImpl(
1166
- result.init?.status || 500,
1167
- void 0,
1168
- result.data
1169
- );
1170
- }
1171
- return {
1172
- type: "error" /* error */,
1173
- error: result,
1174
- statusCode: isRouteErrorResponse(result) ? result.status : void 0
1175
- };
1176
- }
1177
- if (isDataWithResponseInit(result)) {
1178
- return {
1179
- type: "data" /* data */,
1180
- data: result.data,
1181
- statusCode: result.init?.status,
1182
- headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1183
- };
1184
- }
1185
- return { type: "data" /* data */, data: result };
1186
- }
1187
- function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
1188
- let location = response.headers.get("Location");
1189
- invariant(
1190
- location,
1191
- "Redirects returned/thrown from loaders/actions must have a Location header"
1192
- );
1193
- if (!ABSOLUTE_URL_REGEX.test(location)) {
1194
- let trimmedMatches = matches.slice(
1195
- 0,
1196
- matches.findIndex((m) => m.route.id === routeId) + 1
1197
- );
1198
- location = normalizeTo(
1199
- new URL(request.url),
1200
- trimmedMatches,
1201
- basename,
1202
- location
1203
- );
1204
- response.headers.set("Location", location);
1205
- }
1206
- return response;
1207
- }
1208
- function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
1209
- let loaderData = {};
1210
- let errors = null;
1211
- let statusCode;
1212
- let foundError = false;
1213
- let loaderHeaders = {};
1214
- let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
1215
- matches.forEach((match) => {
1216
- if (!(match.route.id in results)) {
1217
- return;
1218
- }
1219
- let id = match.route.id;
1220
- let result = results[id];
1221
- invariant(
1222
- !isRedirectResult(result),
1223
- "Cannot handle redirect results in processLoaderData"
1224
- );
1225
- if (isErrorResult(result)) {
1226
- let error = result.error;
1227
- if (pendingError !== void 0) {
1228
- error = pendingError;
1229
- pendingError = void 0;
1230
- }
1231
- errors = errors || {};
1232
- if (skipLoaderErrorBubbling) {
1233
- errors[id] = error;
1234
- } else {
1235
- let boundaryMatch = findNearestBoundary(matches, id);
1236
- if (errors[boundaryMatch.route.id] == null) {
1237
- errors[boundaryMatch.route.id] = error;
1238
- }
1239
- }
1240
- if (!isStaticHandler) {
1241
- loaderData[id] = ResetLoaderDataSymbol;
1242
- }
1243
- if (!foundError) {
1244
- foundError = true;
1245
- statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
1246
- }
1247
- if (result.headers) {
1248
- loaderHeaders[id] = result.headers;
1249
- }
1250
- } else {
1251
- loaderData[id] = result.data;
1252
- if (result.statusCode && result.statusCode !== 200 && !foundError) {
1253
- statusCode = result.statusCode;
1254
- }
1255
- if (result.headers) {
1256
- loaderHeaders[id] = result.headers;
1257
- }
1258
- }
1259
- });
1260
- if (pendingError !== void 0 && pendingActionResult) {
1261
- errors = { [pendingActionResult[0]]: pendingError };
1262
- loaderData[pendingActionResult[0]] = void 0;
1263
- }
1264
- return {
1265
- loaderData,
1266
- errors,
1267
- statusCode: statusCode || 200,
1268
- loaderHeaders
1269
- };
1270
- }
1271
- function findNearestBoundary(matches, routeId) {
1272
- let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
1273
- return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
1274
- }
1275
- function getShortCircuitMatches(routes) {
1276
- let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
1277
- id: `__shim-error-route__`
1278
- };
1279
- return {
1280
- matches: [
1281
- {
1282
- params: {},
1283
- pathname: "",
1284
- pathnameBase: "",
1285
- route
1286
- }
1287
- ],
1288
- route
1289
- };
1290
- }
1291
- function getInternalRouterError(status, {
1292
- pathname,
1293
- routeId,
1294
- method,
1295
- type,
1296
- message
1297
- } = {}) {
1298
- let statusText = "Unknown Server Error";
1299
- let errorMessage = "Unknown @remix-run/router error";
1300
- if (status === 400) {
1301
- statusText = "Bad Request";
1302
- if (method && pathname && routeId) {
1303
- errorMessage = `You made a ${method} request to "${pathname}" but did not provide a \`loader\` for route "${routeId}", so there is no way to handle the request.`;
1304
- } else if (type === "invalid-body") {
1305
- errorMessage = "Unable to encode submission body";
1306
- }
1307
- } else if (status === 403) {
1308
- statusText = "Forbidden";
1309
- errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
1310
- } else if (status === 404) {
1311
- statusText = "Not Found";
1312
- errorMessage = `No route matches URL "${pathname}"`;
1313
- } else if (status === 405) {
1314
- statusText = "Method Not Allowed";
1315
- if (method && pathname && routeId) {
1316
- errorMessage = `You made a ${method.toUpperCase()} request to "${pathname}" but did not provide an \`action\` for route "${routeId}", so there is no way to handle the request.`;
1317
- } else if (method) {
1318
- errorMessage = `Invalid request method "${method.toUpperCase()}"`;
1319
- }
1320
- }
1321
- return new ErrorResponseImpl(
1322
- status || 500,
1323
- statusText,
1324
- new Error(errorMessage),
1325
- true
1326
- );
1327
- }
1328
- function isDataStrategyResult(result) {
1329
- return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
1330
- }
1331
- function isRedirectDataStrategyResult(result) {
1332
- return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
1333
- }
1334
- function isErrorResult(result) {
1335
- return result.type === "error" /* error */;
1336
- }
1337
- function isRedirectResult(result) {
1338
- return (result && result.type) === "redirect" /* redirect */;
1339
- }
1340
- function isDataWithResponseInit(value) {
1341
- return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
1342
- }
1343
- function isResponse(value) {
1344
- return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
1345
- }
1346
- function isRedirectStatusCode(statusCode) {
1347
- return redirectStatusCodes.has(statusCode);
1348
- }
1349
- function isRedirectResponse(result) {
1350
- return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
1351
- }
1352
- function isValidMethod(method) {
1353
- return validRequestMethods.has(method.toUpperCase());
1354
- }
1355
- function isMutationMethod(method) {
1356
- return validMutationMethods.has(method.toUpperCase());
1357
- }
1358
- function hasNakedIndexQuery(search) {
1359
- return new URLSearchParams(search).getAll("index").some((v) => v === "");
1360
- }
1361
- function getTargetMatch(matches, location) {
1362
- let search = typeof location === "string" ? parsePath(location).search : location.search;
1363
- if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
1364
- return matches[matches.length - 1];
1365
- }
1366
- let pathMatches = getPathContributingMatches(matches);
1367
- return pathMatches[pathMatches.length - 1];
1368
- }
1369
- function mapRouteProperties(route) {
1370
- let updates = {
1371
- // Note: this check also occurs in createRoutesFromChildren so update
1372
- // there if you change this -- please and thank you!
1373
- hasErrorBoundary: route.hasErrorBoundary || route.ErrorBoundary != null || route.errorElement != null
1374
- };
1375
- if (route.Component) {
1376
- {
1377
- if (route.element) {
1378
- warning(
1379
- false,
1380
- "You should not include both `Component` and `element` on your route - `Component` will be used."
1381
- );
1382
- }
1383
- }
1384
- Object.assign(updates, {
1385
- element: React__namespace.createElement(route.Component),
1386
- Component: void 0
1387
- });
1388
- }
1389
- if (route.HydrateFallback) {
1390
- {
1391
- if (route.hydrateFallbackElement) {
1392
- warning(
1393
- false,
1394
- "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."
1395
- );
1396
- }
1397
- }
1398
- Object.assign(updates, {
1399
- hydrateFallbackElement: React__namespace.createElement(route.HydrateFallback),
1400
- HydrateFallback: void 0
1401
- });
1402
- }
1403
- if (route.ErrorBoundary) {
1404
- {
1405
- if (route.errorElement) {
1406
- warning(
1407
- false,
1408
- "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."
1409
- );
1410
- }
1411
- }
1412
- Object.assign(updates, {
1413
- errorElement: React__namespace.createElement(route.ErrorBoundary),
1414
- ErrorBoundary: void 0
1415
- });
1416
- }
1417
- return updates;
1418
- }
1419
-
1420
- // lib/dom/server.tsx
1421
- function createStaticHandler2(routes, opts) {
1422
- return createStaticHandler(routes, {
1423
- ...opts,
1424
- mapRouteProperties
1425
- });
1426
- }
1427
-
1428
- exports.createStaticHandler = createStaticHandler2;
1429
- exports.matchRoutes = matchRoutes;