react-router 0.0.0-experimental-a6d1d1d4e → 0.0.0-experimental-1d760f6a6

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 +12 -0
  2. package/dist/development/{chunk-OEAMHMGQ.mjs → chunk-QBMD7MNB.mjs} +293 -1025
  3. package/dist/development/dom-export.d.mts +2 -2
  4. package/dist/development/dom-export.d.ts +2 -2
  5. package/dist/development/dom-export.js +69 -103
  6. package/dist/development/dom-export.mjs +2 -2
  7. package/dist/development/{fog-of-war-DrUCUQQ-.d.ts → fog-of-war-BLArG-qZ.d.ts} +81 -168
  8. package/dist/{production/fog-of-war-C5L_Yd5M.d.mts → development/fog-of-war-D2zsXvum.d.mts} +81 -168
  9. package/dist/development/index.d.mts +8 -15
  10. package/dist/development/index.d.ts +8 -15
  11. package/dist/development/index.js +291 -1032
  12. package/dist/development/index.mjs +2 -19
  13. package/dist/development/lib/types/route-module.d.mts +1 -1
  14. package/dist/development/lib/types/route-module.d.ts +1 -1
  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-BIYebJr3.d.ts → route-data-C12CLHiN.d.mts} +1 -11
  18. package/dist/{production/route-data-BIYebJr3.d.mts → development/route-data-C12CLHiN.d.ts} +1 -11
  19. package/dist/production/{chunk-I2N4LFMP.mjs → chunk-DSJGM2GU.mjs} +293 -1025
  20. package/dist/production/dom-export.d.mts +2 -2
  21. package/dist/production/dom-export.d.ts +2 -2
  22. package/dist/production/dom-export.js +69 -103
  23. package/dist/production/dom-export.mjs +2 -2
  24. package/dist/production/{fog-of-war-DrUCUQQ-.d.ts → fog-of-war-BLArG-qZ.d.ts} +81 -168
  25. package/dist/{development/fog-of-war-C5L_Yd5M.d.mts → production/fog-of-war-D2zsXvum.d.mts} +81 -168
  26. package/dist/production/index.d.mts +8 -15
  27. package/dist/production/index.d.ts +8 -15
  28. package/dist/production/index.js +291 -1032
  29. package/dist/production/index.mjs +2 -19
  30. package/dist/production/lib/types/route-module.d.mts +1 -1
  31. package/dist/production/lib/types/route-module.d.ts +1 -1
  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-BIYebJr3.d.ts → route-data-C12CLHiN.d.mts} +1 -11
  35. package/dist/{development/route-data-BIYebJr3.d.mts → production/route-data-C12CLHiN.d.ts} +1 -11
  36. package/package.json +2 -33
  37. package/dist/development/rsc-export.d.mts +0 -1553
  38. package/dist/development/rsc-export.d.ts +0 -1553
  39. package/dist/development/rsc-export.js +0 -2413
  40. package/dist/development/rsc-export.mjs +0 -2385
  41. package/dist/production/rsc-export.d.mts +0 -1553
  42. package/dist/production/rsc-export.d.ts +0 -1553
  43. package/dist/production/rsc-export.js +0 -2413
  44. package/dist/production/rsc-export.mjs +0 -2385
@@ -1,2413 +0,0 @@
1
- 'use strict';
2
-
3
- var React = require('react');
4
- var setCookieParser = require('set-cookie-parser');
5
- var reactRouter = require('react-router');
6
-
7
- function _interopNamespace(e) {
8
- if (e && e.__esModule) return e;
9
- var n = Object.create(null);
10
- if (e) {
11
- Object.keys(e).forEach(function (k) {
12
- if (k !== 'default') {
13
- var d = Object.getOwnPropertyDescriptor(e, k);
14
- Object.defineProperty(n, k, d.get ? d : {
15
- enumerable: true,
16
- get: function () { return e[k]; }
17
- });
18
- }
19
- });
20
- }
21
- n.default = e;
22
- return Object.freeze(n);
23
- }
24
-
25
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
26
-
27
- /**
28
- * react-router v0.0.0-experimental-a6d1d1d4e
29
- *
30
- * Copyright (c) Remix Software Inc.
31
- *
32
- * This source code is licensed under the MIT license found in the
33
- * LICENSE.md file in the root directory of this source tree.
34
- *
35
- * @license MIT
36
- */
37
- var __typeError = (msg) => {
38
- throw TypeError(msg);
39
- };
40
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
41
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
42
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
43
-
44
- // lib/router/history.ts
45
- function invariant(value, message) {
46
- if (value === false || value === null || typeof value === "undefined") {
47
- throw new Error(message);
48
- }
49
- }
50
- function warning(cond, message) {
51
- if (!cond) {
52
- if (typeof console !== "undefined") console.warn(message);
53
- try {
54
- throw new Error(message);
55
- } catch (e) {
56
- }
57
- }
58
- }
59
- function createKey() {
60
- return Math.random().toString(36).substring(2, 10);
61
- }
62
- function createLocation(current, to, state = null, key) {
63
- let location = {
64
- pathname: typeof current === "string" ? current : current.pathname,
65
- search: "",
66
- hash: "",
67
- ...typeof to === "string" ? parsePath(to) : to,
68
- state,
69
- // TODO: This could be cleaned up. push/replace should probably just take
70
- // full Locations now and avoid the need to run through this flow at all
71
- // But that's a pretty big refactor to the current test suite so going to
72
- // keep as is for the time being and just let any incoming keys take precedence
73
- key: to && to.key || key || createKey()
74
- };
75
- return location;
76
- }
77
- function createPath({
78
- pathname = "/",
79
- search = "",
80
- hash = ""
81
- }) {
82
- if (search && search !== "?")
83
- pathname += search.charAt(0) === "?" ? search : "?" + search;
84
- if (hash && hash !== "#")
85
- pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
86
- return pathname;
87
- }
88
- function parsePath(path) {
89
- let parsedPath = {};
90
- if (path) {
91
- let hashIndex = path.indexOf("#");
92
- if (hashIndex >= 0) {
93
- parsedPath.hash = path.substring(hashIndex);
94
- path = path.substring(0, hashIndex);
95
- }
96
- let searchIndex = path.indexOf("?");
97
- if (searchIndex >= 0) {
98
- parsedPath.search = path.substring(searchIndex);
99
- path = path.substring(0, searchIndex);
100
- }
101
- if (path) {
102
- parsedPath.pathname = path;
103
- }
104
- }
105
- return parsedPath;
106
- }
107
-
108
- // lib/router/utils.ts
109
- var _map;
110
- var unstable_RouterContextProvider = class {
111
- constructor(init) {
112
- __privateAdd(this, _map, /* @__PURE__ */ new Map());
113
- if (init) {
114
- for (let [context, value] of init) {
115
- this.set(context, value);
116
- }
117
- }
118
- }
119
- get(context) {
120
- if (__privateGet(this, _map).has(context)) {
121
- return __privateGet(this, _map).get(context);
122
- }
123
- if (context.defaultValue !== void 0) {
124
- return context.defaultValue;
125
- }
126
- throw new Error("No value found for context");
127
- }
128
- set(context, value) {
129
- __privateGet(this, _map).set(context, value);
130
- }
131
- };
132
- _map = new WeakMap();
133
- var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
134
- "lazy",
135
- "caseSensitive",
136
- "path",
137
- "id",
138
- "index",
139
- "children"
140
- ]);
141
- function isUnsupportedLazyRouteObjectKey(key) {
142
- return unsupportedLazyRouteObjectKeys.has(
143
- key
144
- );
145
- }
146
- var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
147
- "lazy",
148
- "caseSensitive",
149
- "path",
150
- "id",
151
- "index",
152
- "unstable_middleware",
153
- "children"
154
- ]);
155
- function isUnsupportedLazyRouteFunctionKey(key) {
156
- return unsupportedLazyRouteFunctionKeys.has(
157
- key
158
- );
159
- }
160
- function isIndexRoute(route) {
161
- return route.index === true;
162
- }
163
- function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
164
- return routes.map((route, index) => {
165
- let treePath = [...parentPath, String(index)];
166
- let id = typeof route.id === "string" ? route.id : treePath.join("-");
167
- invariant(
168
- route.index !== true || !route.children,
169
- `Cannot specify children on an index route`
170
- );
171
- invariant(
172
- allowInPlaceMutations || !manifest[id],
173
- `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
174
- );
175
- if (isIndexRoute(route)) {
176
- let indexRoute = {
177
- ...route,
178
- ...mapRouteProperties(route),
179
- id
180
- };
181
- manifest[id] = indexRoute;
182
- return indexRoute;
183
- } else {
184
- let pathOrLayoutRoute = {
185
- ...route,
186
- ...mapRouteProperties(route),
187
- id,
188
- children: void 0
189
- };
190
- manifest[id] = pathOrLayoutRoute;
191
- if (route.children) {
192
- pathOrLayoutRoute.children = convertRoutesToDataRoutes(
193
- route.children,
194
- mapRouteProperties,
195
- treePath,
196
- manifest,
197
- allowInPlaceMutations
198
- );
199
- }
200
- return pathOrLayoutRoute;
201
- }
202
- });
203
- }
204
- function matchRoutes(routes, locationArg, basename = "/") {
205
- return matchRoutesImpl(routes, locationArg, basename, false);
206
- }
207
- function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
208
- let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
209
- let pathname = stripBasename(location.pathname || "/", basename);
210
- if (pathname == null) {
211
- return null;
212
- }
213
- let branches = flattenRoutes(routes);
214
- rankRouteBranches(branches);
215
- let matches = null;
216
- for (let i = 0; matches == null && i < branches.length; ++i) {
217
- let decoded = decodePath(pathname);
218
- matches = matchRouteBranch(
219
- branches[i],
220
- decoded,
221
- allowPartial
222
- );
223
- }
224
- return matches;
225
- }
226
- function convertRouteMatchToUiMatch(match, loaderData) {
227
- let { route, pathname, params } = match;
228
- return {
229
- id: route.id,
230
- pathname,
231
- params,
232
- data: loaderData[route.id],
233
- handle: route.handle
234
- };
235
- }
236
- function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
237
- let flattenRoute = (route, index, relativePath) => {
238
- let meta = {
239
- relativePath: relativePath === void 0 ? route.path || "" : relativePath,
240
- caseSensitive: route.caseSensitive === true,
241
- childrenIndex: index,
242
- route
243
- };
244
- if (meta.relativePath.startsWith("/")) {
245
- invariant(
246
- meta.relativePath.startsWith(parentPath),
247
- `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.`
248
- );
249
- meta.relativePath = meta.relativePath.slice(parentPath.length);
250
- }
251
- let path = joinPaths([parentPath, meta.relativePath]);
252
- let routesMeta = parentsMeta.concat(meta);
253
- if (route.children && route.children.length > 0) {
254
- invariant(
255
- // Our types know better, but runtime JS may not!
256
- // @ts-expect-error
257
- route.index !== true,
258
- `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
259
- );
260
- flattenRoutes(route.children, branches, routesMeta, path);
261
- }
262
- if (route.path == null && !route.index) {
263
- return;
264
- }
265
- branches.push({
266
- path,
267
- score: computeScore(path, route.index),
268
- routesMeta
269
- });
270
- };
271
- routes.forEach((route, index) => {
272
- if (route.path === "" || !route.path?.includes("?")) {
273
- flattenRoute(route, index);
274
- } else {
275
- for (let exploded of explodeOptionalSegments(route.path)) {
276
- flattenRoute(route, index, exploded);
277
- }
278
- }
279
- });
280
- return branches;
281
- }
282
- function explodeOptionalSegments(path) {
283
- let segments = path.split("/");
284
- if (segments.length === 0) return [];
285
- let [first, ...rest] = segments;
286
- let isOptional = first.endsWith("?");
287
- let required = first.replace(/\?$/, "");
288
- if (rest.length === 0) {
289
- return isOptional ? [required, ""] : [required];
290
- }
291
- let restExploded = explodeOptionalSegments(rest.join("/"));
292
- let result = [];
293
- result.push(
294
- ...restExploded.map(
295
- (subpath) => subpath === "" ? required : [required, subpath].join("/")
296
- )
297
- );
298
- if (isOptional) {
299
- result.push(...restExploded);
300
- }
301
- return result.map(
302
- (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
303
- );
304
- }
305
- function rankRouteBranches(branches) {
306
- branches.sort(
307
- (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
308
- a.routesMeta.map((meta) => meta.childrenIndex),
309
- b.routesMeta.map((meta) => meta.childrenIndex)
310
- )
311
- );
312
- }
313
- var paramRe = /^:[\w-]+$/;
314
- var dynamicSegmentValue = 3;
315
- var indexRouteValue = 2;
316
- var emptySegmentValue = 1;
317
- var staticSegmentValue = 10;
318
- var splatPenalty = -2;
319
- var isSplat = (s) => s === "*";
320
- function computeScore(path, index) {
321
- let segments = path.split("/");
322
- let initialScore = segments.length;
323
- if (segments.some(isSplat)) {
324
- initialScore += splatPenalty;
325
- }
326
- if (index) {
327
- initialScore += indexRouteValue;
328
- }
329
- return segments.filter((s) => !isSplat(s)).reduce(
330
- (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
331
- initialScore
332
- );
333
- }
334
- function compareIndexes(a, b) {
335
- let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
336
- return siblings ? (
337
- // If two routes are siblings, we should try to match the earlier sibling
338
- // first. This allows people to have fine-grained control over the matching
339
- // behavior by simply putting routes with identical paths in the order they
340
- // want them tried.
341
- a[a.length - 1] - b[b.length - 1]
342
- ) : (
343
- // Otherwise, it doesn't really make sense to rank non-siblings by index,
344
- // so they sort equally.
345
- 0
346
- );
347
- }
348
- function matchRouteBranch(branch, pathname, allowPartial = false) {
349
- let { routesMeta } = branch;
350
- let matchedParams = {};
351
- let matchedPathname = "/";
352
- let matches = [];
353
- for (let i = 0; i < routesMeta.length; ++i) {
354
- let meta = routesMeta[i];
355
- let end = i === routesMeta.length - 1;
356
- let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
357
- let match = matchPath(
358
- { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
359
- remainingPathname
360
- );
361
- let route = meta.route;
362
- if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
363
- match = matchPath(
364
- {
365
- path: meta.relativePath,
366
- caseSensitive: meta.caseSensitive,
367
- end: false
368
- },
369
- remainingPathname
370
- );
371
- }
372
- if (!match) {
373
- return null;
374
- }
375
- Object.assign(matchedParams, match.params);
376
- matches.push({
377
- // TODO: Can this as be avoided?
378
- params: matchedParams,
379
- pathname: joinPaths([matchedPathname, match.pathname]),
380
- pathnameBase: normalizePathname(
381
- joinPaths([matchedPathname, match.pathnameBase])
382
- ),
383
- route
384
- });
385
- if (match.pathnameBase !== "/") {
386
- matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
387
- }
388
- }
389
- return matches;
390
- }
391
- function matchPath(pattern, pathname) {
392
- if (typeof pattern === "string") {
393
- pattern = { path: pattern, caseSensitive: false, end: true };
394
- }
395
- let [matcher, compiledParams] = compilePath(
396
- pattern.path,
397
- pattern.caseSensitive,
398
- pattern.end
399
- );
400
- let match = pathname.match(matcher);
401
- if (!match) return null;
402
- let matchedPathname = match[0];
403
- let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
404
- let captureGroups = match.slice(1);
405
- let params = compiledParams.reduce(
406
- (memo, { paramName, isOptional }, index) => {
407
- if (paramName === "*") {
408
- let splatValue = captureGroups[index] || "";
409
- pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
410
- }
411
- const value = captureGroups[index];
412
- if (isOptional && !value) {
413
- memo[paramName] = void 0;
414
- } else {
415
- memo[paramName] = (value || "").replace(/%2F/g, "/");
416
- }
417
- return memo;
418
- },
419
- {}
420
- );
421
- return {
422
- params,
423
- pathname: matchedPathname,
424
- pathnameBase,
425
- pattern
426
- };
427
- }
428
- function compilePath(path, caseSensitive = false, end = true) {
429
- warning(
430
- path === "*" || !path.endsWith("*") || path.endsWith("/*"),
431
- `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(/\*$/, "/*")}".`
432
- );
433
- let params = [];
434
- let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
435
- /\/:([\w-]+)(\?)?/g,
436
- (_, paramName, isOptional) => {
437
- params.push({ paramName, isOptional: isOptional != null });
438
- return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
439
- }
440
- );
441
- if (path.endsWith("*")) {
442
- params.push({ paramName: "*" });
443
- regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
444
- } else if (end) {
445
- regexpSource += "\\/*$";
446
- } else if (path !== "" && path !== "/") {
447
- regexpSource += "(?:(?=\\/|$))";
448
- } else ;
449
- let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
450
- return [matcher, params];
451
- }
452
- function decodePath(value) {
453
- try {
454
- return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
455
- } catch (error) {
456
- warning(
457
- false,
458
- `The URL path "${value}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${error}).`
459
- );
460
- return value;
461
- }
462
- }
463
- function stripBasename(pathname, basename) {
464
- if (basename === "/") return pathname;
465
- if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
466
- return null;
467
- }
468
- let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
469
- let nextChar = pathname.charAt(startIndex);
470
- if (nextChar && nextChar !== "/") {
471
- return null;
472
- }
473
- return pathname.slice(startIndex) || "/";
474
- }
475
- function resolvePath(to, fromPathname = "/") {
476
- let {
477
- pathname: toPathname,
478
- search = "",
479
- hash = ""
480
- } = typeof to === "string" ? parsePath(to) : to;
481
- let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
482
- return {
483
- pathname,
484
- search: normalizeSearch(search),
485
- hash: normalizeHash(hash)
486
- };
487
- }
488
- function resolvePathname(relativePath, fromPathname) {
489
- let segments = fromPathname.replace(/\/+$/, "").split("/");
490
- let relativeSegments = relativePath.split("/");
491
- relativeSegments.forEach((segment) => {
492
- if (segment === "..") {
493
- if (segments.length > 1) segments.pop();
494
- } else if (segment !== ".") {
495
- segments.push(segment);
496
- }
497
- });
498
- return segments.length > 1 ? segments.join("/") : "/";
499
- }
500
- function getInvalidPathError(char, field, dest, path) {
501
- return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
502
- path
503
- )}]. 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.`;
504
- }
505
- function getPathContributingMatches(matches) {
506
- return matches.filter(
507
- (match, index) => index === 0 || match.route.path && match.route.path.length > 0
508
- );
509
- }
510
- function getResolveToMatches(matches) {
511
- let pathMatches = getPathContributingMatches(matches);
512
- return pathMatches.map(
513
- (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
514
- );
515
- }
516
- function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
517
- let to;
518
- if (typeof toArg === "string") {
519
- to = parsePath(toArg);
520
- } else {
521
- to = { ...toArg };
522
- invariant(
523
- !to.pathname || !to.pathname.includes("?"),
524
- getInvalidPathError("?", "pathname", "search", to)
525
- );
526
- invariant(
527
- !to.pathname || !to.pathname.includes("#"),
528
- getInvalidPathError("#", "pathname", "hash", to)
529
- );
530
- invariant(
531
- !to.search || !to.search.includes("#"),
532
- getInvalidPathError("#", "search", "hash", to)
533
- );
534
- }
535
- let isEmptyPath = toArg === "" || to.pathname === "";
536
- let toPathname = isEmptyPath ? "/" : to.pathname;
537
- let from;
538
- if (toPathname == null) {
539
- from = locationPathname;
540
- } else {
541
- let routePathnameIndex = routePathnames.length - 1;
542
- if (!isPathRelative && toPathname.startsWith("..")) {
543
- let toSegments = toPathname.split("/");
544
- while (toSegments[0] === "..") {
545
- toSegments.shift();
546
- routePathnameIndex -= 1;
547
- }
548
- to.pathname = toSegments.join("/");
549
- }
550
- from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
551
- }
552
- let path = resolvePath(to, from);
553
- let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
554
- let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
555
- if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
556
- path.pathname += "/";
557
- }
558
- return path;
559
- }
560
- var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
561
- var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
562
- var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
563
- var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
564
- var DataWithResponseInit = class {
565
- constructor(data2, init) {
566
- this.type = "DataWithResponseInit";
567
- this.data = data2;
568
- this.init = init || null;
569
- }
570
- };
571
- function data(data2, init) {
572
- return new DataWithResponseInit(
573
- data2,
574
- typeof init === "number" ? { status: init } : init
575
- );
576
- }
577
- var redirect = (url, init = 302) => {
578
- let responseInit = init;
579
- if (typeof responseInit === "number") {
580
- responseInit = { status: responseInit };
581
- } else if (typeof responseInit.status === "undefined") {
582
- responseInit.status = 302;
583
- }
584
- let headers = new Headers(responseInit.headers);
585
- headers.set("Location", url);
586
- return new Response(null, { ...responseInit, headers });
587
- };
588
- var redirectDocument = (url, init) => {
589
- let response = redirect(url, init);
590
- response.headers.set("X-Remix-Reload-Document", "true");
591
- return response;
592
- };
593
- var replace = (url, init) => {
594
- let response = redirect(url, init);
595
- response.headers.set("X-Remix-Replace", "true");
596
- return response;
597
- };
598
- var ErrorResponseImpl = class {
599
- constructor(status, statusText, data2, internal = false) {
600
- this.status = status;
601
- this.statusText = statusText || "";
602
- this.internal = internal;
603
- if (data2 instanceof Error) {
604
- this.data = data2.toString();
605
- this.error = data2;
606
- } else {
607
- this.data = data2;
608
- }
609
- }
610
- };
611
- function isRouteErrorResponse(error) {
612
- return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
613
- }
614
-
615
- // lib/router/router.ts
616
- var validMutationMethodsArr = [
617
- "POST",
618
- "PUT",
619
- "PATCH",
620
- "DELETE"
621
- ];
622
- var validMutationMethods = new Set(
623
- validMutationMethodsArr
624
- );
625
- var validRequestMethodsArr = [
626
- "GET",
627
- ...validMutationMethodsArr
628
- ];
629
- var validRequestMethods = new Set(validRequestMethodsArr);
630
- var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
631
- var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
632
- var defaultMapRouteProperties = (route) => ({
633
- hasErrorBoundary: Boolean(route.hasErrorBoundary)
634
- });
635
- var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
636
- function createStaticHandler(routes, opts) {
637
- invariant(
638
- routes.length > 0,
639
- "You must provide a non-empty routes array to createStaticHandler"
640
- );
641
- let manifest = {};
642
- let basename = (opts ? opts.basename : null) || "/";
643
- let mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
644
- let dataRoutes = convertRoutesToDataRoutes(
645
- routes,
646
- mapRouteProperties,
647
- void 0,
648
- manifest
649
- );
650
- async function query(request, {
651
- requestContext,
652
- filterMatchesToLoad,
653
- skipLoaderErrorBubbling,
654
- skipRevalidation,
655
- dataStrategy,
656
- unstable_respond: respond
657
- } = {}) {
658
- let url = new URL(request.url);
659
- let method = request.method;
660
- let location = createLocation("", createPath(url), null, "default");
661
- let matches = matchRoutes(dataRoutes, location, basename);
662
- requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
663
- if (!isValidMethod(method) && method !== "HEAD") {
664
- let error = getInternalRouterError(405, { method });
665
- let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
666
- let staticContext = {
667
- basename,
668
- location,
669
- matches: methodNotAllowedMatches,
670
- loaderData: {},
671
- actionData: null,
672
- errors: {
673
- [route.id]: error
674
- },
675
- statusCode: error.status,
676
- loaderHeaders: {},
677
- actionHeaders: {}
678
- };
679
- return respond ? respond(staticContext) : staticContext;
680
- } else if (!matches) {
681
- let error = getInternalRouterError(404, { pathname: location.pathname });
682
- let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
683
- let staticContext = {
684
- basename,
685
- location,
686
- matches: notFoundMatches,
687
- loaderData: {},
688
- actionData: null,
689
- errors: {
690
- [route.id]: error
691
- },
692
- statusCode: error.status,
693
- loaderHeaders: {},
694
- actionHeaders: {}
695
- };
696
- return respond ? respond(staticContext) : staticContext;
697
- }
698
- if (respond && matches.some(
699
- (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
700
- )) {
701
- invariant(
702
- requestContext instanceof unstable_RouterContextProvider,
703
- "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
704
- );
705
- try {
706
- await loadLazyMiddlewareForMatches(
707
- matches,
708
- manifest,
709
- mapRouteProperties
710
- );
711
- let renderedStaticContext;
712
- let response = await runMiddlewarePipeline(
713
- {
714
- request,
715
- matches,
716
- params: matches[0].params,
717
- // If we're calling middleware then it must be enabled so we can cast
718
- // this to the proper type knowing it's not an `AppLoadContext`
719
- context: requestContext
720
- },
721
- true,
722
- async () => {
723
- let result2 = await queryImpl(
724
- request,
725
- location,
726
- matches,
727
- requestContext,
728
- dataStrategy || null,
729
- skipLoaderErrorBubbling === true,
730
- null,
731
- filterMatchesToLoad || null,
732
- skipRevalidation === true
733
- );
734
- if (isResponse(result2)) {
735
- return result2;
736
- }
737
- renderedStaticContext = { location, basename, ...result2 };
738
- let res = await respond(renderedStaticContext);
739
- return res;
740
- },
741
- async (error, routeId) => {
742
- if (isResponse(error)) {
743
- return error;
744
- }
745
- if (renderedStaticContext) {
746
- if (routeId in renderedStaticContext.loaderData) {
747
- renderedStaticContext.loaderData[routeId] = void 0;
748
- }
749
- return respond(
750
- getStaticContextFromError(
751
- dataRoutes,
752
- renderedStaticContext,
753
- error,
754
- findNearestBoundary(matches, routeId).route.id
755
- )
756
- );
757
- } else {
758
- let loaderIdx = matches.findIndex((m) => m.route.loader);
759
- let boundary = loaderIdx >= 0 ? findNearestBoundary(matches, matches[loaderIdx].route.id) : findNearestBoundary(matches);
760
- return respond({
761
- matches,
762
- location,
763
- basename,
764
- loaderData: {},
765
- actionData: null,
766
- errors: {
767
- [boundary.route.id]: error
768
- },
769
- statusCode: isRouteErrorResponse(error) ? error.status : 500,
770
- actionHeaders: {},
771
- loaderHeaders: {}
772
- });
773
- }
774
- }
775
- );
776
- invariant(isResponse(response), "Expected a response in query()");
777
- return response;
778
- } catch (e) {
779
- if (isResponse(e)) {
780
- return e;
781
- }
782
- throw e;
783
- }
784
- }
785
- let result = await queryImpl(
786
- request,
787
- location,
788
- matches,
789
- requestContext,
790
- dataStrategy || null,
791
- skipLoaderErrorBubbling === true,
792
- null,
793
- filterMatchesToLoad || null,
794
- skipRevalidation === true
795
- );
796
- if (isResponse(result)) {
797
- return result;
798
- }
799
- return { location, basename, ...result };
800
- }
801
- async function queryRoute(request, {
802
- routeId,
803
- requestContext,
804
- dataStrategy,
805
- unstable_respond: respond
806
- } = {}) {
807
- let url = new URL(request.url);
808
- let method = request.method;
809
- let location = createLocation("", createPath(url), null, "default");
810
- let matches = matchRoutes(dataRoutes, location, basename);
811
- requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
812
- if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
813
- throw getInternalRouterError(405, { method });
814
- } else if (!matches) {
815
- throw getInternalRouterError(404, { pathname: location.pathname });
816
- }
817
- let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
818
- if (routeId && !match) {
819
- throw getInternalRouterError(403, {
820
- pathname: location.pathname,
821
- routeId
822
- });
823
- } else if (!match) {
824
- throw getInternalRouterError(404, { pathname: location.pathname });
825
- }
826
- if (respond && matches.some(
827
- (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
828
- )) {
829
- invariant(
830
- requestContext instanceof unstable_RouterContextProvider,
831
- "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
832
- );
833
- await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
834
- let response = await runMiddlewarePipeline(
835
- {
836
- request,
837
- matches,
838
- params: matches[0].params,
839
- // If we're calling middleware then it must be enabled so we can cast
840
- // this to the proper type knowing it's not an `AppLoadContext`
841
- context: requestContext
842
- },
843
- true,
844
- async () => {
845
- let result2 = await queryImpl(
846
- request,
847
- location,
848
- matches,
849
- requestContext,
850
- dataStrategy || null,
851
- false,
852
- match,
853
- null,
854
- false
855
- );
856
- if (isResponse(result2)) {
857
- return respond(result2);
858
- }
859
- let error2 = result2.errors ? Object.values(result2.errors)[0] : void 0;
860
- if (error2 !== void 0) {
861
- throw error2;
862
- }
863
- let value = result2.actionData ? Object.values(result2.actionData)[0] : Object.values(result2.loaderData)[0];
864
- return typeof value === "string" ? new Response(value) : Response.json(value);
865
- },
866
- (error2) => {
867
- if (isResponse(error2)) {
868
- return respond(error2);
869
- }
870
- return new Response(String(error2), {
871
- status: 500,
872
- statusText: "Unexpected Server Error"
873
- });
874
- }
875
- );
876
- return response;
877
- }
878
- let result = await queryImpl(
879
- request,
880
- location,
881
- matches,
882
- requestContext,
883
- dataStrategy || null,
884
- false,
885
- match,
886
- null,
887
- false
888
- );
889
- if (isResponse(result)) {
890
- return result;
891
- }
892
- let error = result.errors ? Object.values(result.errors)[0] : void 0;
893
- if (error !== void 0) {
894
- throw error;
895
- }
896
- if (result.actionData) {
897
- return Object.values(result.actionData)[0];
898
- }
899
- if (result.loaderData) {
900
- return Object.values(result.loaderData)[0];
901
- }
902
- return void 0;
903
- }
904
- async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
905
- invariant(
906
- request.signal,
907
- "query()/queryRoute() requests must contain an AbortController signal"
908
- );
909
- try {
910
- if (isMutationMethod(request.method)) {
911
- let result2 = await submit(
912
- request,
913
- matches,
914
- routeMatch || getTargetMatch(matches, location),
915
- requestContext,
916
- dataStrategy,
917
- skipLoaderErrorBubbling,
918
- routeMatch != null,
919
- filterMatchesToLoad,
920
- skipRevalidation
921
- );
922
- return result2;
923
- }
924
- let result = await loadRouteData(
925
- request,
926
- matches,
927
- requestContext,
928
- dataStrategy,
929
- skipLoaderErrorBubbling,
930
- routeMatch,
931
- filterMatchesToLoad
932
- );
933
- return isResponse(result) ? result : {
934
- ...result,
935
- actionData: null,
936
- actionHeaders: {}
937
- };
938
- } catch (e) {
939
- if (isDataStrategyResult(e) && isResponse(e.result)) {
940
- if (e.type === "error" /* error */) {
941
- throw e.result;
942
- }
943
- return e.result;
944
- }
945
- if (isRedirectResponse(e)) {
946
- return e;
947
- }
948
- throw e;
949
- }
950
- }
951
- async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
952
- let result;
953
- if (!actionMatch.route.action && !actionMatch.route.lazy) {
954
- let error = getInternalRouterError(405, {
955
- method: request.method,
956
- pathname: new URL(request.url).pathname,
957
- routeId: actionMatch.route.id
958
- });
959
- if (isRouteRequest) {
960
- throw error;
961
- }
962
- result = {
963
- type: "error" /* error */,
964
- error
965
- };
966
- } else {
967
- let dsMatches = getTargetedDataStrategyMatches(
968
- mapRouteProperties,
969
- manifest,
970
- request,
971
- matches,
972
- actionMatch,
973
- [],
974
- requestContext
975
- );
976
- let results = await callDataStrategy(
977
- request,
978
- dsMatches,
979
- isRouteRequest,
980
- requestContext,
981
- dataStrategy
982
- );
983
- result = results[actionMatch.route.id];
984
- if (request.signal.aborted) {
985
- throwStaticHandlerAbortedError(request, isRouteRequest);
986
- }
987
- }
988
- if (isRedirectResult(result)) {
989
- throw new Response(null, {
990
- status: result.response.status,
991
- headers: {
992
- Location: result.response.headers.get("Location")
993
- }
994
- });
995
- }
996
- if (isRouteRequest) {
997
- if (isErrorResult(result)) {
998
- throw result.error;
999
- }
1000
- return {
1001
- matches: [actionMatch],
1002
- loaderData: {},
1003
- actionData: { [actionMatch.route.id]: result.data },
1004
- errors: null,
1005
- // Note: statusCode + headers are unused here since queryRoute will
1006
- // return the raw Response or value
1007
- statusCode: 200,
1008
- loaderHeaders: {},
1009
- actionHeaders: {}
1010
- };
1011
- }
1012
- if (skipRevalidation) {
1013
- if (isErrorResult(result)) {
1014
- let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1015
- return {
1016
- statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1017
- actionData: null,
1018
- actionHeaders: {
1019
- ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1020
- },
1021
- matches,
1022
- loaderData: {},
1023
- errors: {
1024
- [boundaryMatch.route.id]: result.error
1025
- },
1026
- loaderHeaders: {}
1027
- };
1028
- } else {
1029
- return {
1030
- actionData: {
1031
- [actionMatch.route.id]: result.data
1032
- },
1033
- actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1034
- matches,
1035
- loaderData: {},
1036
- errors: null,
1037
- statusCode: result.statusCode || 200,
1038
- loaderHeaders: {}
1039
- };
1040
- }
1041
- }
1042
- let loaderRequest = new Request(request.url, {
1043
- headers: request.headers,
1044
- redirect: request.redirect,
1045
- signal: request.signal
1046
- });
1047
- if (isErrorResult(result)) {
1048
- let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1049
- let handlerContext2 = await loadRouteData(
1050
- loaderRequest,
1051
- matches,
1052
- requestContext,
1053
- dataStrategy,
1054
- skipLoaderErrorBubbling,
1055
- null,
1056
- filterMatchesToLoad,
1057
- [boundaryMatch.route.id, result]
1058
- );
1059
- return {
1060
- ...handlerContext2,
1061
- statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1062
- actionData: null,
1063
- actionHeaders: {
1064
- ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1065
- }
1066
- };
1067
- }
1068
- let handlerContext = await loadRouteData(
1069
- loaderRequest,
1070
- matches,
1071
- requestContext,
1072
- dataStrategy,
1073
- skipLoaderErrorBubbling,
1074
- null,
1075
- filterMatchesToLoad
1076
- );
1077
- return {
1078
- ...handlerContext,
1079
- actionData: {
1080
- [actionMatch.route.id]: result.data
1081
- },
1082
- // action status codes take precedence over loader status codes
1083
- ...result.statusCode ? { statusCode: result.statusCode } : {},
1084
- actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1085
- };
1086
- }
1087
- async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1088
- let isRouteRequest = routeMatch != null;
1089
- if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
1090
- throw getInternalRouterError(400, {
1091
- method: request.method,
1092
- pathname: new URL(request.url).pathname,
1093
- routeId: routeMatch?.route.id
1094
- });
1095
- }
1096
- let dsMatches;
1097
- if (routeMatch) {
1098
- dsMatches = getTargetedDataStrategyMatches(
1099
- mapRouteProperties,
1100
- manifest,
1101
- request,
1102
- matches,
1103
- routeMatch,
1104
- [],
1105
- requestContext
1106
- );
1107
- } else {
1108
- let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
1109
- // Up to but not including the boundary
1110
- matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
1111
- ) : void 0;
1112
- dsMatches = matches.map((match, index) => {
1113
- if (maxIdx != null && index > maxIdx) {
1114
- return getDataStrategyMatch(
1115
- mapRouteProperties,
1116
- manifest,
1117
- request,
1118
- match,
1119
- [],
1120
- requestContext,
1121
- false
1122
- );
1123
- }
1124
- return getDataStrategyMatch(
1125
- mapRouteProperties,
1126
- manifest,
1127
- request,
1128
- match,
1129
- [],
1130
- requestContext,
1131
- (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
1132
- );
1133
- });
1134
- }
1135
- if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
1136
- return {
1137
- matches,
1138
- loaderData: {},
1139
- errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
1140
- [pendingActionResult[0]]: pendingActionResult[1].error
1141
- } : null,
1142
- statusCode: 200,
1143
- loaderHeaders: {}
1144
- };
1145
- }
1146
- let results = await callDataStrategy(
1147
- request,
1148
- dsMatches,
1149
- isRouteRequest,
1150
- requestContext,
1151
- dataStrategy
1152
- );
1153
- if (request.signal.aborted) {
1154
- throwStaticHandlerAbortedError(request, isRouteRequest);
1155
- }
1156
- let handlerContext = processRouteLoaderData(
1157
- matches,
1158
- results,
1159
- pendingActionResult,
1160
- true,
1161
- skipLoaderErrorBubbling
1162
- );
1163
- return {
1164
- ...handlerContext,
1165
- matches
1166
- };
1167
- }
1168
- async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
1169
- let results = await callDataStrategyImpl(
1170
- dataStrategy || defaultDataStrategy,
1171
- request,
1172
- matches,
1173
- null,
1174
- requestContext);
1175
- let dataResults = {};
1176
- await Promise.all(
1177
- matches.map(async (match) => {
1178
- if (!(match.route.id in results)) {
1179
- return;
1180
- }
1181
- let result = results[match.route.id];
1182
- if (isRedirectDataStrategyResult(result)) {
1183
- let response = result.result;
1184
- throw normalizeRelativeRoutingRedirectResponse(
1185
- response,
1186
- request,
1187
- match.route.id,
1188
- matches,
1189
- basename
1190
- );
1191
- }
1192
- if (isResponse(result.result) && isRouteRequest) {
1193
- throw result;
1194
- }
1195
- dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1196
- })
1197
- );
1198
- return dataResults;
1199
- }
1200
- return {
1201
- dataRoutes,
1202
- query,
1203
- queryRoute
1204
- };
1205
- }
1206
- function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1207
- let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1208
- return {
1209
- ...handlerContext,
1210
- statusCode: isRouteErrorResponse(error) ? error.status : 500,
1211
- errors: {
1212
- [errorBoundaryId]: error
1213
- }
1214
- };
1215
- }
1216
- function throwStaticHandlerAbortedError(request, isRouteRequest) {
1217
- if (request.signal.reason !== void 0) {
1218
- throw request.signal.reason;
1219
- }
1220
- let method = isRouteRequest ? "queryRoute" : "query";
1221
- throw new Error(
1222
- `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1223
- );
1224
- }
1225
- function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1226
- let contextualMatches;
1227
- let activeRouteMatch;
1228
- {
1229
- contextualMatches = matches;
1230
- activeRouteMatch = matches[matches.length - 1];
1231
- }
1232
- let path = resolveTo(
1233
- to ? to : ".",
1234
- getResolveToMatches(contextualMatches),
1235
- stripBasename(location.pathname, basename) || location.pathname,
1236
- relative === "path"
1237
- );
1238
- if (to == null) {
1239
- path.search = location.search;
1240
- path.hash = location.hash;
1241
- }
1242
- if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1243
- let nakedIndex = hasNakedIndexQuery(path.search);
1244
- if (activeRouteMatch.route.index && !nakedIndex) {
1245
- path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1246
- } else if (!activeRouteMatch.route.index && nakedIndex) {
1247
- let params = new URLSearchParams(path.search);
1248
- let indexValues = params.getAll("index");
1249
- params.delete("index");
1250
- indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1251
- let qs = params.toString();
1252
- path.search = qs ? `?${qs}` : "";
1253
- }
1254
- }
1255
- if (basename !== "/") {
1256
- path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
1257
- }
1258
- return createPath(path);
1259
- }
1260
- function shouldRevalidateLoader(loaderMatch, arg) {
1261
- if (loaderMatch.route.shouldRevalidate) {
1262
- let routeChoice = loaderMatch.route.shouldRevalidate(arg);
1263
- if (typeof routeChoice === "boolean") {
1264
- return routeChoice;
1265
- }
1266
- }
1267
- return arg.defaultShouldRevalidate;
1268
- }
1269
- var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
1270
- var loadLazyRouteProperty = ({
1271
- key,
1272
- route,
1273
- manifest,
1274
- mapRouteProperties
1275
- }) => {
1276
- let routeToUpdate = manifest[route.id];
1277
- invariant(routeToUpdate, "No route found in manifest");
1278
- if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
1279
- return;
1280
- }
1281
- let lazyFn = routeToUpdate.lazy[key];
1282
- if (!lazyFn) {
1283
- return;
1284
- }
1285
- let cache = lazyRoutePropertyCache.get(routeToUpdate);
1286
- if (!cache) {
1287
- cache = {};
1288
- lazyRoutePropertyCache.set(routeToUpdate, cache);
1289
- }
1290
- let cachedPromise = cache[key];
1291
- if (cachedPromise) {
1292
- return cachedPromise;
1293
- }
1294
- let propertyPromise = (async () => {
1295
- let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
1296
- let staticRouteValue = routeToUpdate[key];
1297
- let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
1298
- if (isUnsupported) {
1299
- warning(
1300
- !isUnsupported,
1301
- "Route property " + key + " is not a supported lazy route property. This property will be ignored."
1302
- );
1303
- cache[key] = Promise.resolve();
1304
- } else if (isStaticallyDefined) {
1305
- warning(
1306
- false,
1307
- `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
1308
- );
1309
- } else {
1310
- let value = await lazyFn();
1311
- if (value != null) {
1312
- Object.assign(routeToUpdate, { [key]: value });
1313
- Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
1314
- }
1315
- }
1316
- if (typeof routeToUpdate.lazy === "object") {
1317
- routeToUpdate.lazy[key] = void 0;
1318
- if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
1319
- routeToUpdate.lazy = void 0;
1320
- }
1321
- }
1322
- })();
1323
- cache[key] = propertyPromise;
1324
- return propertyPromise;
1325
- };
1326
- var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
1327
- function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
1328
- let routeToUpdate = manifest[route.id];
1329
- invariant(routeToUpdate, "No route found in manifest");
1330
- if (!route.lazy) {
1331
- return {
1332
- lazyRoutePromise: void 0,
1333
- lazyHandlerPromise: void 0
1334
- };
1335
- }
1336
- if (typeof route.lazy === "function") {
1337
- let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
1338
- if (cachedPromise) {
1339
- return {
1340
- lazyRoutePromise: cachedPromise,
1341
- lazyHandlerPromise: cachedPromise
1342
- };
1343
- }
1344
- let lazyRoutePromise2 = (async () => {
1345
- invariant(
1346
- typeof route.lazy === "function",
1347
- "No lazy route function found"
1348
- );
1349
- let lazyRoute = await route.lazy();
1350
- let routeUpdates = {};
1351
- for (let lazyRouteProperty in lazyRoute) {
1352
- let lazyValue = lazyRoute[lazyRouteProperty];
1353
- if (lazyValue === void 0) {
1354
- continue;
1355
- }
1356
- let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
1357
- let staticRouteValue = routeToUpdate[lazyRouteProperty];
1358
- let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
1359
- // on the route updates
1360
- lazyRouteProperty !== "hasErrorBoundary";
1361
- if (isUnsupported) {
1362
- warning(
1363
- !isUnsupported,
1364
- "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
1365
- );
1366
- } else if (isStaticallyDefined) {
1367
- warning(
1368
- !isStaticallyDefined,
1369
- `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.`
1370
- );
1371
- } else {
1372
- routeUpdates[lazyRouteProperty] = lazyValue;
1373
- }
1374
- }
1375
- Object.assign(routeToUpdate, routeUpdates);
1376
- Object.assign(routeToUpdate, {
1377
- // To keep things framework agnostic, we use the provided `mapRouteProperties`
1378
- // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
1379
- // since the logic will differ between frameworks.
1380
- ...mapRouteProperties(routeToUpdate),
1381
- lazy: void 0
1382
- });
1383
- })();
1384
- lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
1385
- lazyRoutePromise2.catch(() => {
1386
- });
1387
- return {
1388
- lazyRoutePromise: lazyRoutePromise2,
1389
- lazyHandlerPromise: lazyRoutePromise2
1390
- };
1391
- }
1392
- let lazyKeys = Object.keys(route.lazy);
1393
- let lazyPropertyPromises = [];
1394
- let lazyHandlerPromise = void 0;
1395
- for (let key of lazyKeys) {
1396
- if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
1397
- continue;
1398
- }
1399
- let promise = loadLazyRouteProperty({
1400
- key,
1401
- route,
1402
- manifest,
1403
- mapRouteProperties
1404
- });
1405
- if (promise) {
1406
- lazyPropertyPromises.push(promise);
1407
- if (key === type) {
1408
- lazyHandlerPromise = promise;
1409
- }
1410
- }
1411
- }
1412
- let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
1413
- }) : void 0;
1414
- lazyRoutePromise?.catch(() => {
1415
- });
1416
- lazyHandlerPromise?.catch(() => {
1417
- });
1418
- return {
1419
- lazyRoutePromise,
1420
- lazyHandlerPromise
1421
- };
1422
- }
1423
- function isNonNullable(value) {
1424
- return value !== void 0;
1425
- }
1426
- function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
1427
- let promises = matches.map(({ route }) => {
1428
- if (typeof route.lazy !== "object" || !route.lazy.unstable_middleware) {
1429
- return void 0;
1430
- }
1431
- return loadLazyRouteProperty({
1432
- key: "unstable_middleware",
1433
- route,
1434
- manifest,
1435
- mapRouteProperties
1436
- });
1437
- }).filter(isNonNullable);
1438
- return promises.length > 0 ? Promise.all(promises) : void 0;
1439
- }
1440
- async function defaultDataStrategy(args) {
1441
- let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
1442
- let keyedResults = {};
1443
- let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
1444
- results.forEach((result, i) => {
1445
- keyedResults[matchesToLoad[i].route.id] = result;
1446
- });
1447
- return keyedResults;
1448
- }
1449
- async function runMiddlewarePipeline(args, propagateResult, handler, errorHandler) {
1450
- let { matches, request, params, context } = args;
1451
- let middlewareState = {
1452
- handlerResult: void 0
1453
- };
1454
- try {
1455
- let tuples = matches.flatMap(
1456
- (m) => m.route.unstable_middleware ? m.route.unstable_middleware.map((fn) => [m.route.id, fn]) : []
1457
- );
1458
- let result = await callRouteMiddleware(
1459
- { request, params, context },
1460
- tuples,
1461
- propagateResult,
1462
- middlewareState,
1463
- handler
1464
- );
1465
- return propagateResult ? result : middlewareState.handlerResult;
1466
- } catch (e) {
1467
- if (!middlewareState.middlewareError) {
1468
- throw e;
1469
- }
1470
- let result = await errorHandler(
1471
- middlewareState.middlewareError.error,
1472
- middlewareState.middlewareError.routeId
1473
- );
1474
- if (propagateResult || !middlewareState.handlerResult) {
1475
- return result;
1476
- }
1477
- return Object.assign(middlewareState.handlerResult, result);
1478
- }
1479
- }
1480
- async function callRouteMiddleware(args, middlewares, propagateResult, middlewareState, handler, idx = 0) {
1481
- let { request } = args;
1482
- if (request.signal.aborted) {
1483
- if (request.signal.reason) {
1484
- throw request.signal.reason;
1485
- }
1486
- throw new Error(
1487
- `Request aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1488
- );
1489
- }
1490
- let tuple = middlewares[idx];
1491
- if (!tuple) {
1492
- middlewareState.handlerResult = await handler();
1493
- return middlewareState.handlerResult;
1494
- }
1495
- let [routeId, middleware] = tuple;
1496
- let nextCalled = false;
1497
- let nextResult = void 0;
1498
- let next = async () => {
1499
- if (nextCalled) {
1500
- throw new Error("You may only call `next()` once per middleware");
1501
- }
1502
- nextCalled = true;
1503
- let result = await callRouteMiddleware(
1504
- args,
1505
- middlewares,
1506
- propagateResult,
1507
- middlewareState,
1508
- handler,
1509
- idx + 1
1510
- );
1511
- if (propagateResult) {
1512
- nextResult = result;
1513
- return nextResult;
1514
- }
1515
- };
1516
- try {
1517
- let result = await middleware(
1518
- {
1519
- request: args.request,
1520
- params: args.params,
1521
- context: args.context
1522
- },
1523
- next
1524
- );
1525
- if (nextCalled) {
1526
- if (result === void 0) {
1527
- return nextResult;
1528
- } else {
1529
- return result;
1530
- }
1531
- } else {
1532
- return next();
1533
- }
1534
- } catch (error) {
1535
- if (!middlewareState.middlewareError) {
1536
- middlewareState.middlewareError = { routeId, error };
1537
- } else if (middlewareState.middlewareError.error !== error) {
1538
- middlewareState.middlewareError = { routeId, error };
1539
- }
1540
- throw error;
1541
- }
1542
- }
1543
- function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
1544
- let lazyMiddlewarePromise = loadLazyRouteProperty({
1545
- key: "unstable_middleware",
1546
- route: match.route,
1547
- manifest,
1548
- mapRouteProperties
1549
- });
1550
- let lazyRoutePromises = loadLazyRoute(
1551
- match.route,
1552
- isMutationMethod(request.method) ? "action" : "loader",
1553
- manifest,
1554
- mapRouteProperties,
1555
- lazyRoutePropertiesToSkip
1556
- );
1557
- return {
1558
- middleware: lazyMiddlewarePromise,
1559
- route: lazyRoutePromises.lazyRoutePromise,
1560
- handler: lazyRoutePromises.lazyHandlerPromise
1561
- };
1562
- }
1563
- function getDataStrategyMatch(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, unstable_shouldRevalidateArgs = null) {
1564
- let isUsingNewApi = false;
1565
- let _lazyPromises = getDataStrategyMatchLazyPromises(
1566
- mapRouteProperties,
1567
- manifest,
1568
- request,
1569
- match,
1570
- lazyRoutePropertiesToSkip
1571
- );
1572
- return {
1573
- ...match,
1574
- _lazyPromises,
1575
- shouldLoad,
1576
- unstable_shouldRevalidateArgs,
1577
- unstable_shouldCallHandler(defaultShouldRevalidate) {
1578
- isUsingNewApi = true;
1579
- if (!unstable_shouldRevalidateArgs) {
1580
- return shouldLoad;
1581
- }
1582
- if (typeof defaultShouldRevalidate === "boolean") {
1583
- return shouldRevalidateLoader(match, {
1584
- ...unstable_shouldRevalidateArgs,
1585
- defaultShouldRevalidate
1586
- });
1587
- }
1588
- return shouldRevalidateLoader(match, unstable_shouldRevalidateArgs);
1589
- },
1590
- resolve(handlerOverride) {
1591
- if (isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (match.route.lazy || match.route.loader)) {
1592
- return callLoaderOrAction({
1593
- request,
1594
- match,
1595
- lazyHandlerPromise: _lazyPromises?.handler,
1596
- lazyRoutePromise: _lazyPromises?.route,
1597
- handlerOverride,
1598
- scopedContext
1599
- });
1600
- }
1601
- return Promise.resolve({ type: "data" /* data */, result: void 0 });
1602
- }
1603
- };
1604
- }
1605
- function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
1606
- return matches.map((match) => {
1607
- if (match.route.id !== targetMatch.route.id) {
1608
- return {
1609
- ...match,
1610
- shouldLoad: false,
1611
- unstable_shouldRevalidateArgs: shouldRevalidateArgs,
1612
- unstable_shouldCallHandler: () => false,
1613
- _lazyPromises: getDataStrategyMatchLazyPromises(
1614
- mapRouteProperties,
1615
- manifest,
1616
- request,
1617
- match,
1618
- lazyRoutePropertiesToSkip
1619
- ),
1620
- resolve: () => Promise.resolve({ type: "data", result: void 0 })
1621
- };
1622
- }
1623
- return getDataStrategyMatch(
1624
- mapRouteProperties,
1625
- manifest,
1626
- request,
1627
- match,
1628
- lazyRoutePropertiesToSkip,
1629
- scopedContext,
1630
- true,
1631
- shouldRevalidateArgs
1632
- );
1633
- });
1634
- }
1635
- async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
1636
- if (matches.some((m) => m._lazyPromises?.middleware)) {
1637
- await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
1638
- }
1639
- let dataStrategyArgs = {
1640
- request,
1641
- params: matches[0].params,
1642
- context: scopedContext,
1643
- matches
1644
- };
1645
- let unstable_runClientMiddleware = () => {
1646
- throw new Error(
1647
- "You cannot call `unstable_runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`"
1648
- );
1649
- } ;
1650
- let results = await dataStrategyImpl({
1651
- ...dataStrategyArgs,
1652
- fetcherKey,
1653
- unstable_runClientMiddleware
1654
- });
1655
- try {
1656
- await Promise.all(
1657
- matches.flatMap((m) => [m._lazyPromises?.handler, m._lazyPromises?.route])
1658
- );
1659
- } catch (e) {
1660
- }
1661
- return results;
1662
- }
1663
- async function callLoaderOrAction({
1664
- request,
1665
- match,
1666
- lazyHandlerPromise,
1667
- lazyRoutePromise,
1668
- handlerOverride,
1669
- scopedContext
1670
- }) {
1671
- let result;
1672
- let onReject;
1673
- let isAction = isMutationMethod(request.method);
1674
- let type = isAction ? "action" : "loader";
1675
- let runHandler = (handler) => {
1676
- let reject;
1677
- let abortPromise = new Promise((_, r) => reject = r);
1678
- onReject = () => reject();
1679
- request.signal.addEventListener("abort", onReject);
1680
- let actualHandler = (ctx) => {
1681
- if (typeof handler !== "function") {
1682
- return Promise.reject(
1683
- new Error(
1684
- `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
1685
- )
1686
- );
1687
- }
1688
- return handler(
1689
- {
1690
- request,
1691
- params: match.params,
1692
- context: scopedContext
1693
- },
1694
- ...ctx !== void 0 ? [ctx] : []
1695
- );
1696
- };
1697
- let handlerPromise = (async () => {
1698
- try {
1699
- let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
1700
- return { type: "data", result: val };
1701
- } catch (e) {
1702
- return { type: "error", result: e };
1703
- }
1704
- })();
1705
- return Promise.race([handlerPromise, abortPromise]);
1706
- };
1707
- try {
1708
- let handler = isAction ? match.route.action : match.route.loader;
1709
- if (lazyHandlerPromise || lazyRoutePromise) {
1710
- if (handler) {
1711
- let handlerError;
1712
- let [value] = await Promise.all([
1713
- // If the handler throws, don't let it immediately bubble out,
1714
- // since we need to let the lazy() execution finish so we know if this
1715
- // route has a boundary that can handle the error
1716
- runHandler(handler).catch((e) => {
1717
- handlerError = e;
1718
- }),
1719
- // Ensure all lazy route promises are resolved before continuing
1720
- lazyHandlerPromise,
1721
- lazyRoutePromise
1722
- ]);
1723
- if (handlerError !== void 0) {
1724
- throw handlerError;
1725
- }
1726
- result = value;
1727
- } else {
1728
- await lazyHandlerPromise;
1729
- let handler2 = isAction ? match.route.action : match.route.loader;
1730
- if (handler2) {
1731
- [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
1732
- } else if (type === "action") {
1733
- let url = new URL(request.url);
1734
- let pathname = url.pathname + url.search;
1735
- throw getInternalRouterError(405, {
1736
- method: request.method,
1737
- pathname,
1738
- routeId: match.route.id
1739
- });
1740
- } else {
1741
- return { type: "data" /* data */, result: void 0 };
1742
- }
1743
- }
1744
- } else if (!handler) {
1745
- let url = new URL(request.url);
1746
- let pathname = url.pathname + url.search;
1747
- throw getInternalRouterError(404, {
1748
- pathname
1749
- });
1750
- } else {
1751
- result = await runHandler(handler);
1752
- }
1753
- } catch (e) {
1754
- return { type: "error" /* error */, result: e };
1755
- } finally {
1756
- if (onReject) {
1757
- request.signal.removeEventListener("abort", onReject);
1758
- }
1759
- }
1760
- return result;
1761
- }
1762
- async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1763
- let { result, type } = dataStrategyResult;
1764
- if (isResponse(result)) {
1765
- let data2;
1766
- try {
1767
- let contentType = result.headers.get("Content-Type");
1768
- if (contentType && /\bapplication\/json\b/.test(contentType)) {
1769
- if (result.body == null) {
1770
- data2 = null;
1771
- } else {
1772
- data2 = await result.json();
1773
- }
1774
- } else {
1775
- data2 = await result.text();
1776
- }
1777
- } catch (e) {
1778
- return { type: "error" /* error */, error: e };
1779
- }
1780
- if (type === "error" /* error */) {
1781
- return {
1782
- type: "error" /* error */,
1783
- error: new ErrorResponseImpl(result.status, result.statusText, data2),
1784
- statusCode: result.status,
1785
- headers: result.headers
1786
- };
1787
- }
1788
- return {
1789
- type: "data" /* data */,
1790
- data: data2,
1791
- statusCode: result.status,
1792
- headers: result.headers
1793
- };
1794
- }
1795
- if (type === "error" /* error */) {
1796
- if (isDataWithResponseInit(result)) {
1797
- if (result.data instanceof Error) {
1798
- return {
1799
- type: "error" /* error */,
1800
- error: result.data,
1801
- statusCode: result.init?.status,
1802
- headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1803
- };
1804
- }
1805
- return {
1806
- type: "error" /* error */,
1807
- error: new ErrorResponseImpl(
1808
- result.init?.status || 500,
1809
- void 0,
1810
- result.data
1811
- ),
1812
- statusCode: isRouteErrorResponse(result) ? result.status : void 0,
1813
- headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1814
- };
1815
- }
1816
- return {
1817
- type: "error" /* error */,
1818
- error: result,
1819
- statusCode: isRouteErrorResponse(result) ? result.status : void 0
1820
- };
1821
- }
1822
- if (isDataWithResponseInit(result)) {
1823
- return {
1824
- type: "data" /* data */,
1825
- data: result.data,
1826
- statusCode: result.init?.status,
1827
- headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1828
- };
1829
- }
1830
- return { type: "data" /* data */, data: result };
1831
- }
1832
- function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
1833
- let location = response.headers.get("Location");
1834
- invariant(
1835
- location,
1836
- "Redirects returned/thrown from loaders/actions must have a Location header"
1837
- );
1838
- if (!ABSOLUTE_URL_REGEX.test(location)) {
1839
- let trimmedMatches = matches.slice(
1840
- 0,
1841
- matches.findIndex((m) => m.route.id === routeId) + 1
1842
- );
1843
- location = normalizeTo(
1844
- new URL(request.url),
1845
- trimmedMatches,
1846
- basename,
1847
- location
1848
- );
1849
- response.headers.set("Location", location);
1850
- }
1851
- return response;
1852
- }
1853
- function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
1854
- let loaderData = {};
1855
- let errors = null;
1856
- let statusCode;
1857
- let foundError = false;
1858
- let loaderHeaders = {};
1859
- let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
1860
- matches.forEach((match) => {
1861
- if (!(match.route.id in results)) {
1862
- return;
1863
- }
1864
- let id = match.route.id;
1865
- let result = results[id];
1866
- invariant(
1867
- !isRedirectResult(result),
1868
- "Cannot handle redirect results in processLoaderData"
1869
- );
1870
- if (isErrorResult(result)) {
1871
- let error = result.error;
1872
- if (pendingError !== void 0) {
1873
- error = pendingError;
1874
- pendingError = void 0;
1875
- }
1876
- errors = errors || {};
1877
- if (skipLoaderErrorBubbling) {
1878
- errors[id] = error;
1879
- } else {
1880
- let boundaryMatch = findNearestBoundary(matches, id);
1881
- if (errors[boundaryMatch.route.id] == null) {
1882
- errors[boundaryMatch.route.id] = error;
1883
- }
1884
- }
1885
- if (!isStaticHandler) {
1886
- loaderData[id] = ResetLoaderDataSymbol;
1887
- }
1888
- if (!foundError) {
1889
- foundError = true;
1890
- statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
1891
- }
1892
- if (result.headers) {
1893
- loaderHeaders[id] = result.headers;
1894
- }
1895
- } else {
1896
- loaderData[id] = result.data;
1897
- if (result.statusCode && result.statusCode !== 200 && !foundError) {
1898
- statusCode = result.statusCode;
1899
- }
1900
- if (result.headers) {
1901
- loaderHeaders[id] = result.headers;
1902
- }
1903
- }
1904
- });
1905
- if (pendingError !== void 0 && pendingActionResult) {
1906
- errors = { [pendingActionResult[0]]: pendingError };
1907
- loaderData[pendingActionResult[0]] = void 0;
1908
- }
1909
- return {
1910
- loaderData,
1911
- errors,
1912
- statusCode: statusCode || 200,
1913
- loaderHeaders
1914
- };
1915
- }
1916
- function findNearestBoundary(matches, routeId) {
1917
- let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
1918
- return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
1919
- }
1920
- function getShortCircuitMatches(routes) {
1921
- let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
1922
- id: `__shim-error-route__`
1923
- };
1924
- return {
1925
- matches: [
1926
- {
1927
- params: {},
1928
- pathname: "",
1929
- pathnameBase: "",
1930
- route
1931
- }
1932
- ],
1933
- route
1934
- };
1935
- }
1936
- function getInternalRouterError(status, {
1937
- pathname,
1938
- routeId,
1939
- method,
1940
- type,
1941
- message
1942
- } = {}) {
1943
- let statusText = "Unknown Server Error";
1944
- let errorMessage = "Unknown @remix-run/router error";
1945
- if (status === 400) {
1946
- statusText = "Bad Request";
1947
- if (method && pathname && routeId) {
1948
- 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.`;
1949
- } else if (type === "invalid-body") {
1950
- errorMessage = "Unable to encode submission body";
1951
- }
1952
- } else if (status === 403) {
1953
- statusText = "Forbidden";
1954
- errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
1955
- } else if (status === 404) {
1956
- statusText = "Not Found";
1957
- errorMessage = `No route matches URL "${pathname}"`;
1958
- } else if (status === 405) {
1959
- statusText = "Method Not Allowed";
1960
- if (method && pathname && routeId) {
1961
- 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.`;
1962
- } else if (method) {
1963
- errorMessage = `Invalid request method "${method.toUpperCase()}"`;
1964
- }
1965
- }
1966
- return new ErrorResponseImpl(
1967
- status || 500,
1968
- statusText,
1969
- new Error(errorMessage),
1970
- true
1971
- );
1972
- }
1973
- function isDataStrategyResult(result) {
1974
- return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
1975
- }
1976
- function isRedirectDataStrategyResult(result) {
1977
- return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
1978
- }
1979
- function isErrorResult(result) {
1980
- return result.type === "error" /* error */;
1981
- }
1982
- function isRedirectResult(result) {
1983
- return (result && result.type) === "redirect" /* redirect */;
1984
- }
1985
- function isDataWithResponseInit(value) {
1986
- return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
1987
- }
1988
- function isResponse(value) {
1989
- return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
1990
- }
1991
- function isRedirectStatusCode(statusCode) {
1992
- return redirectStatusCodes.has(statusCode);
1993
- }
1994
- function isRedirectResponse(result) {
1995
- return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
1996
- }
1997
- function isValidMethod(method) {
1998
- return validRequestMethods.has(method.toUpperCase());
1999
- }
2000
- function isMutationMethod(method) {
2001
- return validMutationMethods.has(method.toUpperCase());
2002
- }
2003
- function hasNakedIndexQuery(search) {
2004
- return new URLSearchParams(search).getAll("index").some((v) => v === "");
2005
- }
2006
- function getTargetMatch(matches, location) {
2007
- let search = typeof location === "string" ? parsePath(location).search : location.search;
2008
- if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
2009
- return matches[matches.length - 1];
2010
- }
2011
- let pathMatches = getPathContributingMatches(matches);
2012
- return pathMatches[pathMatches.length - 1];
2013
- }
2014
- function getDocumentHeaders(context, getRouteHeadersFn) {
2015
- let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
2016
- let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
2017
- let errorHeaders;
2018
- if (boundaryIdx >= 0) {
2019
- let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
2020
- context.matches.slice(boundaryIdx).some((match) => {
2021
- let id = match.route.id;
2022
- if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) {
2023
- errorHeaders = actionHeaders[id];
2024
- } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {
2025
- errorHeaders = loaderHeaders[id];
2026
- }
2027
- return errorHeaders != null;
2028
- });
2029
- }
2030
- return matches.reduce((parentHeaders, match, idx) => {
2031
- let { id } = match.route;
2032
- let loaderHeaders = context.loaderHeaders[id] || new Headers();
2033
- let actionHeaders = context.actionHeaders[id] || new Headers();
2034
- let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
2035
- let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
2036
- let headersFn = getRouteHeadersFn(match);
2037
- if (headersFn == null) {
2038
- let headers2 = new Headers(parentHeaders);
2039
- if (includeErrorCookies) {
2040
- prependCookies(errorHeaders, headers2);
2041
- }
2042
- prependCookies(actionHeaders, headers2);
2043
- prependCookies(loaderHeaders, headers2);
2044
- return headers2;
2045
- }
2046
- let headers = new Headers(
2047
- typeof headersFn === "function" ? headersFn({
2048
- loaderHeaders,
2049
- parentHeaders,
2050
- actionHeaders,
2051
- errorHeaders: includeErrorHeaders ? errorHeaders : void 0
2052
- }) : headersFn
2053
- );
2054
- if (includeErrorCookies) {
2055
- prependCookies(errorHeaders, headers);
2056
- }
2057
- prependCookies(actionHeaders, headers);
2058
- prependCookies(loaderHeaders, headers);
2059
- prependCookies(parentHeaders, headers);
2060
- return headers;
2061
- }, new Headers());
2062
- }
2063
- function prependCookies(parentHeaders, childHeaders) {
2064
- let parentSetCookieString = parentHeaders.get("Set-Cookie");
2065
- if (parentSetCookieString) {
2066
- let cookies = setCookieParser.splitCookiesString(parentSetCookieString);
2067
- let childCookies = new Set(childHeaders.getSetCookie());
2068
- cookies.forEach((cookie) => {
2069
- if (!childCookies.has(cookie)) {
2070
- childHeaders.append("Set-Cookie", cookie);
2071
- }
2072
- });
2073
- }
2074
- }
2075
- async function matchRSCServerRequest({
2076
- decodeCallServer,
2077
- decodeFormAction,
2078
- onError,
2079
- request,
2080
- routes
2081
- }) {
2082
- const url = new URL(request.url);
2083
- let isDataRequest = request.headers.has("X-React-Router-Data-Request");
2084
- if (isManifestRequest(url)) {
2085
- const matches = matchRoutes(
2086
- routes,
2087
- url.pathname.replace(/\.manifest$/, "")
2088
- );
2089
- return {
2090
- statusCode: 200,
2091
- headers: new Headers({
2092
- "Content-Type": "text/x-component",
2093
- Vary: "Content-Type"
2094
- }),
2095
- payload: {
2096
- type: "manifest",
2097
- matches: await Promise.all(
2098
- matches?.map((m, i) => getRoute(m.route, matches[i - 1]?.route.id)) ?? []
2099
- ),
2100
- patches: await getAdditionalRoutePatches(
2101
- url.pathname,
2102
- routes,
2103
- matches?.map((m) => m.route.id) ?? []
2104
- )
2105
- }
2106
- };
2107
- }
2108
- let statusCode = 200;
2109
- let actionResult;
2110
- const actionId = request.headers.get("rsc-action-id");
2111
- if (actionId) {
2112
- if (!decodeCallServer) {
2113
- throw new Error(
2114
- "Cannot handle enhanced server action without a decodeCallServer function"
2115
- );
2116
- }
2117
- const reply = canDecodeWithFormData(request.headers.get("Content-Type")) ? await request.formData() : await request.text();
2118
- const serverAction = await decodeCallServer(actionId, reply);
2119
- actionResult = Promise.resolve(serverAction());
2120
- try {
2121
- await actionResult;
2122
- } catch (error) {
2123
- onError?.(error);
2124
- }
2125
- request = new Request(request.url, {
2126
- method: "GET",
2127
- headers: request.headers,
2128
- signal: request.signal
2129
- });
2130
- }
2131
- if (request.method === "POST") {
2132
- const formData = await request.formData();
2133
- if (Array.from(formData.keys()).some((key) => key.startsWith("$ACTION_ID_"))) {
2134
- if (!decodeFormAction) {
2135
- throw new Error(
2136
- "Cannot handle form actions without a decodeFormAction function"
2137
- );
2138
- }
2139
- const action = await decodeFormAction(formData);
2140
- try {
2141
- await action();
2142
- } catch (error) {
2143
- onError?.(error);
2144
- }
2145
- request = new Request(request.url, {
2146
- method: "GET",
2147
- headers: request.headers,
2148
- signal: request.signal
2149
- });
2150
- }
2151
- }
2152
- const getRenderPayload = async (isDataRequest2) => {
2153
- const handler = createStaticHandler(routes);
2154
- let isSubmission = isMutationMethod(request.method);
2155
- let searchParams = new URL(request.url).searchParams;
2156
- let routeIdsToLoad = !isSubmission && searchParams.has("_routes") ? searchParams.get("_routes").split(",") : null;
2157
- const staticContext = await handler.query(request, {
2158
- skipLoaderErrorBubbling: true,
2159
- skipRevalidation: isSubmission,
2160
- ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : null
2161
- });
2162
- if (staticContext instanceof Response) {
2163
- return {
2164
- payload: {
2165
- type: "redirect",
2166
- location: staticContext.headers.get("Location") || "",
2167
- reload: staticContext.headers.get("x-remix-reload-document") === "true",
2168
- replace: staticContext.headers.get("x-remix-replace") === "true",
2169
- status: staticContext.status
2170
- }
2171
- };
2172
- }
2173
- statusCode = staticContext.statusCode ?? statusCode;
2174
- const errors = staticContext.errors ? Object.fromEntries(
2175
- Object.entries(staticContext.errors).map(([key, error]) => [
2176
- key,
2177
- isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error
2178
- ])
2179
- ) : staticContext.errors;
2180
- staticContext.matches.forEach((m) => {
2181
- if (staticContext.loaderData[m.route.id] === void 0) {
2182
- staticContext.loaderData[m.route.id] = null;
2183
- }
2184
- });
2185
- let headers = getDocumentHeaders(
2186
- staticContext,
2187
- (match) => match.route.headers
2188
- );
2189
- const payload = {
2190
- type: "render",
2191
- actionData: staticContext.actionData,
2192
- errors,
2193
- loaderData: staticContext.loaderData,
2194
- location: staticContext.location
2195
- };
2196
- if (isSubmission) {
2197
- return {
2198
- headers,
2199
- payload: {
2200
- ...payload,
2201
- matches: [],
2202
- patches: []
2203
- }
2204
- };
2205
- }
2206
- let lastMatch = null;
2207
- let matches = await Promise.all(
2208
- staticContext.matches.map(async (match) => {
2209
- if ("lazy" in match.route && match.route.lazy) {
2210
- Object.assign(match.route, {
2211
- // @ts-expect-error - FIXME: Fix the types here
2212
- ...await match.route.lazy(),
2213
- path: match.route.path,
2214
- index: match.route.index,
2215
- id: match.route.id
2216
- });
2217
- match.route.lazy = void 0;
2218
- }
2219
- const Layout = match.route.Layout || React__namespace.Fragment;
2220
- const Component = match.route.default;
2221
- const ErrorBoundary = match.route.ErrorBoundary;
2222
- const HydrateFallback = match.route.HydrateFallback;
2223
- const loaderData = staticContext.loaderData[match.route.id];
2224
- const actionData = staticContext.actionData?.[match.route.id];
2225
- const params = match.params;
2226
- const element = Component ? staticContext.errors?.[match.route.id] ? false : React__namespace.createElement(
2227
- Layout,
2228
- null,
2229
- Component.$$typeof === Symbol.for("react.client.reference") ? React__namespace.createElement(
2230
- reactRouter.UNSAFE_WithRouteComponentProps,
2231
- null,
2232
- React__namespace.createElement(Component)
2233
- ) : React__namespace.createElement(Component, {
2234
- loaderData,
2235
- actionData,
2236
- params,
2237
- matches: staticContext.matches.map(
2238
- (match2) => convertRouteMatchToUiMatch(
2239
- match2,
2240
- staticContext.loaderData
2241
- )
2242
- )
2243
- })
2244
- ) : void 0;
2245
- const errorElement = ErrorBoundary ? React__namespace.createElement(
2246
- Layout,
2247
- null,
2248
- Component.$$typeof === Symbol.for("react.client.reference") ? React__namespace.createElement(
2249
- reactRouter.UNSAFE_WithErrorBoundaryProps,
2250
- null,
2251
- React__namespace.createElement(ErrorBoundary)
2252
- ) : React__namespace.createElement(ErrorBoundary, {
2253
- loaderData,
2254
- actionData,
2255
- params,
2256
- error: [...staticContext.matches].reverse().find((match2) => staticContext.errors?.[match2.route.id])
2257
- })
2258
- ) : void 0;
2259
- const hydrateFallbackElement = HydrateFallback ? React__namespace.createElement(
2260
- Layout,
2261
- null,
2262
- Component.$$typeof === Symbol.for("react.client.reference") ? React__namespace.createElement(
2263
- reactRouter.UNSAFE_WithHydrateFallbackProps,
2264
- null,
2265
- React__namespace.createElement(HydrateFallback)
2266
- ) : React__namespace.createElement(HydrateFallback, {
2267
- loaderData,
2268
- actionData,
2269
- params
2270
- })
2271
- ) : match.route.id === "root" ? (
2272
- // FIXME: This should use the `RemixRootDefaultErrorBoundary` but that
2273
- // currently uses a hook internally so it fails during RSC. Restructure
2274
- // so it can be used safely in an RSC render pass.
2275
- React__namespace.createElement("p", null, "Loading!")
2276
- ) : void 0;
2277
- let result = {
2278
- clientAction: match.route.clientAction,
2279
- clientLoader: match.route.clientLoader,
2280
- element,
2281
- errorElement,
2282
- handle: match.route.handle,
2283
- hasAction: !!match.route.action,
2284
- hasErrorBoundary: !!match.route.ErrorBoundary,
2285
- hasLoader: !!match.route.loader,
2286
- hydrateFallbackElement,
2287
- id: match.route.id,
2288
- index: match.route.index,
2289
- links: match.route.links,
2290
- meta: match.route.meta,
2291
- params,
2292
- parentId: lastMatch?.route.id,
2293
- path: match.route.path,
2294
- pathname: match.pathname,
2295
- pathnameBase: match.pathnameBase,
2296
- shouldRevalidate: match.route.shouldRevalidate
2297
- };
2298
- lastMatch = match;
2299
- return result;
2300
- })
2301
- );
2302
- return {
2303
- headers,
2304
- payload: {
2305
- ...payload,
2306
- matches: routeIdsToLoad ? matches.filter((m) => routeIdsToLoad.includes(m.id)) : matches,
2307
- patches: !isDataRequest2 ? await getAdditionalRoutePatches(
2308
- staticContext.location.pathname,
2309
- routes,
2310
- matches.map((m) => m.id)
2311
- ) : void 0
2312
- }
2313
- };
2314
- };
2315
- try {
2316
- if (actionResult !== void 0) {
2317
- return {
2318
- statusCode,
2319
- headers: new Headers({
2320
- "Content-Type": "text/x-component",
2321
- Vary: "Content-Type"
2322
- }),
2323
- payload: {
2324
- type: "action",
2325
- actionResult,
2326
- rerender: getRenderPayload(isDataRequest).then((r) => r.payload)
2327
- }
2328
- };
2329
- } else {
2330
- let { headers, payload } = await getRenderPayload(isDataRequest);
2331
- headers || (headers = new Headers());
2332
- headers.set("Content-Type", "text/x-component");
2333
- headers.set("Vary", "Content-Type");
2334
- return {
2335
- statusCode,
2336
- headers,
2337
- payload
2338
- };
2339
- }
2340
- } catch (error) {
2341
- throw error;
2342
- }
2343
- }
2344
- async function getRoute(route, parentId) {
2345
- if ("lazy" in route && route.lazy) {
2346
- Object.assign(route, {
2347
- ...await route.lazy(),
2348
- path: route.path,
2349
- index: route.index,
2350
- id: route.id
2351
- });
2352
- route.lazy = void 0;
2353
- }
2354
- const Layout = route.Layout || React__namespace.Fragment;
2355
- const errorElement = route.ErrorBoundary ? React__namespace.createElement(
2356
- Layout,
2357
- null,
2358
- React__namespace.createElement(route.ErrorBoundary)
2359
- ) : void 0;
2360
- return {
2361
- clientAction: route.clientAction,
2362
- clientLoader: route.clientLoader,
2363
- handle: route.handle,
2364
- hasAction: !!route.action,
2365
- hasErrorBoundary: !!route.ErrorBoundary,
2366
- errorElement,
2367
- hasLoader: !!route.loader,
2368
- id: route.id,
2369
- parentId,
2370
- path: route.path,
2371
- index: "index" in route ? route.index : void 0,
2372
- links: route.links,
2373
- meta: route.meta
2374
- };
2375
- }
2376
- async function getAdditionalRoutePatches(pathname, routes, matchedRouteIds) {
2377
- let patchRouteMatches = /* @__PURE__ */ new Map();
2378
- let segments = pathname.split("/").filter(Boolean);
2379
- let paths = ["/"];
2380
- segments.pop();
2381
- while (segments.length > 0) {
2382
- paths.push(`/${segments.join("/")}`);
2383
- segments.pop();
2384
- }
2385
- paths.forEach((path) => {
2386
- let matches = matchRoutes(routes, path) || [];
2387
- matches.forEach(
2388
- (m, i) => patchRouteMatches.set(m.route.id, {
2389
- ...m.route,
2390
- parentId: matches[i - 1]?.route.id
2391
- })
2392
- );
2393
- });
2394
- let patches = await Promise.all(
2395
- [...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getRoute(route, route.parentId))
2396
- );
2397
- return patches;
2398
- }
2399
- function isManifestRequest(url) {
2400
- return url.pathname.endsWith(".manifest");
2401
- }
2402
- function canDecodeWithFormData(contentType) {
2403
- if (!contentType) return false;
2404
- return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
2405
- }
2406
-
2407
- exports.createStaticHandler = createStaticHandler;
2408
- exports.data = data;
2409
- exports.matchRSCServerRequest = matchRSCServerRequest;
2410
- exports.matchRoutes = matchRoutes;
2411
- exports.redirect = redirect;
2412
- exports.redirectDocument = redirectDocument;
2413
- exports.replace = replace;