react-router 0.0.0-experimental-b588f7e → 0.0.0-experimental-23decd7bc

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 (64) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/development/browser-CmIT056Z.d.mts +154 -0
  3. package/dist/development/chunk-3E3CD4NY.mjs +2669 -0
  4. package/dist/development/{chunk-3HOZPCHX.mjs → chunk-GJVCYY62.mjs} +1445 -3021
  5. package/dist/development/chunk-H2M6MMUH.js +10007 -0
  6. package/dist/development/chunk-I3MHZ4NU.js +21 -0
  7. package/dist/development/components-CwtESh53.d.mts +816 -0
  8. package/dist/development/dom-export.d.mts +4 -2
  9. package/dist/development/dom-export.js +53 -72
  10. package/dist/development/dom-export.mjs +7 -4
  11. package/dist/development/index-react-server-client-CzKQ01cq.d.mts +1360 -0
  12. package/dist/development/{lib-oW7CoPA6.d.mts → index-react-server-client-unV28389.d.ts} +39 -39
  13. package/dist/development/index-react-server-client.d.mts +4 -0
  14. package/dist/development/index-react-server-client.d.ts +3 -0
  15. package/dist/development/index-react-server-client.js +54 -0
  16. package/dist/development/index-react-server-client.mjs +53 -0
  17. package/dist/development/index-react-server.d.mts +1861 -0
  18. package/dist/development/index-react-server.d.ts +1861 -0
  19. package/dist/development/index-react-server.js +3137 -0
  20. package/dist/development/index-react-server.mjs +3025 -0
  21. package/dist/development/index.d.mts +32 -46
  22. package/dist/development/index.d.ts +191 -2223
  23. package/dist/development/index.js +2577 -11464
  24. package/dist/development/index.mjs +33 -22
  25. package/dist/development/lib/types/internal.d.mts +8 -72
  26. package/dist/development/lib/types/internal.d.ts +8 -71
  27. package/dist/development/lib/types/internal.js +2 -20
  28. package/dist/development/lib/types/internal.mjs +1 -1
  29. package/dist/{production/register-DeIo2iHO.d.mts → development/register-DiOIlEq5.d.mts} +1 -1
  30. package/dist/development/{register-DeIo2iHO.d.mts → register-DiOIlEq5.d.ts} +1 -1
  31. package/dist/development/{route-data-ByAYLHuM.d.mts → route-data-Csr8hE3v.d.mts} +80 -3
  32. package/dist/{production/register-DCE0tH5m.d.ts → development/route-data-x_b_BLCv.d.ts} +90 -36
  33. package/dist/production/browser-CmIT056Z.d.mts +154 -0
  34. package/dist/production/chunk-7TUGB72O.js +10007 -0
  35. package/dist/production/chunk-I3MHZ4NU.js +21 -0
  36. package/dist/production/chunk-XNTCWHOK.mjs +2669 -0
  37. package/dist/production/{chunk-UROK22QK.mjs → chunk-YWCG2M57.mjs} +1445 -3021
  38. package/dist/production/components-CwtESh53.d.mts +816 -0
  39. package/dist/production/dom-export.d.mts +4 -2
  40. package/dist/production/dom-export.js +53 -72
  41. package/dist/production/dom-export.mjs +7 -4
  42. package/dist/production/index-react-server-client-CzKQ01cq.d.mts +1360 -0
  43. package/dist/production/{lib-oW7CoPA6.d.mts → index-react-server-client-unV28389.d.ts} +39 -39
  44. package/dist/production/index-react-server-client.d.mts +4 -0
  45. package/dist/production/index-react-server-client.d.ts +3 -0
  46. package/dist/production/index-react-server-client.js +54 -0
  47. package/dist/production/index-react-server-client.mjs +53 -0
  48. package/dist/production/index-react-server.d.mts +1861 -0
  49. package/dist/production/index-react-server.d.ts +1861 -0
  50. package/dist/production/index-react-server.js +3137 -0
  51. package/dist/production/index-react-server.mjs +3025 -0
  52. package/dist/production/index.d.mts +32 -46
  53. package/dist/production/index.d.ts +191 -2223
  54. package/dist/production/index.js +2577 -11464
  55. package/dist/production/index.mjs +33 -22
  56. package/dist/production/lib/types/internal.d.mts +8 -72
  57. package/dist/production/lib/types/internal.d.ts +8 -71
  58. package/dist/production/lib/types/internal.js +2 -20
  59. package/dist/production/lib/types/internal.mjs +1 -1
  60. package/dist/production/register-DiOIlEq5.d.mts +24 -0
  61. package/dist/production/register-DiOIlEq5.d.ts +24 -0
  62. package/dist/{development/register-DCE0tH5m.d.ts → production/route-data-Csr8hE3v.d.mts} +80 -26
  63. package/dist/production/{route-data-ByAYLHuM.d.mts → route-data-x_b_BLCv.d.ts} +90 -13
  64. package/package.json +49 -10
@@ -0,0 +1,3137 @@
1
+ 'use strict';
2
+
3
+ var node_async_hooks = require('node:async_hooks');
4
+ var React2 = require('react');
5
+ var setCookieParser = require('set-cookie-parser');
6
+ var reactServerClient = require('react-router/internal/react-server-client');
7
+ var cookie = require('cookie');
8
+
9
+ function _interopNamespace(e) {
10
+ if (e && e.__esModule) return e;
11
+ var n = Object.create(null);
12
+ if (e) {
13
+ Object.keys(e).forEach(function (k) {
14
+ if (k !== 'default') {
15
+ var d = Object.getOwnPropertyDescriptor(e, k);
16
+ Object.defineProperty(n, k, d.get ? d : {
17
+ enumerable: true,
18
+ get: function () { return e[k]; }
19
+ });
20
+ }
21
+ });
22
+ }
23
+ n.default = e;
24
+ return Object.freeze(n);
25
+ }
26
+
27
+ var React2__namespace = /*#__PURE__*/_interopNamespace(React2);
28
+
29
+ /**
30
+ * react-router v0.0.0-experimental-23decd7bc
31
+ *
32
+ * Copyright (c) Remix Software Inc.
33
+ *
34
+ * This source code is licensed under the MIT license found in the
35
+ * LICENSE.md file in the root directory of this source tree.
36
+ *
37
+ * @license MIT
38
+ */
39
+ var __typeError = (msg) => {
40
+ throw TypeError(msg);
41
+ };
42
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
43
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
44
+ 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);
45
+
46
+ // lib/router/history.ts
47
+ function invariant(value, message) {
48
+ if (value === false || value === null || typeof value === "undefined") {
49
+ throw new Error(message);
50
+ }
51
+ }
52
+ function warning(cond, message) {
53
+ if (!cond) {
54
+ if (typeof console !== "undefined") console.warn(message);
55
+ try {
56
+ throw new Error(message);
57
+ } catch (e) {
58
+ }
59
+ }
60
+ }
61
+ function createKey() {
62
+ return Math.random().toString(36).substring(2, 10);
63
+ }
64
+ function createLocation(current, to, state = null, key) {
65
+ let location = {
66
+ pathname: "string" === "string" ? current : current.pathname,
67
+ search: "",
68
+ hash: "",
69
+ ...typeof to === "string" ? parsePath(to) : to,
70
+ state,
71
+ // TODO: This could be cleaned up. push/replace should probably just take
72
+ // full Locations now and avoid the need to run through this flow at all
73
+ // But that's a pretty big refactor to the current test suite so going to
74
+ // keep as is for the time being and just let any incoming keys take precedence
75
+ key: to && to.key || key || createKey()
76
+ };
77
+ return location;
78
+ }
79
+ function createPath({
80
+ pathname = "/",
81
+ search = "",
82
+ hash = ""
83
+ }) {
84
+ if (search && search !== "?")
85
+ pathname += search.charAt(0) === "?" ? search : "?" + search;
86
+ if (hash && hash !== "#")
87
+ pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
88
+ return pathname;
89
+ }
90
+ function parsePath(path) {
91
+ let parsedPath = {};
92
+ if (path) {
93
+ let hashIndex = path.indexOf("#");
94
+ if (hashIndex >= 0) {
95
+ parsedPath.hash = path.substring(hashIndex);
96
+ path = path.substring(0, hashIndex);
97
+ }
98
+ let searchIndex = path.indexOf("?");
99
+ if (searchIndex >= 0) {
100
+ parsedPath.search = path.substring(searchIndex);
101
+ path = path.substring(0, searchIndex);
102
+ }
103
+ if (path) {
104
+ parsedPath.pathname = path;
105
+ }
106
+ }
107
+ return parsedPath;
108
+ }
109
+
110
+ // lib/router/utils.ts
111
+ function unstable_createContext(defaultValue) {
112
+ return { defaultValue };
113
+ }
114
+ var _map;
115
+ var unstable_RouterContextProvider = class {
116
+ constructor(init) {
117
+ __privateAdd(this, _map, /* @__PURE__ */ new Map());
118
+ if (init) {
119
+ for (let [context, value] of init) {
120
+ this.set(context, value);
121
+ }
122
+ }
123
+ }
124
+ get(context) {
125
+ if (__privateGet(this, _map).has(context)) {
126
+ return __privateGet(this, _map).get(context);
127
+ }
128
+ if (context.defaultValue !== void 0) {
129
+ return context.defaultValue;
130
+ }
131
+ throw new Error("No value found for context");
132
+ }
133
+ set(context, value) {
134
+ __privateGet(this, _map).set(context, value);
135
+ }
136
+ };
137
+ _map = new WeakMap();
138
+ var unsupportedLazyRouteObjectKeys = /* @__PURE__ */ new Set([
139
+ "lazy",
140
+ "caseSensitive",
141
+ "path",
142
+ "id",
143
+ "index",
144
+ "children"
145
+ ]);
146
+ function isUnsupportedLazyRouteObjectKey(key) {
147
+ return unsupportedLazyRouteObjectKeys.has(
148
+ key
149
+ );
150
+ }
151
+ var unsupportedLazyRouteFunctionKeys = /* @__PURE__ */ new Set([
152
+ "lazy",
153
+ "caseSensitive",
154
+ "path",
155
+ "id",
156
+ "index",
157
+ "unstable_middleware",
158
+ "children"
159
+ ]);
160
+ function isUnsupportedLazyRouteFunctionKey(key) {
161
+ return unsupportedLazyRouteFunctionKeys.has(
162
+ key
163
+ );
164
+ }
165
+ function isIndexRoute(route) {
166
+ return route.index === true;
167
+ }
168
+ function convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath = [], manifest = {}, allowInPlaceMutations = false) {
169
+ return routes.map((route, index) => {
170
+ let treePath = [...parentPath, String(index)];
171
+ let id = typeof route.id === "string" ? route.id : treePath.join("-");
172
+ invariant(
173
+ route.index !== true || !route.children,
174
+ `Cannot specify children on an index route`
175
+ );
176
+ invariant(
177
+ allowInPlaceMutations || !manifest[id],
178
+ `Found a route id collision on id "${id}". Route id's must be globally unique within Data Router usages`
179
+ );
180
+ if (isIndexRoute(route)) {
181
+ let indexRoute = {
182
+ ...route,
183
+ ...mapRouteProperties(route),
184
+ id
185
+ };
186
+ manifest[id] = indexRoute;
187
+ return indexRoute;
188
+ } else {
189
+ let pathOrLayoutRoute = {
190
+ ...route,
191
+ ...mapRouteProperties(route),
192
+ id,
193
+ children: void 0
194
+ };
195
+ manifest[id] = pathOrLayoutRoute;
196
+ if (route.children) {
197
+ pathOrLayoutRoute.children = convertRoutesToDataRoutes(
198
+ route.children,
199
+ mapRouteProperties,
200
+ treePath,
201
+ manifest,
202
+ allowInPlaceMutations
203
+ );
204
+ }
205
+ return pathOrLayoutRoute;
206
+ }
207
+ });
208
+ }
209
+ function matchRoutes(routes, locationArg, basename = "/") {
210
+ return matchRoutesImpl(routes, locationArg, basename, false);
211
+ }
212
+ function matchRoutesImpl(routes, locationArg, basename, allowPartial) {
213
+ let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
214
+ let pathname = stripBasename(location.pathname || "/", basename);
215
+ if (pathname == null) {
216
+ return null;
217
+ }
218
+ let branches = flattenRoutes(routes);
219
+ rankRouteBranches(branches);
220
+ let matches = null;
221
+ for (let i = 0; matches == null && i < branches.length; ++i) {
222
+ let decoded = decodePath(pathname);
223
+ matches = matchRouteBranch(
224
+ branches[i],
225
+ decoded,
226
+ allowPartial
227
+ );
228
+ }
229
+ return matches;
230
+ }
231
+ function convertRouteMatchToUiMatch(match, loaderData) {
232
+ let { route, pathname, params } = match;
233
+ return {
234
+ id: route.id,
235
+ pathname,
236
+ params,
237
+ data: loaderData[route.id],
238
+ handle: route.handle
239
+ };
240
+ }
241
+ function flattenRoutes(routes, branches = [], parentsMeta = [], parentPath = "") {
242
+ let flattenRoute = (route, index, relativePath) => {
243
+ let meta = {
244
+ relativePath: relativePath === void 0 ? route.path || "" : relativePath,
245
+ caseSensitive: route.caseSensitive === true,
246
+ childrenIndex: index,
247
+ route
248
+ };
249
+ if (meta.relativePath.startsWith("/")) {
250
+ invariant(
251
+ meta.relativePath.startsWith(parentPath),
252
+ `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.`
253
+ );
254
+ meta.relativePath = meta.relativePath.slice(parentPath.length);
255
+ }
256
+ let path = joinPaths([parentPath, meta.relativePath]);
257
+ let routesMeta = parentsMeta.concat(meta);
258
+ if (route.children && route.children.length > 0) {
259
+ invariant(
260
+ // Our types know better, but runtime JS may not!
261
+ // @ts-expect-error
262
+ route.index !== true,
263
+ `Index routes must not have child routes. Please remove all child routes from route path "${path}".`
264
+ );
265
+ flattenRoutes(route.children, branches, routesMeta, path);
266
+ }
267
+ if (route.path == null && !route.index) {
268
+ return;
269
+ }
270
+ branches.push({
271
+ path,
272
+ score: computeScore(path, route.index),
273
+ routesMeta
274
+ });
275
+ };
276
+ routes.forEach((route, index) => {
277
+ if (route.path === "" || !route.path?.includes("?")) {
278
+ flattenRoute(route, index);
279
+ } else {
280
+ for (let exploded of explodeOptionalSegments(route.path)) {
281
+ flattenRoute(route, index, exploded);
282
+ }
283
+ }
284
+ });
285
+ return branches;
286
+ }
287
+ function explodeOptionalSegments(path) {
288
+ let segments = path.split("/");
289
+ if (segments.length === 0) return [];
290
+ let [first, ...rest] = segments;
291
+ let isOptional = first.endsWith("?");
292
+ let required = first.replace(/\?$/, "");
293
+ if (rest.length === 0) {
294
+ return isOptional ? [required, ""] : [required];
295
+ }
296
+ let restExploded = explodeOptionalSegments(rest.join("/"));
297
+ let result = [];
298
+ result.push(
299
+ ...restExploded.map(
300
+ (subpath) => subpath === "" ? required : [required, subpath].join("/")
301
+ )
302
+ );
303
+ if (isOptional) {
304
+ result.push(...restExploded);
305
+ }
306
+ return result.map(
307
+ (exploded) => path.startsWith("/") && exploded === "" ? "/" : exploded
308
+ );
309
+ }
310
+ function rankRouteBranches(branches) {
311
+ branches.sort(
312
+ (a, b) => a.score !== b.score ? b.score - a.score : compareIndexes(
313
+ a.routesMeta.map((meta) => meta.childrenIndex),
314
+ b.routesMeta.map((meta) => meta.childrenIndex)
315
+ )
316
+ );
317
+ }
318
+ var paramRe = /^:[\w-]+$/;
319
+ var dynamicSegmentValue = 3;
320
+ var indexRouteValue = 2;
321
+ var emptySegmentValue = 1;
322
+ var staticSegmentValue = 10;
323
+ var splatPenalty = -2;
324
+ var isSplat = (s) => s === "*";
325
+ function computeScore(path, index) {
326
+ let segments = path.split("/");
327
+ let initialScore = segments.length;
328
+ if (segments.some(isSplat)) {
329
+ initialScore += splatPenalty;
330
+ }
331
+ if (index) {
332
+ initialScore += indexRouteValue;
333
+ }
334
+ return segments.filter((s) => !isSplat(s)).reduce(
335
+ (score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue),
336
+ initialScore
337
+ );
338
+ }
339
+ function compareIndexes(a, b) {
340
+ let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
341
+ return siblings ? (
342
+ // If two routes are siblings, we should try to match the earlier sibling
343
+ // first. This allows people to have fine-grained control over the matching
344
+ // behavior by simply putting routes with identical paths in the order they
345
+ // want them tried.
346
+ a[a.length - 1] - b[b.length - 1]
347
+ ) : (
348
+ // Otherwise, it doesn't really make sense to rank non-siblings by index,
349
+ // so they sort equally.
350
+ 0
351
+ );
352
+ }
353
+ function matchRouteBranch(branch, pathname, allowPartial = false) {
354
+ let { routesMeta } = branch;
355
+ let matchedParams = {};
356
+ let matchedPathname = "/";
357
+ let matches = [];
358
+ for (let i = 0; i < routesMeta.length; ++i) {
359
+ let meta = routesMeta[i];
360
+ let end = i === routesMeta.length - 1;
361
+ let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
362
+ let match = matchPath(
363
+ { path: meta.relativePath, caseSensitive: meta.caseSensitive, end },
364
+ remainingPathname
365
+ );
366
+ let route = meta.route;
367
+ if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {
368
+ match = matchPath(
369
+ {
370
+ path: meta.relativePath,
371
+ caseSensitive: meta.caseSensitive,
372
+ end: false
373
+ },
374
+ remainingPathname
375
+ );
376
+ }
377
+ if (!match) {
378
+ return null;
379
+ }
380
+ Object.assign(matchedParams, match.params);
381
+ matches.push({
382
+ // TODO: Can this as be avoided?
383
+ params: matchedParams,
384
+ pathname: joinPaths([matchedPathname, match.pathname]),
385
+ pathnameBase: normalizePathname(
386
+ joinPaths([matchedPathname, match.pathnameBase])
387
+ ),
388
+ route
389
+ });
390
+ if (match.pathnameBase !== "/") {
391
+ matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
392
+ }
393
+ }
394
+ return matches;
395
+ }
396
+ function matchPath(pattern, pathname) {
397
+ if (typeof pattern === "string") {
398
+ pattern = { path: pattern, caseSensitive: false, end: true };
399
+ }
400
+ let [matcher, compiledParams] = compilePath(
401
+ pattern.path,
402
+ pattern.caseSensitive,
403
+ pattern.end
404
+ );
405
+ let match = pathname.match(matcher);
406
+ if (!match) return null;
407
+ let matchedPathname = match[0];
408
+ let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
409
+ let captureGroups = match.slice(1);
410
+ let params = compiledParams.reduce(
411
+ (memo, { paramName, isOptional }, index) => {
412
+ if (paramName === "*") {
413
+ let splatValue = captureGroups[index] || "";
414
+ pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
415
+ }
416
+ const value = captureGroups[index];
417
+ if (isOptional && !value) {
418
+ memo[paramName] = void 0;
419
+ } else {
420
+ memo[paramName] = (value || "").replace(/%2F/g, "/");
421
+ }
422
+ return memo;
423
+ },
424
+ {}
425
+ );
426
+ return {
427
+ params,
428
+ pathname: matchedPathname,
429
+ pathnameBase,
430
+ pattern
431
+ };
432
+ }
433
+ function compilePath(path, caseSensitive = false, end = true) {
434
+ warning(
435
+ path === "*" || !path.endsWith("*") || path.endsWith("/*"),
436
+ `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(/\*$/, "/*")}".`
437
+ );
438
+ let params = [];
439
+ let regexpSource = "^" + path.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace(
440
+ /\/:([\w-]+)(\?)?/g,
441
+ (_, paramName, isOptional) => {
442
+ params.push({ paramName, isOptional: isOptional != null });
443
+ return isOptional ? "/?([^\\/]+)?" : "/([^\\/]+)";
444
+ }
445
+ );
446
+ if (path.endsWith("*")) {
447
+ params.push({ paramName: "*" });
448
+ regexpSource += path === "*" || path === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$";
449
+ } else if (end) {
450
+ regexpSource += "\\/*$";
451
+ } else if (path !== "" && path !== "/") {
452
+ regexpSource += "(?:(?=\\/|$))";
453
+ } else ;
454
+ let matcher = new RegExp(regexpSource, caseSensitive ? void 0 : "i");
455
+ return [matcher, params];
456
+ }
457
+ function decodePath(value) {
458
+ try {
459
+ return value.split("/").map((v) => decodeURIComponent(v).replace(/\//g, "%2F")).join("/");
460
+ } catch (error) {
461
+ warning(
462
+ false,
463
+ `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}).`
464
+ );
465
+ return value;
466
+ }
467
+ }
468
+ function stripBasename(pathname, basename) {
469
+ if (basename === "/") return pathname;
470
+ if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
471
+ return null;
472
+ }
473
+ let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
474
+ let nextChar = pathname.charAt(startIndex);
475
+ if (nextChar && nextChar !== "/") {
476
+ return null;
477
+ }
478
+ return pathname.slice(startIndex) || "/";
479
+ }
480
+ function resolvePath(to, fromPathname = "/") {
481
+ let {
482
+ pathname: toPathname,
483
+ search = "",
484
+ hash = ""
485
+ } = typeof to === "string" ? parsePath(to) : to;
486
+ let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
487
+ return {
488
+ pathname,
489
+ search: normalizeSearch(search),
490
+ hash: normalizeHash(hash)
491
+ };
492
+ }
493
+ function resolvePathname(relativePath, fromPathname) {
494
+ let segments = fromPathname.replace(/\/+$/, "").split("/");
495
+ let relativeSegments = relativePath.split("/");
496
+ relativeSegments.forEach((segment) => {
497
+ if (segment === "..") {
498
+ if (segments.length > 1) segments.pop();
499
+ } else if (segment !== ".") {
500
+ segments.push(segment);
501
+ }
502
+ });
503
+ return segments.length > 1 ? segments.join("/") : "/";
504
+ }
505
+ function getInvalidPathError(char, field, dest, path) {
506
+ return `Cannot include a '${char}' character in a manually specified \`to.${field}\` field [${JSON.stringify(
507
+ path
508
+ )}]. 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.`;
509
+ }
510
+ function getPathContributingMatches(matches) {
511
+ return matches.filter(
512
+ (match, index) => index === 0 || match.route.path && match.route.path.length > 0
513
+ );
514
+ }
515
+ function getResolveToMatches(matches) {
516
+ let pathMatches = getPathContributingMatches(matches);
517
+ return pathMatches.map(
518
+ (match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase
519
+ );
520
+ }
521
+ function resolveTo(toArg, routePathnames, locationPathname, isPathRelative = false) {
522
+ let to;
523
+ if (typeof toArg === "string") {
524
+ to = parsePath(toArg);
525
+ } else {
526
+ to = { ...toArg };
527
+ invariant(
528
+ !to.pathname || !to.pathname.includes("?"),
529
+ getInvalidPathError("?", "pathname", "search", to)
530
+ );
531
+ invariant(
532
+ !to.pathname || !to.pathname.includes("#"),
533
+ getInvalidPathError("#", "pathname", "hash", to)
534
+ );
535
+ invariant(
536
+ !to.search || !to.search.includes("#"),
537
+ getInvalidPathError("#", "search", "hash", to)
538
+ );
539
+ }
540
+ let isEmptyPath = toArg === "" || to.pathname === "";
541
+ let toPathname = isEmptyPath ? "/" : to.pathname;
542
+ let from;
543
+ if (toPathname == null) {
544
+ from = locationPathname;
545
+ } else {
546
+ let routePathnameIndex = routePathnames.length - 1;
547
+ if (!isPathRelative && toPathname.startsWith("..")) {
548
+ let toSegments = toPathname.split("/");
549
+ while (toSegments[0] === "..") {
550
+ toSegments.shift();
551
+ routePathnameIndex -= 1;
552
+ }
553
+ to.pathname = toSegments.join("/");
554
+ }
555
+ from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
556
+ }
557
+ let path = resolvePath(to, from);
558
+ let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/");
559
+ let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
560
+ if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
561
+ path.pathname += "/";
562
+ }
563
+ return path;
564
+ }
565
+ var joinPaths = (paths) => paths.join("/").replace(/\/\/+/g, "/");
566
+ var normalizePathname = (pathname) => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
567
+ var normalizeSearch = (search) => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
568
+ var normalizeHash = (hash) => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
569
+ var DataWithResponseInit = class {
570
+ constructor(data2, init) {
571
+ this.type = "DataWithResponseInit";
572
+ this.data = data2;
573
+ this.init = init || null;
574
+ }
575
+ };
576
+ function data(data2, init) {
577
+ return new DataWithResponseInit(
578
+ data2,
579
+ typeof init === "number" ? { status: init } : init
580
+ );
581
+ }
582
+ var redirect = (url, init = 302) => {
583
+ let responseInit = init;
584
+ if (typeof responseInit === "number") {
585
+ responseInit = { status: responseInit };
586
+ } else if (typeof responseInit.status === "undefined") {
587
+ responseInit.status = 302;
588
+ }
589
+ let headers = new Headers(responseInit.headers);
590
+ headers.set("Location", url);
591
+ return new Response(null, { ...responseInit, headers });
592
+ };
593
+ var redirectDocument = (url, init) => {
594
+ let response = redirect(url, init);
595
+ response.headers.set("X-Remix-Reload-Document", "true");
596
+ return response;
597
+ };
598
+ var replace = (url, init) => {
599
+ let response = redirect(url, init);
600
+ response.headers.set("X-Remix-Replace", "true");
601
+ return response;
602
+ };
603
+ var ErrorResponseImpl = class {
604
+ constructor(status, statusText, data2, internal = false) {
605
+ this.status = status;
606
+ this.statusText = statusText || "";
607
+ this.internal = internal;
608
+ if (data2 instanceof Error) {
609
+ this.data = data2.toString();
610
+ this.error = data2;
611
+ } else {
612
+ this.data = data2;
613
+ }
614
+ }
615
+ };
616
+ function isRouteErrorResponse(error) {
617
+ return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
618
+ }
619
+
620
+ // lib/router/router.ts
621
+ var validMutationMethodsArr = [
622
+ "POST",
623
+ "PUT",
624
+ "PATCH",
625
+ "DELETE"
626
+ ];
627
+ var validMutationMethods = new Set(
628
+ validMutationMethodsArr
629
+ );
630
+ var validRequestMethodsArr = [
631
+ "GET",
632
+ ...validMutationMethodsArr
633
+ ];
634
+ var validRequestMethods = new Set(validRequestMethodsArr);
635
+ var redirectStatusCodes = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
636
+ var ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
637
+ var defaultMapRouteProperties = (route) => ({
638
+ hasErrorBoundary: Boolean(route.hasErrorBoundary)
639
+ });
640
+ var ResetLoaderDataSymbol = Symbol("ResetLoaderData");
641
+ function createStaticHandler(routes, opts) {
642
+ invariant(
643
+ routes.length > 0,
644
+ "You must provide a non-empty routes array to createStaticHandler"
645
+ );
646
+ let manifest = {};
647
+ let basename = (opts ? opts.basename : null) || "/";
648
+ let mapRouteProperties = opts?.mapRouteProperties || defaultMapRouteProperties;
649
+ let dataRoutes = convertRoutesToDataRoutes(
650
+ routes,
651
+ mapRouteProperties,
652
+ void 0,
653
+ manifest
654
+ );
655
+ async function query(request, {
656
+ requestContext,
657
+ filterMatchesToLoad,
658
+ skipLoaderErrorBubbling,
659
+ skipRevalidation,
660
+ dataStrategy,
661
+ unstable_stream: stream,
662
+ unstable_respond: respond
663
+ } = {}) {
664
+ let url = new URL(request.url);
665
+ let method = request.method;
666
+ let location = createLocation("", createPath(url), null, "default");
667
+ let matches = matchRoutes(dataRoutes, location, basename);
668
+ requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
669
+ let respondOrStreamStaticContext = (ctx) => {
670
+ return stream ? stream(
671
+ requestContext,
672
+ () => Promise.resolve(ctx)
673
+ ) : respond ? respond(ctx) : ctx;
674
+ };
675
+ if (!isValidMethod(method) && method !== "HEAD") {
676
+ let error = getInternalRouterError(405, { method });
677
+ let { matches: methodNotAllowedMatches, route } = getShortCircuitMatches(dataRoutes);
678
+ let staticContext = {
679
+ basename,
680
+ location,
681
+ matches: methodNotAllowedMatches,
682
+ loaderData: {},
683
+ actionData: null,
684
+ errors: {
685
+ [route.id]: error
686
+ },
687
+ statusCode: error.status,
688
+ loaderHeaders: {},
689
+ actionHeaders: {}
690
+ };
691
+ return respondOrStreamStaticContext(staticContext);
692
+ } else if (!matches) {
693
+ let error = getInternalRouterError(404, { pathname: location.pathname });
694
+ let { matches: notFoundMatches, route } = getShortCircuitMatches(dataRoutes);
695
+ let staticContext = {
696
+ basename,
697
+ location,
698
+ matches: notFoundMatches,
699
+ loaderData: {},
700
+ actionData: null,
701
+ errors: {
702
+ [route.id]: error
703
+ },
704
+ statusCode: error.status,
705
+ loaderHeaders: {},
706
+ actionHeaders: {}
707
+ };
708
+ return respondOrStreamStaticContext(staticContext);
709
+ }
710
+ if (stream || respond && matches.some(
711
+ (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
712
+ )) {
713
+ invariant(
714
+ requestContext instanceof unstable_RouterContextProvider,
715
+ "When using middleware in `staticHandler.query()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
716
+ );
717
+ try {
718
+ await loadLazyMiddlewareForMatches(
719
+ matches,
720
+ manifest,
721
+ mapRouteProperties
722
+ );
723
+ let renderedStaticContext;
724
+ let response = await runMiddlewarePipeline(
725
+ {
726
+ request,
727
+ matches,
728
+ params: matches[0].params,
729
+ // If we're calling middleware then it must be enabled so we can cast
730
+ // this to the proper type knowing it's not an `AppLoadContext`
731
+ context: requestContext
732
+ },
733
+ true,
734
+ async () => {
735
+ if (stream) {
736
+ let res2 = await stream(
737
+ requestContext,
738
+ async (revalidationRequest) => {
739
+ let result3 = await queryImpl(
740
+ revalidationRequest,
741
+ location,
742
+ matches,
743
+ requestContext,
744
+ dataStrategy || null,
745
+ skipLoaderErrorBubbling === true,
746
+ null,
747
+ filterMatchesToLoad || null,
748
+ skipRevalidation === true
749
+ );
750
+ return isResponse(result3) ? result3 : { location, basename, ...result3 };
751
+ }
752
+ );
753
+ return res2;
754
+ }
755
+ invariant(respond, "Expected respond to be defined");
756
+ let result2 = await queryImpl(
757
+ request,
758
+ location,
759
+ matches,
760
+ requestContext,
761
+ dataStrategy || null,
762
+ skipLoaderErrorBubbling === true,
763
+ null,
764
+ filterMatchesToLoad || null,
765
+ skipRevalidation === true
766
+ );
767
+ if (isResponse(result2)) {
768
+ return result2;
769
+ }
770
+ renderedStaticContext = { location, basename, ...result2 };
771
+ let res = await respond(renderedStaticContext);
772
+ return res;
773
+ },
774
+ async (error, routeId) => {
775
+ if (isResponse(error)) {
776
+ return error;
777
+ }
778
+ if (renderedStaticContext) {
779
+ if (routeId in renderedStaticContext.loaderData) {
780
+ renderedStaticContext.loaderData[routeId] = void 0;
781
+ }
782
+ let staticContext = getStaticContextFromError(
783
+ dataRoutes,
784
+ renderedStaticContext,
785
+ error,
786
+ skipLoaderErrorBubbling ? routeId : findNearestBoundary(matches, routeId).route.id
787
+ );
788
+ return respondOrStreamStaticContext(staticContext);
789
+ } else {
790
+ let boundaryRouteId = skipLoaderErrorBubbling ? routeId : findNearestBoundary(
791
+ matches,
792
+ matches.find(
793
+ (m) => m.route.id === routeId || m.route.loader
794
+ )?.route.id || routeId
795
+ ).route.id;
796
+ let staticContext = {
797
+ matches,
798
+ location,
799
+ basename,
800
+ loaderData: {},
801
+ actionData: null,
802
+ errors: {
803
+ [boundaryRouteId]: error
804
+ },
805
+ statusCode: isRouteErrorResponse(error) ? error.status : 500,
806
+ actionHeaders: {},
807
+ loaderHeaders: {}
808
+ };
809
+ return respondOrStreamStaticContext(staticContext);
810
+ }
811
+ }
812
+ );
813
+ invariant(isResponse(response), "Expected a response in query()");
814
+ return response;
815
+ } catch (e) {
816
+ if (isResponse(e)) {
817
+ return e;
818
+ }
819
+ throw e;
820
+ }
821
+ }
822
+ let result = await queryImpl(
823
+ request,
824
+ location,
825
+ matches,
826
+ requestContext,
827
+ dataStrategy || null,
828
+ skipLoaderErrorBubbling === true,
829
+ null,
830
+ filterMatchesToLoad || null,
831
+ skipRevalidation === true
832
+ );
833
+ if (isResponse(result)) {
834
+ return result;
835
+ }
836
+ return { location, basename, ...result };
837
+ }
838
+ async function queryRoute(request, {
839
+ routeId,
840
+ requestContext,
841
+ dataStrategy,
842
+ unstable_respond: respond
843
+ } = {}) {
844
+ let url = new URL(request.url);
845
+ let method = request.method;
846
+ let location = createLocation("", createPath(url), null, "default");
847
+ let matches = matchRoutes(dataRoutes, location, basename);
848
+ requestContext = requestContext != null ? requestContext : new unstable_RouterContextProvider();
849
+ if (!isValidMethod(method) && method !== "HEAD" && method !== "OPTIONS") {
850
+ throw getInternalRouterError(405, { method });
851
+ } else if (!matches) {
852
+ throw getInternalRouterError(404, { pathname: location.pathname });
853
+ }
854
+ let match = routeId ? matches.find((m) => m.route.id === routeId) : getTargetMatch(matches, location);
855
+ if (routeId && !match) {
856
+ throw getInternalRouterError(403, {
857
+ pathname: location.pathname,
858
+ routeId
859
+ });
860
+ } else if (!match) {
861
+ throw getInternalRouterError(404, { pathname: location.pathname });
862
+ }
863
+ if (respond && matches.some(
864
+ (m) => m.route.unstable_middleware || typeof m.route.lazy === "object" && m.route.lazy.unstable_middleware
865
+ )) {
866
+ invariant(
867
+ requestContext instanceof unstable_RouterContextProvider,
868
+ "When using middleware in `staticHandler.queryRoute()`, any provided `requestContext` must be an instance of `unstable_RouterContextProvider`"
869
+ );
870
+ await loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties);
871
+ let response = await runMiddlewarePipeline(
872
+ {
873
+ request,
874
+ matches,
875
+ params: matches[0].params,
876
+ // If we're calling middleware then it must be enabled so we can cast
877
+ // this to the proper type knowing it's not an `AppLoadContext`
878
+ context: requestContext
879
+ },
880
+ true,
881
+ async () => {
882
+ let result2 = await queryImpl(
883
+ request,
884
+ location,
885
+ matches,
886
+ requestContext,
887
+ dataStrategy || null,
888
+ false,
889
+ match,
890
+ null,
891
+ false
892
+ );
893
+ if (isResponse(result2)) {
894
+ return respond(result2);
895
+ }
896
+ let error2 = result2.errors ? Object.values(result2.errors)[0] : void 0;
897
+ if (error2 !== void 0) {
898
+ throw error2;
899
+ }
900
+ let value = result2.actionData ? Object.values(result2.actionData)[0] : Object.values(result2.loaderData)[0];
901
+ return typeof value === "string" ? new Response(value) : Response.json(value);
902
+ },
903
+ (error2) => {
904
+ if (isResponse(error2)) {
905
+ return respond(error2);
906
+ }
907
+ return new Response(String(error2), {
908
+ status: 500,
909
+ statusText: "Unexpected Server Error"
910
+ });
911
+ }
912
+ );
913
+ return response;
914
+ }
915
+ let result = await queryImpl(
916
+ request,
917
+ location,
918
+ matches,
919
+ requestContext,
920
+ dataStrategy || null,
921
+ false,
922
+ match,
923
+ null,
924
+ false
925
+ );
926
+ if (isResponse(result)) {
927
+ return result;
928
+ }
929
+ let error = result.errors ? Object.values(result.errors)[0] : void 0;
930
+ if (error !== void 0) {
931
+ throw error;
932
+ }
933
+ if (result.actionData) {
934
+ return Object.values(result.actionData)[0];
935
+ }
936
+ if (result.loaderData) {
937
+ return Object.values(result.loaderData)[0];
938
+ }
939
+ return void 0;
940
+ }
941
+ async function queryImpl(request, location, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, skipRevalidation) {
942
+ invariant(
943
+ request.signal,
944
+ "query()/queryRoute() requests must contain an AbortController signal"
945
+ );
946
+ try {
947
+ if (isMutationMethod(request.method)) {
948
+ let result2 = await submit(
949
+ request,
950
+ matches,
951
+ routeMatch || getTargetMatch(matches, location),
952
+ requestContext,
953
+ dataStrategy,
954
+ skipLoaderErrorBubbling,
955
+ routeMatch != null,
956
+ filterMatchesToLoad,
957
+ skipRevalidation
958
+ );
959
+ return result2;
960
+ }
961
+ let result = await loadRouteData(
962
+ request,
963
+ matches,
964
+ requestContext,
965
+ dataStrategy,
966
+ skipLoaderErrorBubbling,
967
+ routeMatch,
968
+ filterMatchesToLoad
969
+ );
970
+ return isResponse(result) ? result : {
971
+ ...result,
972
+ actionData: null,
973
+ actionHeaders: {}
974
+ };
975
+ } catch (e) {
976
+ if (isDataStrategyResult(e) && isResponse(e.result)) {
977
+ if (e.type === "error" /* error */) {
978
+ throw e.result;
979
+ }
980
+ return e.result;
981
+ }
982
+ if (isRedirectResponse(e)) {
983
+ return e;
984
+ }
985
+ throw e;
986
+ }
987
+ }
988
+ async function submit(request, matches, actionMatch, requestContext, dataStrategy, skipLoaderErrorBubbling, isRouteRequest, filterMatchesToLoad, skipRevalidation) {
989
+ let result;
990
+ if (!actionMatch.route.action && !actionMatch.route.lazy) {
991
+ let error = getInternalRouterError(405, {
992
+ method: request.method,
993
+ pathname: new URL(request.url).pathname,
994
+ routeId: actionMatch.route.id
995
+ });
996
+ if (isRouteRequest) {
997
+ throw error;
998
+ }
999
+ result = {
1000
+ type: "error" /* error */,
1001
+ error
1002
+ };
1003
+ } else {
1004
+ let dsMatches = getTargetedDataStrategyMatches(
1005
+ mapRouteProperties,
1006
+ manifest,
1007
+ request,
1008
+ matches,
1009
+ actionMatch,
1010
+ [],
1011
+ requestContext
1012
+ );
1013
+ let results = await callDataStrategy(
1014
+ request,
1015
+ dsMatches,
1016
+ isRouteRequest,
1017
+ requestContext,
1018
+ dataStrategy
1019
+ );
1020
+ result = results[actionMatch.route.id];
1021
+ if (request.signal.aborted) {
1022
+ throwStaticHandlerAbortedError(request, isRouteRequest);
1023
+ }
1024
+ }
1025
+ if (isRedirectResult(result)) {
1026
+ throw new Response(null, {
1027
+ status: result.response.status,
1028
+ headers: {
1029
+ Location: result.response.headers.get("Location")
1030
+ }
1031
+ });
1032
+ }
1033
+ if (isRouteRequest) {
1034
+ if (isErrorResult(result)) {
1035
+ throw result.error;
1036
+ }
1037
+ return {
1038
+ matches: [actionMatch],
1039
+ loaderData: {},
1040
+ actionData: { [actionMatch.route.id]: result.data },
1041
+ errors: null,
1042
+ // Note: statusCode + headers are unused here since queryRoute will
1043
+ // return the raw Response or value
1044
+ statusCode: 200,
1045
+ loaderHeaders: {},
1046
+ actionHeaders: {}
1047
+ };
1048
+ }
1049
+ if (skipRevalidation) {
1050
+ if (isErrorResult(result)) {
1051
+ let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1052
+ return {
1053
+ statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1054
+ actionData: null,
1055
+ actionHeaders: {
1056
+ ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1057
+ },
1058
+ matches,
1059
+ loaderData: {},
1060
+ errors: {
1061
+ [boundaryMatch.route.id]: result.error
1062
+ },
1063
+ loaderHeaders: {}
1064
+ };
1065
+ } else {
1066
+ return {
1067
+ actionData: {
1068
+ [actionMatch.route.id]: result.data
1069
+ },
1070
+ actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {},
1071
+ matches,
1072
+ loaderData: {},
1073
+ errors: null,
1074
+ statusCode: result.statusCode || 200,
1075
+ loaderHeaders: {}
1076
+ };
1077
+ }
1078
+ }
1079
+ let loaderRequest = new Request(request.url, {
1080
+ headers: request.headers,
1081
+ redirect: request.redirect,
1082
+ signal: request.signal
1083
+ });
1084
+ if (isErrorResult(result)) {
1085
+ let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);
1086
+ let handlerContext2 = await loadRouteData(
1087
+ loaderRequest,
1088
+ matches,
1089
+ requestContext,
1090
+ dataStrategy,
1091
+ skipLoaderErrorBubbling,
1092
+ null,
1093
+ filterMatchesToLoad,
1094
+ [boundaryMatch.route.id, result]
1095
+ );
1096
+ return {
1097
+ ...handlerContext2,
1098
+ statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,
1099
+ actionData: null,
1100
+ actionHeaders: {
1101
+ ...result.headers ? { [actionMatch.route.id]: result.headers } : {}
1102
+ }
1103
+ };
1104
+ }
1105
+ let handlerContext = await loadRouteData(
1106
+ loaderRequest,
1107
+ matches,
1108
+ requestContext,
1109
+ dataStrategy,
1110
+ skipLoaderErrorBubbling,
1111
+ null,
1112
+ filterMatchesToLoad
1113
+ );
1114
+ return {
1115
+ ...handlerContext,
1116
+ actionData: {
1117
+ [actionMatch.route.id]: result.data
1118
+ },
1119
+ // action status codes take precedence over loader status codes
1120
+ ...result.statusCode ? { statusCode: result.statusCode } : {},
1121
+ actionHeaders: result.headers ? { [actionMatch.route.id]: result.headers } : {}
1122
+ };
1123
+ }
1124
+ async function loadRouteData(request, matches, requestContext, dataStrategy, skipLoaderErrorBubbling, routeMatch, filterMatchesToLoad, pendingActionResult) {
1125
+ let isRouteRequest = routeMatch != null;
1126
+ if (isRouteRequest && !routeMatch?.route.loader && !routeMatch?.route.lazy) {
1127
+ throw getInternalRouterError(400, {
1128
+ method: request.method,
1129
+ pathname: new URL(request.url).pathname,
1130
+ routeId: routeMatch?.route.id
1131
+ });
1132
+ }
1133
+ let dsMatches;
1134
+ if (routeMatch) {
1135
+ dsMatches = getTargetedDataStrategyMatches(
1136
+ mapRouteProperties,
1137
+ manifest,
1138
+ request,
1139
+ matches,
1140
+ routeMatch,
1141
+ [],
1142
+ requestContext
1143
+ );
1144
+ } else {
1145
+ let maxIdx = pendingActionResult && isErrorResult(pendingActionResult[1]) ? (
1146
+ // Up to but not including the boundary
1147
+ matches.findIndex((m) => m.route.id === pendingActionResult[0]) - 1
1148
+ ) : void 0;
1149
+ dsMatches = matches.map((match, index) => {
1150
+ if (maxIdx != null && index > maxIdx) {
1151
+ return getDataStrategyMatch(
1152
+ mapRouteProperties,
1153
+ manifest,
1154
+ request,
1155
+ match,
1156
+ [],
1157
+ requestContext,
1158
+ false
1159
+ );
1160
+ }
1161
+ return getDataStrategyMatch(
1162
+ mapRouteProperties,
1163
+ manifest,
1164
+ request,
1165
+ match,
1166
+ [],
1167
+ requestContext,
1168
+ (match.route.loader || match.route.lazy) != null && (!filterMatchesToLoad || filterMatchesToLoad(match))
1169
+ );
1170
+ });
1171
+ }
1172
+ if (!dataStrategy && !dsMatches.some((m) => m.shouldLoad)) {
1173
+ return {
1174
+ matches,
1175
+ loaderData: {},
1176
+ errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {
1177
+ [pendingActionResult[0]]: pendingActionResult[1].error
1178
+ } : null,
1179
+ statusCode: 200,
1180
+ loaderHeaders: {}
1181
+ };
1182
+ }
1183
+ let results = await callDataStrategy(
1184
+ request,
1185
+ dsMatches,
1186
+ isRouteRequest,
1187
+ requestContext,
1188
+ dataStrategy
1189
+ );
1190
+ if (request.signal.aborted) {
1191
+ throwStaticHandlerAbortedError(request, isRouteRequest);
1192
+ }
1193
+ let handlerContext = processRouteLoaderData(
1194
+ matches,
1195
+ results,
1196
+ pendingActionResult,
1197
+ true,
1198
+ skipLoaderErrorBubbling
1199
+ );
1200
+ return {
1201
+ ...handlerContext,
1202
+ matches
1203
+ };
1204
+ }
1205
+ async function callDataStrategy(request, matches, isRouteRequest, requestContext, dataStrategy) {
1206
+ let results = await callDataStrategyImpl(
1207
+ dataStrategy || defaultDataStrategy,
1208
+ request,
1209
+ matches,
1210
+ null,
1211
+ requestContext);
1212
+ let dataResults = {};
1213
+ await Promise.all(
1214
+ matches.map(async (match) => {
1215
+ if (!(match.route.id in results)) {
1216
+ return;
1217
+ }
1218
+ let result = results[match.route.id];
1219
+ if (isRedirectDataStrategyResult(result)) {
1220
+ let response = result.result;
1221
+ throw normalizeRelativeRoutingRedirectResponse(
1222
+ response,
1223
+ request,
1224
+ match.route.id,
1225
+ matches,
1226
+ basename
1227
+ );
1228
+ }
1229
+ if (isResponse(result.result) && isRouteRequest) {
1230
+ throw result;
1231
+ }
1232
+ dataResults[match.route.id] = await convertDataStrategyResultToDataResult(result);
1233
+ })
1234
+ );
1235
+ return dataResults;
1236
+ }
1237
+ return {
1238
+ dataRoutes,
1239
+ query,
1240
+ queryRoute
1241
+ };
1242
+ }
1243
+ function getStaticContextFromError(routes, handlerContext, error, boundaryId) {
1244
+ let errorBoundaryId = boundaryId || handlerContext._deepestRenderedBoundaryId || routes[0].id;
1245
+ return {
1246
+ ...handlerContext,
1247
+ statusCode: isRouteErrorResponse(error) ? error.status : 500,
1248
+ errors: {
1249
+ [errorBoundaryId]: error
1250
+ }
1251
+ };
1252
+ }
1253
+ function throwStaticHandlerAbortedError(request, isRouteRequest) {
1254
+ if (request.signal.reason !== void 0) {
1255
+ throw request.signal.reason;
1256
+ }
1257
+ let method = isRouteRequest ? "queryRoute" : "query";
1258
+ throw new Error(
1259
+ `${method}() call aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1260
+ );
1261
+ }
1262
+ function normalizeTo(location, matches, basename, to, fromRouteId, relative) {
1263
+ let contextualMatches;
1264
+ let activeRouteMatch;
1265
+ {
1266
+ contextualMatches = matches;
1267
+ activeRouteMatch = matches[matches.length - 1];
1268
+ }
1269
+ let path = resolveTo(
1270
+ to ? to : ".",
1271
+ getResolveToMatches(contextualMatches),
1272
+ stripBasename(location.pathname, basename) || location.pathname,
1273
+ relative === "path"
1274
+ );
1275
+ if (to == null) {
1276
+ path.search = location.search;
1277
+ path.hash = location.hash;
1278
+ }
1279
+ if ((to == null || to === "" || to === ".") && activeRouteMatch) {
1280
+ let nakedIndex = hasNakedIndexQuery(path.search);
1281
+ if (activeRouteMatch.route.index && !nakedIndex) {
1282
+ path.search = path.search ? path.search.replace(/^\?/, "?index&") : "?index";
1283
+ } else if (!activeRouteMatch.route.index && nakedIndex) {
1284
+ let params = new URLSearchParams(path.search);
1285
+ let indexValues = params.getAll("index");
1286
+ params.delete("index");
1287
+ indexValues.filter((v) => v).forEach((v) => params.append("index", v));
1288
+ let qs = params.toString();
1289
+ path.search = qs ? `?${qs}` : "";
1290
+ }
1291
+ }
1292
+ if (basename !== "/") {
1293
+ path.pathname = path.pathname === "/" ? basename : joinPaths([basename, path.pathname]);
1294
+ }
1295
+ return createPath(path);
1296
+ }
1297
+ function shouldRevalidateLoader(loaderMatch, arg) {
1298
+ if (loaderMatch.route.shouldRevalidate) {
1299
+ let routeChoice = loaderMatch.route.shouldRevalidate(arg);
1300
+ if (typeof routeChoice === "boolean") {
1301
+ return routeChoice;
1302
+ }
1303
+ }
1304
+ return arg.defaultShouldRevalidate;
1305
+ }
1306
+ var lazyRoutePropertyCache = /* @__PURE__ */ new WeakMap();
1307
+ var loadLazyRouteProperty = ({
1308
+ key,
1309
+ route,
1310
+ manifest,
1311
+ mapRouteProperties
1312
+ }) => {
1313
+ let routeToUpdate = manifest[route.id];
1314
+ invariant(routeToUpdate, "No route found in manifest");
1315
+ if (!routeToUpdate.lazy || typeof routeToUpdate.lazy !== "object") {
1316
+ return;
1317
+ }
1318
+ let lazyFn = routeToUpdate.lazy[key];
1319
+ if (!lazyFn) {
1320
+ return;
1321
+ }
1322
+ let cache = lazyRoutePropertyCache.get(routeToUpdate);
1323
+ if (!cache) {
1324
+ cache = {};
1325
+ lazyRoutePropertyCache.set(routeToUpdate, cache);
1326
+ }
1327
+ let cachedPromise = cache[key];
1328
+ if (cachedPromise) {
1329
+ return cachedPromise;
1330
+ }
1331
+ let propertyPromise = (async () => {
1332
+ let isUnsupported = isUnsupportedLazyRouteObjectKey(key);
1333
+ let staticRouteValue = routeToUpdate[key];
1334
+ let isStaticallyDefined = staticRouteValue !== void 0 && key !== "hasErrorBoundary";
1335
+ if (isUnsupported) {
1336
+ warning(
1337
+ !isUnsupported,
1338
+ "Route property " + key + " is not a supported lazy route property. This property will be ignored."
1339
+ );
1340
+ cache[key] = Promise.resolve();
1341
+ } else if (isStaticallyDefined) {
1342
+ warning(
1343
+ false,
1344
+ `Route "${routeToUpdate.id}" has a static property "${key}" defined. The lazy property will be ignored.`
1345
+ );
1346
+ } else {
1347
+ let value = await lazyFn();
1348
+ if (value != null) {
1349
+ Object.assign(routeToUpdate, { [key]: value });
1350
+ Object.assign(routeToUpdate, mapRouteProperties(routeToUpdate));
1351
+ }
1352
+ }
1353
+ if (typeof routeToUpdate.lazy === "object") {
1354
+ routeToUpdate.lazy[key] = void 0;
1355
+ if (Object.values(routeToUpdate.lazy).every((value) => value === void 0)) {
1356
+ routeToUpdate.lazy = void 0;
1357
+ }
1358
+ }
1359
+ })();
1360
+ cache[key] = propertyPromise;
1361
+ return propertyPromise;
1362
+ };
1363
+ var lazyRouteFunctionCache = /* @__PURE__ */ new WeakMap();
1364
+ function loadLazyRoute(route, type, manifest, mapRouteProperties, lazyRoutePropertiesToSkip) {
1365
+ let routeToUpdate = manifest[route.id];
1366
+ invariant(routeToUpdate, "No route found in manifest");
1367
+ if (!route.lazy) {
1368
+ return {
1369
+ lazyRoutePromise: void 0,
1370
+ lazyHandlerPromise: void 0
1371
+ };
1372
+ }
1373
+ if (typeof route.lazy === "function") {
1374
+ let cachedPromise = lazyRouteFunctionCache.get(routeToUpdate);
1375
+ if (cachedPromise) {
1376
+ return {
1377
+ lazyRoutePromise: cachedPromise,
1378
+ lazyHandlerPromise: cachedPromise
1379
+ };
1380
+ }
1381
+ let lazyRoutePromise2 = (async () => {
1382
+ invariant(
1383
+ typeof route.lazy === "function",
1384
+ "No lazy route function found"
1385
+ );
1386
+ let lazyRoute = await route.lazy();
1387
+ let routeUpdates = {};
1388
+ for (let lazyRouteProperty in lazyRoute) {
1389
+ let lazyValue = lazyRoute[lazyRouteProperty];
1390
+ if (lazyValue === void 0) {
1391
+ continue;
1392
+ }
1393
+ let isUnsupported = isUnsupportedLazyRouteFunctionKey(lazyRouteProperty);
1394
+ let staticRouteValue = routeToUpdate[lazyRouteProperty];
1395
+ let isStaticallyDefined = staticRouteValue !== void 0 && // This property isn't static since it should always be updated based
1396
+ // on the route updates
1397
+ lazyRouteProperty !== "hasErrorBoundary";
1398
+ if (isUnsupported) {
1399
+ warning(
1400
+ !isUnsupported,
1401
+ "Route property " + lazyRouteProperty + " is not a supported property to be returned from a lazy route function. This property will be ignored."
1402
+ );
1403
+ } else if (isStaticallyDefined) {
1404
+ warning(
1405
+ !isStaticallyDefined,
1406
+ `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.`
1407
+ );
1408
+ } else {
1409
+ routeUpdates[lazyRouteProperty] = lazyValue;
1410
+ }
1411
+ }
1412
+ Object.assign(routeToUpdate, routeUpdates);
1413
+ Object.assign(routeToUpdate, {
1414
+ // To keep things framework agnostic, we use the provided `mapRouteProperties`
1415
+ // function to set the framework-aware properties (`element`/`hasErrorBoundary`)
1416
+ // since the logic will differ between frameworks.
1417
+ ...mapRouteProperties(routeToUpdate),
1418
+ lazy: void 0
1419
+ });
1420
+ })();
1421
+ lazyRouteFunctionCache.set(routeToUpdate, lazyRoutePromise2);
1422
+ lazyRoutePromise2.catch(() => {
1423
+ });
1424
+ return {
1425
+ lazyRoutePromise: lazyRoutePromise2,
1426
+ lazyHandlerPromise: lazyRoutePromise2
1427
+ };
1428
+ }
1429
+ let lazyKeys = Object.keys(route.lazy);
1430
+ let lazyPropertyPromises = [];
1431
+ let lazyHandlerPromise = void 0;
1432
+ for (let key of lazyKeys) {
1433
+ if (lazyRoutePropertiesToSkip && lazyRoutePropertiesToSkip.includes(key)) {
1434
+ continue;
1435
+ }
1436
+ let promise = loadLazyRouteProperty({
1437
+ key,
1438
+ route,
1439
+ manifest,
1440
+ mapRouteProperties
1441
+ });
1442
+ if (promise) {
1443
+ lazyPropertyPromises.push(promise);
1444
+ if (key === type) {
1445
+ lazyHandlerPromise = promise;
1446
+ }
1447
+ }
1448
+ }
1449
+ let lazyRoutePromise = lazyPropertyPromises.length > 0 ? Promise.all(lazyPropertyPromises).then(() => {
1450
+ }) : void 0;
1451
+ lazyRoutePromise?.catch(() => {
1452
+ });
1453
+ lazyHandlerPromise?.catch(() => {
1454
+ });
1455
+ return {
1456
+ lazyRoutePromise,
1457
+ lazyHandlerPromise
1458
+ };
1459
+ }
1460
+ function isNonNullable(value) {
1461
+ return value !== void 0;
1462
+ }
1463
+ function loadLazyMiddlewareForMatches(matches, manifest, mapRouteProperties) {
1464
+ let promises = matches.map(({ route }) => {
1465
+ if (typeof route.lazy !== "object" || !route.lazy.unstable_middleware) {
1466
+ return void 0;
1467
+ }
1468
+ return loadLazyRouteProperty({
1469
+ key: "unstable_middleware",
1470
+ route,
1471
+ manifest,
1472
+ mapRouteProperties
1473
+ });
1474
+ }).filter(isNonNullable);
1475
+ return promises.length > 0 ? Promise.all(promises) : void 0;
1476
+ }
1477
+ async function defaultDataStrategy(args) {
1478
+ let matchesToLoad = args.matches.filter((m) => m.shouldLoad);
1479
+ let keyedResults = {};
1480
+ let results = await Promise.all(matchesToLoad.map((m) => m.resolve()));
1481
+ results.forEach((result, i) => {
1482
+ keyedResults[matchesToLoad[i].route.id] = result;
1483
+ });
1484
+ return keyedResults;
1485
+ }
1486
+ async function runMiddlewarePipeline(args, propagateResult, handler, errorHandler) {
1487
+ let { matches, request, params, context } = args;
1488
+ let middlewareState = {
1489
+ handlerResult: void 0
1490
+ };
1491
+ try {
1492
+ let tuples = matches.flatMap(
1493
+ (m) => m.route.unstable_middleware ? m.route.unstable_middleware.map((fn) => [m.route.id, fn]) : []
1494
+ );
1495
+ let result = await callRouteMiddleware(
1496
+ { request, params, context },
1497
+ tuples,
1498
+ propagateResult,
1499
+ middlewareState,
1500
+ handler
1501
+ );
1502
+ return propagateResult ? result : middlewareState.handlerResult;
1503
+ } catch (e) {
1504
+ if (!middlewareState.middlewareError) {
1505
+ throw e;
1506
+ }
1507
+ let result = await errorHandler(
1508
+ middlewareState.middlewareError.error,
1509
+ middlewareState.middlewareError.routeId
1510
+ );
1511
+ {
1512
+ return result;
1513
+ }
1514
+ }
1515
+ }
1516
+ async function callRouteMiddleware(args, middlewares, propagateResult, middlewareState, handler, idx = 0) {
1517
+ let { request } = args;
1518
+ if (request.signal.aborted) {
1519
+ if (request.signal.reason) {
1520
+ throw request.signal.reason;
1521
+ }
1522
+ throw new Error(
1523
+ `Request aborted without an \`AbortSignal.reason\`: ${request.method} ${request.url}`
1524
+ );
1525
+ }
1526
+ let tuple = middlewares[idx];
1527
+ if (!tuple) {
1528
+ middlewareState.handlerResult = await handler();
1529
+ return middlewareState.handlerResult;
1530
+ }
1531
+ let [routeId, middleware] = tuple;
1532
+ let nextCalled = false;
1533
+ let nextResult = void 0;
1534
+ let next = async () => {
1535
+ if (nextCalled) {
1536
+ throw new Error("You may only call `next()` once per middleware");
1537
+ }
1538
+ nextCalled = true;
1539
+ let result = await callRouteMiddleware(
1540
+ args,
1541
+ middlewares,
1542
+ propagateResult,
1543
+ middlewareState,
1544
+ handler,
1545
+ idx + 1
1546
+ );
1547
+ {
1548
+ nextResult = result;
1549
+ return nextResult;
1550
+ }
1551
+ };
1552
+ try {
1553
+ let result = await middleware(
1554
+ {
1555
+ request: args.request,
1556
+ params: args.params,
1557
+ context: args.context
1558
+ },
1559
+ next
1560
+ );
1561
+ if (nextCalled) {
1562
+ if (result === void 0) {
1563
+ return nextResult;
1564
+ } else {
1565
+ return result;
1566
+ }
1567
+ } else {
1568
+ return next();
1569
+ }
1570
+ } catch (error) {
1571
+ if (!middlewareState.middlewareError) {
1572
+ middlewareState.middlewareError = { routeId, error };
1573
+ } else if (middlewareState.middlewareError.error !== error) {
1574
+ middlewareState.middlewareError = { routeId, error };
1575
+ }
1576
+ throw error;
1577
+ }
1578
+ }
1579
+ function getDataStrategyMatchLazyPromises(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip) {
1580
+ let lazyMiddlewarePromise = loadLazyRouteProperty({
1581
+ key: "unstable_middleware",
1582
+ route: match.route,
1583
+ manifest,
1584
+ mapRouteProperties
1585
+ });
1586
+ let lazyRoutePromises = loadLazyRoute(
1587
+ match.route,
1588
+ isMutationMethod(request.method) ? "action" : "loader",
1589
+ manifest,
1590
+ mapRouteProperties,
1591
+ lazyRoutePropertiesToSkip
1592
+ );
1593
+ return {
1594
+ middleware: lazyMiddlewarePromise,
1595
+ route: lazyRoutePromises.lazyRoutePromise,
1596
+ handler: lazyRoutePromises.lazyHandlerPromise
1597
+ };
1598
+ }
1599
+ function getDataStrategyMatch(mapRouteProperties, manifest, request, match, lazyRoutePropertiesToSkip, scopedContext, shouldLoad, unstable_shouldRevalidateArgs = null) {
1600
+ let isUsingNewApi = false;
1601
+ let _lazyPromises = getDataStrategyMatchLazyPromises(
1602
+ mapRouteProperties,
1603
+ manifest,
1604
+ request,
1605
+ match,
1606
+ lazyRoutePropertiesToSkip
1607
+ );
1608
+ return {
1609
+ ...match,
1610
+ _lazyPromises,
1611
+ shouldLoad,
1612
+ unstable_shouldRevalidateArgs,
1613
+ unstable_shouldCallHandler(defaultShouldRevalidate) {
1614
+ isUsingNewApi = true;
1615
+ if (!unstable_shouldRevalidateArgs) {
1616
+ return shouldLoad;
1617
+ }
1618
+ if (typeof defaultShouldRevalidate === "boolean") {
1619
+ return shouldRevalidateLoader(match, {
1620
+ ...unstable_shouldRevalidateArgs,
1621
+ defaultShouldRevalidate
1622
+ });
1623
+ }
1624
+ return shouldRevalidateLoader(match, unstable_shouldRevalidateArgs);
1625
+ },
1626
+ resolve(handlerOverride) {
1627
+ if (isUsingNewApi || shouldLoad || handlerOverride && !isMutationMethod(request.method) && (match.route.lazy || match.route.loader)) {
1628
+ return callLoaderOrAction({
1629
+ request,
1630
+ match,
1631
+ lazyHandlerPromise: _lazyPromises?.handler,
1632
+ lazyRoutePromise: _lazyPromises?.route,
1633
+ handlerOverride,
1634
+ scopedContext
1635
+ });
1636
+ }
1637
+ return Promise.resolve({ type: "data" /* data */, result: void 0 });
1638
+ }
1639
+ };
1640
+ }
1641
+ function getTargetedDataStrategyMatches(mapRouteProperties, manifest, request, matches, targetMatch, lazyRoutePropertiesToSkip, scopedContext, shouldRevalidateArgs = null) {
1642
+ return matches.map((match) => {
1643
+ if (match.route.id !== targetMatch.route.id) {
1644
+ return {
1645
+ ...match,
1646
+ shouldLoad: false,
1647
+ unstable_shouldRevalidateArgs: shouldRevalidateArgs,
1648
+ unstable_shouldCallHandler: () => false,
1649
+ _lazyPromises: getDataStrategyMatchLazyPromises(
1650
+ mapRouteProperties,
1651
+ manifest,
1652
+ request,
1653
+ match,
1654
+ lazyRoutePropertiesToSkip
1655
+ ),
1656
+ resolve: () => Promise.resolve({ type: "data", result: void 0 })
1657
+ };
1658
+ }
1659
+ return getDataStrategyMatch(
1660
+ mapRouteProperties,
1661
+ manifest,
1662
+ request,
1663
+ match,
1664
+ lazyRoutePropertiesToSkip,
1665
+ scopedContext,
1666
+ true,
1667
+ shouldRevalidateArgs
1668
+ );
1669
+ });
1670
+ }
1671
+ async function callDataStrategyImpl(dataStrategyImpl, request, matches, fetcherKey, scopedContext, isStaticHandler) {
1672
+ if (matches.some((m) => m._lazyPromises?.middleware)) {
1673
+ await Promise.all(matches.map((m) => m._lazyPromises?.middleware));
1674
+ }
1675
+ let dataStrategyArgs = {
1676
+ request,
1677
+ params: matches[0].params,
1678
+ context: scopedContext,
1679
+ matches
1680
+ };
1681
+ let unstable_runClientMiddleware = () => {
1682
+ throw new Error(
1683
+ "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`"
1684
+ );
1685
+ } ;
1686
+ let results = await dataStrategyImpl({
1687
+ ...dataStrategyArgs,
1688
+ fetcherKey,
1689
+ unstable_runClientMiddleware
1690
+ });
1691
+ try {
1692
+ await Promise.all(
1693
+ matches.flatMap((m) => [m._lazyPromises?.handler, m._lazyPromises?.route])
1694
+ );
1695
+ } catch (e) {
1696
+ }
1697
+ return results;
1698
+ }
1699
+ async function callLoaderOrAction({
1700
+ request,
1701
+ match,
1702
+ lazyHandlerPromise,
1703
+ lazyRoutePromise,
1704
+ handlerOverride,
1705
+ scopedContext
1706
+ }) {
1707
+ let result;
1708
+ let onReject;
1709
+ let isAction = isMutationMethod(request.method);
1710
+ let type = isAction ? "action" : "loader";
1711
+ let runHandler = (handler) => {
1712
+ let reject;
1713
+ let abortPromise = new Promise((_, r) => reject = r);
1714
+ onReject = () => reject();
1715
+ request.signal.addEventListener("abort", onReject);
1716
+ let actualHandler = (ctx) => {
1717
+ if (typeof handler !== "function") {
1718
+ return Promise.reject(
1719
+ new Error(
1720
+ `You cannot call the handler for a route which defines a boolean "${type}" [routeId: ${match.route.id}]`
1721
+ )
1722
+ );
1723
+ }
1724
+ return handler(
1725
+ {
1726
+ request,
1727
+ params: match.params,
1728
+ context: scopedContext
1729
+ },
1730
+ ...ctx !== void 0 ? [ctx] : []
1731
+ );
1732
+ };
1733
+ let handlerPromise = (async () => {
1734
+ try {
1735
+ let val = await (handlerOverride ? handlerOverride((ctx) => actualHandler(ctx)) : actualHandler());
1736
+ return { type: "data", result: val };
1737
+ } catch (e) {
1738
+ return { type: "error", result: e };
1739
+ }
1740
+ })();
1741
+ return Promise.race([handlerPromise, abortPromise]);
1742
+ };
1743
+ try {
1744
+ let handler = isAction ? match.route.action : match.route.loader;
1745
+ if (lazyHandlerPromise || lazyRoutePromise) {
1746
+ if (handler) {
1747
+ let handlerError;
1748
+ let [value] = await Promise.all([
1749
+ // If the handler throws, don't let it immediately bubble out,
1750
+ // since we need to let the lazy() execution finish so we know if this
1751
+ // route has a boundary that can handle the error
1752
+ runHandler(handler).catch((e) => {
1753
+ handlerError = e;
1754
+ }),
1755
+ // Ensure all lazy route promises are resolved before continuing
1756
+ lazyHandlerPromise,
1757
+ lazyRoutePromise
1758
+ ]);
1759
+ if (handlerError !== void 0) {
1760
+ throw handlerError;
1761
+ }
1762
+ result = value;
1763
+ } else {
1764
+ await lazyHandlerPromise;
1765
+ let handler2 = isAction ? match.route.action : match.route.loader;
1766
+ if (handler2) {
1767
+ [result] = await Promise.all([runHandler(handler2), lazyRoutePromise]);
1768
+ } else if (type === "action") {
1769
+ let url = new URL(request.url);
1770
+ let pathname = url.pathname + url.search;
1771
+ throw getInternalRouterError(405, {
1772
+ method: request.method,
1773
+ pathname,
1774
+ routeId: match.route.id
1775
+ });
1776
+ } else {
1777
+ return { type: "data" /* data */, result: void 0 };
1778
+ }
1779
+ }
1780
+ } else if (!handler) {
1781
+ let url = new URL(request.url);
1782
+ let pathname = url.pathname + url.search;
1783
+ throw getInternalRouterError(404, {
1784
+ pathname
1785
+ });
1786
+ } else {
1787
+ result = await runHandler(handler);
1788
+ }
1789
+ } catch (e) {
1790
+ return { type: "error" /* error */, result: e };
1791
+ } finally {
1792
+ if (onReject) {
1793
+ request.signal.removeEventListener("abort", onReject);
1794
+ }
1795
+ }
1796
+ return result;
1797
+ }
1798
+ async function convertDataStrategyResultToDataResult(dataStrategyResult) {
1799
+ let { result, type } = dataStrategyResult;
1800
+ if (isResponse(result)) {
1801
+ let data2;
1802
+ try {
1803
+ let contentType = result.headers.get("Content-Type");
1804
+ if (contentType && /\bapplication\/json\b/.test(contentType)) {
1805
+ if (result.body == null) {
1806
+ data2 = null;
1807
+ } else {
1808
+ data2 = await result.json();
1809
+ }
1810
+ } else {
1811
+ data2 = await result.text();
1812
+ }
1813
+ } catch (e) {
1814
+ return { type: "error" /* error */, error: e };
1815
+ }
1816
+ if (type === "error" /* error */) {
1817
+ return {
1818
+ type: "error" /* error */,
1819
+ error: new ErrorResponseImpl(result.status, result.statusText, data2),
1820
+ statusCode: result.status,
1821
+ headers: result.headers
1822
+ };
1823
+ }
1824
+ return {
1825
+ type: "data" /* data */,
1826
+ data: data2,
1827
+ statusCode: result.status,
1828
+ headers: result.headers
1829
+ };
1830
+ }
1831
+ if (type === "error" /* error */) {
1832
+ if (isDataWithResponseInit(result)) {
1833
+ if (result.data instanceof Error) {
1834
+ return {
1835
+ type: "error" /* error */,
1836
+ error: result.data,
1837
+ statusCode: result.init?.status,
1838
+ headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1839
+ };
1840
+ }
1841
+ return {
1842
+ type: "error" /* error */,
1843
+ error: new ErrorResponseImpl(
1844
+ result.init?.status || 500,
1845
+ void 0,
1846
+ result.data
1847
+ ),
1848
+ statusCode: isRouteErrorResponse(result) ? result.status : void 0,
1849
+ headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1850
+ };
1851
+ }
1852
+ return {
1853
+ type: "error" /* error */,
1854
+ error: result,
1855
+ statusCode: isRouteErrorResponse(result) ? result.status : void 0
1856
+ };
1857
+ }
1858
+ if (isDataWithResponseInit(result)) {
1859
+ return {
1860
+ type: "data" /* data */,
1861
+ data: result.data,
1862
+ statusCode: result.init?.status,
1863
+ headers: result.init?.headers ? new Headers(result.init.headers) : void 0
1864
+ };
1865
+ }
1866
+ return { type: "data" /* data */, data: result };
1867
+ }
1868
+ function normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename) {
1869
+ let location = response.headers.get("Location");
1870
+ invariant(
1871
+ location,
1872
+ "Redirects returned/thrown from loaders/actions must have a Location header"
1873
+ );
1874
+ if (!ABSOLUTE_URL_REGEX.test(location)) {
1875
+ let trimmedMatches = matches.slice(
1876
+ 0,
1877
+ matches.findIndex((m) => m.route.id === routeId) + 1
1878
+ );
1879
+ location = normalizeTo(
1880
+ new URL(request.url),
1881
+ trimmedMatches,
1882
+ basename,
1883
+ location
1884
+ );
1885
+ response.headers.set("Location", location);
1886
+ }
1887
+ return response;
1888
+ }
1889
+ function processRouteLoaderData(matches, results, pendingActionResult, isStaticHandler = false, skipLoaderErrorBubbling = false) {
1890
+ let loaderData = {};
1891
+ let errors = null;
1892
+ let statusCode;
1893
+ let foundError = false;
1894
+ let loaderHeaders = {};
1895
+ let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : void 0;
1896
+ matches.forEach((match) => {
1897
+ if (!(match.route.id in results)) {
1898
+ return;
1899
+ }
1900
+ let id = match.route.id;
1901
+ let result = results[id];
1902
+ invariant(
1903
+ !isRedirectResult(result),
1904
+ "Cannot handle redirect results in processLoaderData"
1905
+ );
1906
+ if (isErrorResult(result)) {
1907
+ let error = result.error;
1908
+ if (pendingError !== void 0) {
1909
+ error = pendingError;
1910
+ pendingError = void 0;
1911
+ }
1912
+ errors = errors || {};
1913
+ if (skipLoaderErrorBubbling) {
1914
+ errors[id] = error;
1915
+ } else {
1916
+ let boundaryMatch = findNearestBoundary(matches, id);
1917
+ if (errors[boundaryMatch.route.id] == null) {
1918
+ errors[boundaryMatch.route.id] = error;
1919
+ }
1920
+ }
1921
+ if (!isStaticHandler) {
1922
+ loaderData[id] = ResetLoaderDataSymbol;
1923
+ }
1924
+ if (!foundError) {
1925
+ foundError = true;
1926
+ statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
1927
+ }
1928
+ if (result.headers) {
1929
+ loaderHeaders[id] = result.headers;
1930
+ }
1931
+ } else {
1932
+ loaderData[id] = result.data;
1933
+ if (result.statusCode && result.statusCode !== 200 && !foundError) {
1934
+ statusCode = result.statusCode;
1935
+ }
1936
+ if (result.headers) {
1937
+ loaderHeaders[id] = result.headers;
1938
+ }
1939
+ }
1940
+ });
1941
+ if (pendingError !== void 0 && pendingActionResult) {
1942
+ errors = { [pendingActionResult[0]]: pendingError };
1943
+ if (pendingActionResult[2]) {
1944
+ loaderData[pendingActionResult[2]] = void 0;
1945
+ }
1946
+ }
1947
+ return {
1948
+ loaderData,
1949
+ errors,
1950
+ statusCode: statusCode || 200,
1951
+ loaderHeaders
1952
+ };
1953
+ }
1954
+ function findNearestBoundary(matches, routeId) {
1955
+ let eligibleMatches = routeId ? matches.slice(0, matches.findIndex((m) => m.route.id === routeId) + 1) : [...matches];
1956
+ return eligibleMatches.reverse().find((m) => m.route.hasErrorBoundary === true) || matches[0];
1957
+ }
1958
+ function getShortCircuitMatches(routes) {
1959
+ let route = routes.length === 1 ? routes[0] : routes.find((r) => r.index || !r.path || r.path === "/") || {
1960
+ id: `__shim-error-route__`
1961
+ };
1962
+ return {
1963
+ matches: [
1964
+ {
1965
+ params: {},
1966
+ pathname: "",
1967
+ pathnameBase: "",
1968
+ route
1969
+ }
1970
+ ],
1971
+ route
1972
+ };
1973
+ }
1974
+ function getInternalRouterError(status, {
1975
+ pathname,
1976
+ routeId,
1977
+ method,
1978
+ type,
1979
+ message
1980
+ } = {}) {
1981
+ let statusText = "Unknown Server Error";
1982
+ let errorMessage = "Unknown @remix-run/router error";
1983
+ if (status === 400) {
1984
+ statusText = "Bad Request";
1985
+ if (method && pathname && routeId) {
1986
+ 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.`;
1987
+ } else if (type === "invalid-body") {
1988
+ errorMessage = "Unable to encode submission body";
1989
+ }
1990
+ } else if (status === 403) {
1991
+ statusText = "Forbidden";
1992
+ errorMessage = `Route "${routeId}" does not match URL "${pathname}"`;
1993
+ } else if (status === 404) {
1994
+ statusText = "Not Found";
1995
+ errorMessage = `No route matches URL "${pathname}"`;
1996
+ } else if (status === 405) {
1997
+ statusText = "Method Not Allowed";
1998
+ if (method && pathname && routeId) {
1999
+ 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.`;
2000
+ } else if (method) {
2001
+ errorMessage = `Invalid request method "${method.toUpperCase()}"`;
2002
+ }
2003
+ }
2004
+ return new ErrorResponseImpl(
2005
+ status || 500,
2006
+ statusText,
2007
+ new Error(errorMessage),
2008
+ true
2009
+ );
2010
+ }
2011
+ function isDataStrategyResult(result) {
2012
+ return result != null && typeof result === "object" && "type" in result && "result" in result && (result.type === "data" /* data */ || result.type === "error" /* error */);
2013
+ }
2014
+ function isRedirectDataStrategyResult(result) {
2015
+ return isResponse(result.result) && redirectStatusCodes.has(result.result.status);
2016
+ }
2017
+ function isErrorResult(result) {
2018
+ return result.type === "error" /* error */;
2019
+ }
2020
+ function isRedirectResult(result) {
2021
+ return (result && result.type) === "redirect" /* redirect */;
2022
+ }
2023
+ function isDataWithResponseInit(value) {
2024
+ return typeof value === "object" && value != null && "type" in value && "data" in value && "init" in value && value.type === "DataWithResponseInit";
2025
+ }
2026
+ function isResponse(value) {
2027
+ return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
2028
+ }
2029
+ function isRedirectStatusCode(statusCode) {
2030
+ return redirectStatusCodes.has(statusCode);
2031
+ }
2032
+ function isRedirectResponse(result) {
2033
+ return isResponse(result) && isRedirectStatusCode(result.status) && result.headers.has("Location");
2034
+ }
2035
+ function isValidMethod(method) {
2036
+ return validRequestMethods.has(method.toUpperCase());
2037
+ }
2038
+ function isMutationMethod(method) {
2039
+ return validMutationMethods.has(method.toUpperCase());
2040
+ }
2041
+ function hasNakedIndexQuery(search) {
2042
+ return new URLSearchParams(search).getAll("index").some((v) => v === "");
2043
+ }
2044
+ function getTargetMatch(matches, location) {
2045
+ let search = typeof location === "string" ? parsePath(location).search : location.search;
2046
+ if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
2047
+ return matches[matches.length - 1];
2048
+ }
2049
+ let pathMatches = getPathContributingMatches(matches);
2050
+ return pathMatches[pathMatches.length - 1];
2051
+ }
2052
+
2053
+ // lib/server-runtime/invariant.ts
2054
+ function invariant2(value, message) {
2055
+ if (value === false || value === null || typeof value === "undefined") {
2056
+ console.error(
2057
+ "The following error is a bug in React Router; please open an issue! https://github.com/remix-run/react-router/issues/new/choose"
2058
+ );
2059
+ throw new Error(message);
2060
+ }
2061
+ }
2062
+
2063
+ // lib/server-runtime/headers.ts
2064
+ function getDocumentHeadersImpl(context, getRouteHeadersFn) {
2065
+ let boundaryIdx = context.errors ? context.matches.findIndex((m) => context.errors[m.route.id]) : -1;
2066
+ let matches = boundaryIdx >= 0 ? context.matches.slice(0, boundaryIdx + 1) : context.matches;
2067
+ let errorHeaders;
2068
+ if (boundaryIdx >= 0) {
2069
+ let { actionHeaders, actionData, loaderHeaders, loaderData } = context;
2070
+ context.matches.slice(boundaryIdx).some((match) => {
2071
+ let id = match.route.id;
2072
+ if (actionHeaders[id] && (!actionData || !actionData.hasOwnProperty(id))) {
2073
+ errorHeaders = actionHeaders[id];
2074
+ } else if (loaderHeaders[id] && !loaderData.hasOwnProperty(id)) {
2075
+ errorHeaders = loaderHeaders[id];
2076
+ }
2077
+ return errorHeaders != null;
2078
+ });
2079
+ }
2080
+ return matches.reduce((parentHeaders, match, idx) => {
2081
+ let { id } = match.route;
2082
+ let loaderHeaders = context.loaderHeaders[id] || new Headers();
2083
+ let actionHeaders = context.actionHeaders[id] || new Headers();
2084
+ let includeErrorHeaders = errorHeaders != null && idx === matches.length - 1;
2085
+ let includeErrorCookies = includeErrorHeaders && errorHeaders !== loaderHeaders && errorHeaders !== actionHeaders;
2086
+ let headersFn = getRouteHeadersFn(match);
2087
+ if (headersFn == null) {
2088
+ let headers2 = new Headers(parentHeaders);
2089
+ if (includeErrorCookies) {
2090
+ prependCookies(errorHeaders, headers2);
2091
+ }
2092
+ prependCookies(actionHeaders, headers2);
2093
+ prependCookies(loaderHeaders, headers2);
2094
+ return headers2;
2095
+ }
2096
+ let headers = new Headers(
2097
+ typeof headersFn === "function" ? headersFn({
2098
+ loaderHeaders,
2099
+ parentHeaders,
2100
+ actionHeaders,
2101
+ errorHeaders: includeErrorHeaders ? errorHeaders : void 0
2102
+ }) : headersFn
2103
+ );
2104
+ if (includeErrorCookies) {
2105
+ prependCookies(errorHeaders, headers);
2106
+ }
2107
+ prependCookies(actionHeaders, headers);
2108
+ prependCookies(loaderHeaders, headers);
2109
+ prependCookies(parentHeaders, headers);
2110
+ return headers;
2111
+ }, new Headers());
2112
+ }
2113
+ function prependCookies(parentHeaders, childHeaders) {
2114
+ let parentSetCookieString = parentHeaders.get("Set-Cookie");
2115
+ if (parentSetCookieString) {
2116
+ let cookies = setCookieParser.splitCookiesString(parentSetCookieString);
2117
+ let childCookies = new Set(childHeaders.getSetCookie());
2118
+ cookies.forEach((cookie) => {
2119
+ if (!childCookies.has(cookie)) {
2120
+ childHeaders.append("Set-Cookie", cookie);
2121
+ }
2122
+ });
2123
+ }
2124
+ }
2125
+ var SINGLE_FETCH_REDIRECT_STATUS = 202;
2126
+
2127
+ // lib/rsc/server.rsc.ts
2128
+ var globalVar = typeof globalThis !== "undefined" ? globalThis : global;
2129
+ var ServerStorage = globalVar.___reactRouterServerStorage___ ?? (globalVar.___reactRouterServerStorage___ = new node_async_hooks.AsyncLocalStorage());
2130
+ var redirect2 = (...args) => {
2131
+ const response = redirect(...args);
2132
+ const ctx = ServerStorage.getStore();
2133
+ if (ctx) {
2134
+ ctx.redirect = response;
2135
+ }
2136
+ return response;
2137
+ };
2138
+ var redirectDocument2 = (...args) => {
2139
+ const response = redirectDocument(...args);
2140
+ const ctx = ServerStorage.getStore();
2141
+ if (ctx) {
2142
+ ctx.redirect = response;
2143
+ }
2144
+ return response;
2145
+ };
2146
+ var replace2 = (...args) => {
2147
+ const response = replace(...args);
2148
+ const ctx = ServerStorage.getStore();
2149
+ if (ctx) {
2150
+ ctx.redirect = response;
2151
+ }
2152
+ return response;
2153
+ };
2154
+ async function matchRSCServerRequest({
2155
+ createTemporaryReferenceSet,
2156
+ decodeReply,
2157
+ loadServerAction,
2158
+ decodeAction,
2159
+ decodeFormState,
2160
+ onError,
2161
+ request,
2162
+ routes,
2163
+ generateResponse
2164
+ }) {
2165
+ let requestUrl = new URL(request.url);
2166
+ const temporaryReferences = createTemporaryReferenceSet();
2167
+ if (isManifestRequest(requestUrl)) {
2168
+ let response2 = await generateManifestResponse(
2169
+ routes,
2170
+ request,
2171
+ generateResponse,
2172
+ temporaryReferences
2173
+ );
2174
+ return response2;
2175
+ }
2176
+ let isDataRequest = isReactServerRequest(requestUrl);
2177
+ const url = new URL(request.url);
2178
+ let routerRequest = request;
2179
+ if (isDataRequest) {
2180
+ url.pathname = url.pathname.replace(/(_root)?\.rsc$/, "");
2181
+ routerRequest = new Request(url.toString(), {
2182
+ method: request.method,
2183
+ headers: request.headers,
2184
+ body: request.body,
2185
+ signal: request.signal,
2186
+ duplex: request.body ? "half" : void 0
2187
+ });
2188
+ }
2189
+ let matches = matchRoutes(routes, url.pathname);
2190
+ if (matches) {
2191
+ await Promise.all(matches.map((m) => explodeLazyRoute(m.route)));
2192
+ }
2193
+ const leafMatch = matches?.[matches.length - 1];
2194
+ if (!isDataRequest && leafMatch && !leafMatch.route.Component && !leafMatch.route.ErrorBoundary) {
2195
+ return generateResourceResponse(
2196
+ routerRequest,
2197
+ routes,
2198
+ leafMatch.route.id,
2199
+ onError
2200
+ );
2201
+ }
2202
+ let response = await generateRenderResponse(
2203
+ routerRequest,
2204
+ routes,
2205
+ isDataRequest,
2206
+ decodeReply,
2207
+ loadServerAction,
2208
+ decodeAction,
2209
+ decodeFormState,
2210
+ onError,
2211
+ generateResponse,
2212
+ temporaryReferences
2213
+ );
2214
+ response.headers.set("X-Remix-Response", "yes");
2215
+ return response;
2216
+ }
2217
+ async function generateManifestResponse(routes, request, generateResponse, temporaryReferences) {
2218
+ let url = new URL(request.url);
2219
+ let pathnameParams = url.searchParams.getAll("p");
2220
+ let pathnames = pathnameParams.length ? pathnameParams : [url.pathname.replace(/\.manifest$/, "")];
2221
+ let routeIds = /* @__PURE__ */ new Set();
2222
+ let matchedRoutes = pathnames.flatMap((pathname) => {
2223
+ let pathnameMatches = matchRoutes(routes, pathname);
2224
+ return pathnameMatches?.map((m, i) => ({
2225
+ ...m.route,
2226
+ parentId: pathnameMatches[i - 1]?.route.id
2227
+ })) ?? [];
2228
+ }).filter((route) => {
2229
+ if (!routeIds.has(route.id)) {
2230
+ routeIds.add(route.id);
2231
+ return true;
2232
+ }
2233
+ return false;
2234
+ });
2235
+ let payload = {
2236
+ type: "manifest",
2237
+ patches: (await Promise.all([
2238
+ ...matchedRoutes.map((route) => getManifestRoute(route)),
2239
+ getAdditionalRoutePatches(pathnames, routes, Array.from(routeIds))
2240
+ ])).flat(1)
2241
+ };
2242
+ return generateResponse(
2243
+ {
2244
+ statusCode: 200,
2245
+ headers: new Headers({
2246
+ "Content-Type": "text/x-component",
2247
+ Vary: "Content-Type"
2248
+ }),
2249
+ payload
2250
+ },
2251
+ { temporaryReferences }
2252
+ );
2253
+ }
2254
+ async function processServerAction(request, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, temporaryReferences) {
2255
+ const getRevalidationRequest = () => new Request(request.url, {
2256
+ method: "GET",
2257
+ headers: request.headers,
2258
+ signal: request.signal
2259
+ });
2260
+ const isFormRequest = canDecodeWithFormData(
2261
+ request.headers.get("Content-Type")
2262
+ );
2263
+ const actionId = request.headers.get("rsc-action-id");
2264
+ if (actionId) {
2265
+ if (!decodeReply || !loadServerAction) {
2266
+ throw new Error(
2267
+ "Cannot handle enhanced server action without decodeReply and loadServerAction functions"
2268
+ );
2269
+ }
2270
+ const reply = isFormRequest ? await request.formData() : await request.text();
2271
+ const actionArgs = await decodeReply(reply, { temporaryReferences });
2272
+ const action = await loadServerAction(actionId);
2273
+ const serverAction = action.bind(null, ...actionArgs);
2274
+ let actionResult = Promise.resolve(serverAction());
2275
+ try {
2276
+ await actionResult;
2277
+ } catch (error) {
2278
+ if (isResponse(error)) {
2279
+ return error;
2280
+ }
2281
+ onError?.(error);
2282
+ }
2283
+ return {
2284
+ actionResult,
2285
+ revalidationRequest: getRevalidationRequest()
2286
+ };
2287
+ } else if (isFormRequest) {
2288
+ const formData = await request.clone().formData();
2289
+ if (Array.from(formData.keys()).some((k) => k.startsWith("$ACTION_"))) {
2290
+ if (!decodeAction) {
2291
+ throw new Error(
2292
+ "Cannot handle form actions without a decodeAction function"
2293
+ );
2294
+ }
2295
+ const action = await decodeAction(formData);
2296
+ let formState = void 0;
2297
+ try {
2298
+ const result = await action();
2299
+ formState = decodeFormState?.(result, formData);
2300
+ } catch (error) {
2301
+ if (isResponse(error)) {
2302
+ return error;
2303
+ }
2304
+ onError?.(error);
2305
+ }
2306
+ return {
2307
+ formState,
2308
+ revalidationRequest: getRevalidationRequest()
2309
+ };
2310
+ }
2311
+ }
2312
+ }
2313
+ async function generateResourceResponse(request, routes, routeId, onError) {
2314
+ let result;
2315
+ try {
2316
+ const staticHandler = createStaticHandler(routes, {
2317
+ // TODO: Support basename
2318
+ // basename
2319
+ });
2320
+ let response = await staticHandler.queryRoute(request, {
2321
+ routeId,
2322
+ // TODO: Support loadContext
2323
+ // requestContext: loadContext,
2324
+ unstable_respond: (ctx) => ctx
2325
+ });
2326
+ if (isResponse(response)) {
2327
+ result = response;
2328
+ } else {
2329
+ if (typeof response === "string") {
2330
+ result = new Response(response);
2331
+ } else {
2332
+ result = Response.json(response);
2333
+ }
2334
+ }
2335
+ } catch (error) {
2336
+ if (isResponse(error)) {
2337
+ result = error;
2338
+ } else {
2339
+ onError?.(error);
2340
+ result = new Response("Internal Server Error", {
2341
+ status: 500
2342
+ });
2343
+ }
2344
+ }
2345
+ const headers = new Headers(result.headers);
2346
+ headers.set("React-Router-Resource", "true");
2347
+ return new Response(result.body, {
2348
+ status: result.status,
2349
+ statusText: result.statusText,
2350
+ headers
2351
+ });
2352
+ }
2353
+ async function generateRenderResponse(request, routes, isDataRequest, decodeReply, loadServerAction, decodeAction, decodeFormState, onError, generateResponse, temporaryReferences) {
2354
+ let statusCode = 200;
2355
+ let url = new URL(request.url);
2356
+ let isSubmission = isMutationMethod(request.method);
2357
+ let routeIdsToLoad = !isSubmission && url.searchParams.has("_routes") ? url.searchParams.get("_routes").split(",") : null;
2358
+ const handler = createStaticHandler(routes, {
2359
+ mapRouteProperties: (r) => ({
2360
+ hasErrorBoundary: r.ErrorBoundary != null
2361
+ })
2362
+ });
2363
+ let actionResult;
2364
+ const ctx = {};
2365
+ const result = await ServerStorage.run(
2366
+ ctx,
2367
+ () => handler.query(request, {
2368
+ skipLoaderErrorBubbling: isDataRequest,
2369
+ skipRevalidation: isSubmission,
2370
+ ...routeIdsToLoad ? { filterMatchesToLoad: (m) => routeIdsToLoad.includes(m.route.id) } : null,
2371
+ async unstable_stream(_, query) {
2372
+ let formState;
2373
+ if (request.method === "POST") {
2374
+ let result2 = await processServerAction(
2375
+ request,
2376
+ decodeReply,
2377
+ loadServerAction,
2378
+ decodeAction,
2379
+ decodeFormState,
2380
+ onError,
2381
+ temporaryReferences
2382
+ );
2383
+ if (isResponse(result2)) {
2384
+ return generateRedirectResponse(
2385
+ result2,
2386
+ actionResult,
2387
+ generateResponse,
2388
+ temporaryReferences
2389
+ );
2390
+ }
2391
+ actionResult = result2?.actionResult;
2392
+ formState = result2?.formState;
2393
+ request = result2?.revalidationRequest ?? request;
2394
+ }
2395
+ if (ctx.redirect) {
2396
+ return generateRedirectResponse(
2397
+ ctx.redirect,
2398
+ actionResult,
2399
+ generateResponse,
2400
+ temporaryReferences
2401
+ );
2402
+ }
2403
+ let staticContext = await query(request);
2404
+ if (isResponse(staticContext)) {
2405
+ return generateRedirectResponse(
2406
+ staticContext,
2407
+ actionResult,
2408
+ generateResponse,
2409
+ temporaryReferences
2410
+ );
2411
+ }
2412
+ return generateStaticContextResponse(
2413
+ routes,
2414
+ generateResponse,
2415
+ statusCode,
2416
+ routeIdsToLoad,
2417
+ isDataRequest,
2418
+ isSubmission,
2419
+ actionResult,
2420
+ formState,
2421
+ staticContext,
2422
+ temporaryReferences
2423
+ );
2424
+ }
2425
+ })
2426
+ );
2427
+ if (isRedirectResponse(result)) {
2428
+ return generateRedirectResponse(
2429
+ result,
2430
+ actionResult,
2431
+ generateResponse,
2432
+ temporaryReferences
2433
+ );
2434
+ }
2435
+ invariant2(isResponse(result), "Expected a response from query");
2436
+ return result;
2437
+ }
2438
+ function generateRedirectResponse(response, actionResult, generateResponse, temporaryReferences) {
2439
+ let payload = {
2440
+ type: "redirect",
2441
+ location: response.headers.get("Location") || "",
2442
+ reload: response.headers.get("X-Remix-Reload-Document") === "true",
2443
+ replace: response.headers.get("X-Remix-Replace") === "true",
2444
+ status: response.status,
2445
+ actionResult
2446
+ };
2447
+ return generateResponse(
2448
+ {
2449
+ statusCode: SINGLE_FETCH_REDIRECT_STATUS,
2450
+ headers: new Headers({
2451
+ "Content-Type": "text/x-component",
2452
+ Vary: "Content-Type"
2453
+ }),
2454
+ payload
2455
+ },
2456
+ { temporaryReferences }
2457
+ );
2458
+ }
2459
+ async function generateStaticContextResponse(routes, generateResponse, statusCode, routeIdsToLoad, isDataRequest, isSubmission, actionResult, formState, staticContext, temporaryReferences) {
2460
+ statusCode = staticContext.statusCode ?? statusCode;
2461
+ if (staticContext.errors) {
2462
+ staticContext.errors = Object.fromEntries(
2463
+ Object.entries(staticContext.errors).map(([key, error]) => [
2464
+ key,
2465
+ isRouteErrorResponse(error) ? Object.fromEntries(Object.entries(error)) : error
2466
+ ])
2467
+ );
2468
+ }
2469
+ staticContext.matches.forEach((m) => {
2470
+ if (staticContext.loaderData[m.route.id] === void 0) {
2471
+ staticContext.loaderData[m.route.id] = null;
2472
+ }
2473
+ });
2474
+ let headers = getDocumentHeadersImpl(
2475
+ staticContext,
2476
+ (match) => match.route.headers
2477
+ );
2478
+ const baseRenderPayload = {
2479
+ type: "render",
2480
+ actionData: staticContext.actionData,
2481
+ errors: staticContext.errors,
2482
+ loaderData: staticContext.loaderData,
2483
+ location: staticContext.location,
2484
+ formState
2485
+ };
2486
+ const renderPayloadPromise = () => getRenderPayload(
2487
+ baseRenderPayload,
2488
+ routes,
2489
+ routeIdsToLoad,
2490
+ isDataRequest,
2491
+ staticContext
2492
+ );
2493
+ let payload;
2494
+ if (actionResult) {
2495
+ payload = {
2496
+ type: "action",
2497
+ actionResult,
2498
+ rerender: renderPayloadPromise()
2499
+ };
2500
+ } else if (isSubmission && isDataRequest) {
2501
+ payload = {
2502
+ ...baseRenderPayload,
2503
+ matches: [],
2504
+ patches: []
2505
+ };
2506
+ } else {
2507
+ payload = await renderPayloadPromise();
2508
+ }
2509
+ return generateResponse(
2510
+ {
2511
+ statusCode,
2512
+ headers,
2513
+ payload
2514
+ },
2515
+ { temporaryReferences }
2516
+ );
2517
+ }
2518
+ async function getRenderPayload(baseRenderPayload, routes, routeIdsToLoad, isDataRequest, staticContext) {
2519
+ let deepestRenderedRouteIdx = staticContext.matches.length - 1;
2520
+ let parentIds = {};
2521
+ staticContext.matches.forEach((m, i) => {
2522
+ if (i > 0) {
2523
+ parentIds[m.route.id] = staticContext.matches[i - 1].route.id;
2524
+ }
2525
+ if (staticContext.errors && m.route.id in staticContext.errors && deepestRenderedRouteIdx > i) {
2526
+ deepestRenderedRouteIdx = i;
2527
+ }
2528
+ });
2529
+ let matchesPromise = Promise.all(
2530
+ staticContext.matches.map((match, i) => {
2531
+ let shouldRenderComponent = i <= deepestRenderedRouteIdx && (!routeIdsToLoad || routeIdsToLoad.includes(match.route.id)) && (!staticContext.errors || !(match.route.id in staticContext.errors));
2532
+ return getRSCRouteMatch(
2533
+ staticContext,
2534
+ match,
2535
+ shouldRenderComponent,
2536
+ parentIds[match.route.id]
2537
+ );
2538
+ })
2539
+ );
2540
+ let patchesPromise = !isDataRequest ? getAdditionalRoutePatches(
2541
+ [staticContext.location.pathname],
2542
+ routes,
2543
+ staticContext.matches.map((m) => m.route.id)
2544
+ ) : void 0;
2545
+ let [matches, patches] = await Promise.all([matchesPromise, patchesPromise]);
2546
+ return {
2547
+ ...baseRenderPayload,
2548
+ matches,
2549
+ patches
2550
+ };
2551
+ }
2552
+ async function getRSCRouteMatch(staticContext, match, shouldRenderComponent, parentId) {
2553
+ await explodeLazyRoute(match.route);
2554
+ const Layout = match.route.Layout || React2__namespace.Fragment;
2555
+ const Component = match.route.Component;
2556
+ const ErrorBoundary = match.route.ErrorBoundary;
2557
+ const HydrateFallback = match.route.HydrateFallback;
2558
+ const loaderData = staticContext.loaderData[match.route.id];
2559
+ const actionData = staticContext.actionData?.[match.route.id];
2560
+ const params = match.params;
2561
+ const element = Component && shouldRenderComponent ? React2__namespace.createElement(
2562
+ Layout,
2563
+ null,
2564
+ React2__namespace.createElement(Component, {
2565
+ loaderData,
2566
+ actionData,
2567
+ params,
2568
+ matches: staticContext.matches.map(
2569
+ (match2) => convertRouteMatchToUiMatch(match2, staticContext.loaderData)
2570
+ )
2571
+ })
2572
+ ) : (
2573
+ // TODO: Render outet instead?
2574
+ void 0
2575
+ );
2576
+ let error = void 0;
2577
+ if (ErrorBoundary && staticContext.errors) {
2578
+ for (const match2 of [...staticContext.matches].reverse()) {
2579
+ if (match2.route.id in staticContext.errors) {
2580
+ error = staticContext.errors[match2.route.id];
2581
+ break;
2582
+ }
2583
+ }
2584
+ }
2585
+ const errorElement = ErrorBoundary ? React2__namespace.createElement(
2586
+ Layout,
2587
+ null,
2588
+ React2__namespace.createElement(ErrorBoundary, {
2589
+ loaderData,
2590
+ actionData,
2591
+ params,
2592
+ error
2593
+ })
2594
+ ) : void 0;
2595
+ const hydrateFallbackElement = HydrateFallback ? React2__namespace.createElement(
2596
+ Layout,
2597
+ null,
2598
+ React2__namespace.createElement(HydrateFallback, {
2599
+ loaderData,
2600
+ actionData,
2601
+ params
2602
+ })
2603
+ ) : match.route.id === "root" ? (
2604
+ // FIXME: This should use the `RemixRootDefaultErrorBoundary` but that
2605
+ // currently uses a hook internally so it fails during RSC. Restructure
2606
+ // so it can be used safely in an RSC render pass.
2607
+ React2__namespace.createElement("p", null, "Loading!")
2608
+ ) : void 0;
2609
+ return {
2610
+ clientAction: match.route.clientAction,
2611
+ clientLoader: match.route.clientLoader,
2612
+ element,
2613
+ errorElement,
2614
+ handle: match.route.handle,
2615
+ hasAction: !!match.route.action,
2616
+ hasComponent: !!Component,
2617
+ hasErrorBoundary: !!ErrorBoundary,
2618
+ hasLoader: !!match.route.loader,
2619
+ hydrateFallbackElement,
2620
+ id: match.route.id,
2621
+ index: match.route.index,
2622
+ links: match.route.links,
2623
+ meta: match.route.meta,
2624
+ params,
2625
+ parentId,
2626
+ path: match.route.path,
2627
+ pathname: match.pathname,
2628
+ pathnameBase: match.pathnameBase,
2629
+ shouldRevalidate: match.route.shouldRevalidate
2630
+ };
2631
+ }
2632
+ async function getManifestRoute(route) {
2633
+ await explodeLazyRoute(route);
2634
+ const Layout = route.Layout || React2__namespace.Fragment;
2635
+ const errorElement = route.ErrorBoundary ? React2__namespace.createElement(
2636
+ Layout,
2637
+ null,
2638
+ React2__namespace.createElement(route.ErrorBoundary)
2639
+ ) : void 0;
2640
+ return {
2641
+ clientAction: route.clientAction,
2642
+ clientLoader: route.clientLoader,
2643
+ handle: route.handle,
2644
+ hasAction: !!route.action,
2645
+ hasComponent: !!route.Component,
2646
+ hasErrorBoundary: !!route.ErrorBoundary,
2647
+ errorElement,
2648
+ hasLoader: !!route.loader,
2649
+ id: route.id,
2650
+ parentId: route.parentId,
2651
+ path: route.path,
2652
+ index: "index" in route ? route.index : void 0,
2653
+ links: route.links,
2654
+ meta: route.meta
2655
+ };
2656
+ }
2657
+ async function explodeLazyRoute(route) {
2658
+ if ("lazy" in route && route.lazy) {
2659
+ let {
2660
+ default: lazyDefaultExport,
2661
+ Component: lazyComponentExport,
2662
+ ...lazyProperties
2663
+ } = await route.lazy();
2664
+ let Component = lazyComponentExport || lazyDefaultExport;
2665
+ if (Component && !route.Component) {
2666
+ route.Component = Component;
2667
+ }
2668
+ for (let [k, v] of Object.entries(lazyProperties)) {
2669
+ if (k !== "id" && k !== "path" && k !== "index" && k !== "children" && route[k] == null) {
2670
+ route[k] = v;
2671
+ }
2672
+ }
2673
+ route.lazy = void 0;
2674
+ }
2675
+ }
2676
+ async function getAdditionalRoutePatches(pathnames, routes, matchedRouteIds) {
2677
+ let patchRouteMatches = /* @__PURE__ */ new Map();
2678
+ let matchedPaths = /* @__PURE__ */ new Set();
2679
+ for (const pathname of pathnames) {
2680
+ let segments = pathname.split("/").filter(Boolean);
2681
+ let paths = ["/"];
2682
+ segments.pop();
2683
+ while (segments.length > 0) {
2684
+ paths.push(`/${segments.join("/")}`);
2685
+ segments.pop();
2686
+ }
2687
+ paths.forEach((path) => {
2688
+ if (matchedPaths.has(path)) {
2689
+ return;
2690
+ }
2691
+ matchedPaths.add(path);
2692
+ let matches = matchRoutes(routes, path) || [];
2693
+ matches.forEach((m, i) => {
2694
+ if (patchRouteMatches.get(m.route.id)) {
2695
+ return;
2696
+ }
2697
+ patchRouteMatches.set(m.route.id, {
2698
+ ...m.route,
2699
+ parentId: matches[i - 1]?.route.id
2700
+ });
2701
+ });
2702
+ });
2703
+ }
2704
+ let patches = await Promise.all(
2705
+ [...patchRouteMatches.values()].filter((route) => !matchedRouteIds.some((id) => id === route.id)).map((route) => getManifestRoute(route))
2706
+ );
2707
+ return patches;
2708
+ }
2709
+ function isReactServerRequest(url) {
2710
+ return url.pathname.endsWith(".rsc");
2711
+ }
2712
+ function isManifestRequest(url) {
2713
+ return url.pathname.endsWith(".manifest");
2714
+ }
2715
+ function canDecodeWithFormData(contentType) {
2716
+ if (!contentType) return false;
2717
+ return contentType.match(/\bapplication\/x-www-form-urlencoded\b/) || contentType.match(/\bmultipart\/form-data\b/);
2718
+ }
2719
+
2720
+ // lib/server-runtime/crypto.ts
2721
+ var encoder = /* @__PURE__ */ new TextEncoder();
2722
+ var sign = async (value, secret) => {
2723
+ let data2 = encoder.encode(value);
2724
+ let key = await createKey2(secret, ["sign"]);
2725
+ let signature = await crypto.subtle.sign("HMAC", key, data2);
2726
+ let hash = btoa(String.fromCharCode(...new Uint8Array(signature))).replace(
2727
+ /=+$/,
2728
+ ""
2729
+ );
2730
+ return value + "." + hash;
2731
+ };
2732
+ var unsign = async (cookie, secret) => {
2733
+ let index = cookie.lastIndexOf(".");
2734
+ let value = cookie.slice(0, index);
2735
+ let hash = cookie.slice(index + 1);
2736
+ let data2 = encoder.encode(value);
2737
+ let key = await createKey2(secret, ["verify"]);
2738
+ try {
2739
+ let signature = byteStringToUint8Array(atob(hash));
2740
+ let valid = await crypto.subtle.verify("HMAC", key, signature, data2);
2741
+ return valid ? value : false;
2742
+ } catch (error) {
2743
+ return false;
2744
+ }
2745
+ };
2746
+ var createKey2 = async (secret, usages) => crypto.subtle.importKey(
2747
+ "raw",
2748
+ encoder.encode(secret),
2749
+ { name: "HMAC", hash: "SHA-256" },
2750
+ false,
2751
+ usages
2752
+ );
2753
+ function byteStringToUint8Array(byteString) {
2754
+ let array = new Uint8Array(byteString.length);
2755
+ for (let i = 0; i < byteString.length; i++) {
2756
+ array[i] = byteString.charCodeAt(i);
2757
+ }
2758
+ return array;
2759
+ }
2760
+
2761
+ // lib/server-runtime/warnings.ts
2762
+ var alreadyWarned = {};
2763
+ function warnOnce(condition, message) {
2764
+ if (!condition && !alreadyWarned[message]) {
2765
+ alreadyWarned[message] = true;
2766
+ console.warn(message);
2767
+ }
2768
+ }
2769
+
2770
+ // lib/server-runtime/cookies.ts
2771
+ var createCookie = (name, cookieOptions = {}) => {
2772
+ let { secrets = [], ...options } = {
2773
+ path: "/",
2774
+ sameSite: "lax",
2775
+ ...cookieOptions
2776
+ };
2777
+ warnOnceAboutExpiresCookie(name, options.expires);
2778
+ return {
2779
+ get name() {
2780
+ return name;
2781
+ },
2782
+ get isSigned() {
2783
+ return secrets.length > 0;
2784
+ },
2785
+ get expires() {
2786
+ return typeof options.maxAge !== "undefined" ? new Date(Date.now() + options.maxAge * 1e3) : options.expires;
2787
+ },
2788
+ async parse(cookieHeader, parseOptions) {
2789
+ if (!cookieHeader) return null;
2790
+ let cookies = cookie.parse(cookieHeader, { ...options, ...parseOptions });
2791
+ if (name in cookies) {
2792
+ let value = cookies[name];
2793
+ if (typeof value === "string" && value !== "") {
2794
+ let decoded = await decodeCookieValue(value, secrets);
2795
+ return decoded;
2796
+ } else {
2797
+ return "";
2798
+ }
2799
+ } else {
2800
+ return null;
2801
+ }
2802
+ },
2803
+ async serialize(value, serializeOptions) {
2804
+ return cookie.serialize(
2805
+ name,
2806
+ value === "" ? "" : await encodeCookieValue(value, secrets),
2807
+ {
2808
+ ...options,
2809
+ ...serializeOptions
2810
+ }
2811
+ );
2812
+ }
2813
+ };
2814
+ };
2815
+ var isCookie = (object) => {
2816
+ return object != null && typeof object.name === "string" && typeof object.isSigned === "boolean" && typeof object.parse === "function" && typeof object.serialize === "function";
2817
+ };
2818
+ async function encodeCookieValue(value, secrets) {
2819
+ let encoded = encodeData(value);
2820
+ if (secrets.length > 0) {
2821
+ encoded = await sign(encoded, secrets[0]);
2822
+ }
2823
+ return encoded;
2824
+ }
2825
+ async function decodeCookieValue(value, secrets) {
2826
+ if (secrets.length > 0) {
2827
+ for (let secret of secrets) {
2828
+ let unsignedValue = await unsign(value, secret);
2829
+ if (unsignedValue !== false) {
2830
+ return decodeData(unsignedValue);
2831
+ }
2832
+ }
2833
+ return null;
2834
+ }
2835
+ return decodeData(value);
2836
+ }
2837
+ function encodeData(value) {
2838
+ return btoa(myUnescape(encodeURIComponent(JSON.stringify(value))));
2839
+ }
2840
+ function decodeData(value) {
2841
+ try {
2842
+ return JSON.parse(decodeURIComponent(myEscape(atob(value))));
2843
+ } catch (error) {
2844
+ return {};
2845
+ }
2846
+ }
2847
+ function myEscape(value) {
2848
+ let str = value.toString();
2849
+ let result = "";
2850
+ let index = 0;
2851
+ let chr, code;
2852
+ while (index < str.length) {
2853
+ chr = str.charAt(index++);
2854
+ if (/[\w*+\-./@]/.exec(chr)) {
2855
+ result += chr;
2856
+ } else {
2857
+ code = chr.charCodeAt(0);
2858
+ if (code < 256) {
2859
+ result += "%" + hex(code, 2);
2860
+ } else {
2861
+ result += "%u" + hex(code, 4).toUpperCase();
2862
+ }
2863
+ }
2864
+ }
2865
+ return result;
2866
+ }
2867
+ function hex(code, length) {
2868
+ let result = code.toString(16);
2869
+ while (result.length < length) result = "0" + result;
2870
+ return result;
2871
+ }
2872
+ function myUnescape(value) {
2873
+ let str = value.toString();
2874
+ let result = "";
2875
+ let index = 0;
2876
+ let chr, part;
2877
+ while (index < str.length) {
2878
+ chr = str.charAt(index++);
2879
+ if (chr === "%") {
2880
+ if (str.charAt(index) === "u") {
2881
+ part = str.slice(index + 1, index + 5);
2882
+ if (/^[\da-f]{4}$/i.exec(part)) {
2883
+ result += String.fromCharCode(parseInt(part, 16));
2884
+ index += 5;
2885
+ continue;
2886
+ }
2887
+ } else {
2888
+ part = str.slice(index, index + 2);
2889
+ if (/^[\da-f]{2}$/i.exec(part)) {
2890
+ result += String.fromCharCode(parseInt(part, 16));
2891
+ index += 2;
2892
+ continue;
2893
+ }
2894
+ }
2895
+ }
2896
+ result += chr;
2897
+ }
2898
+ return result;
2899
+ }
2900
+ function warnOnceAboutExpiresCookie(name, expires) {
2901
+ warnOnce(
2902
+ !expires,
2903
+ `The "${name}" cookie has an "expires" property set. This will cause the expires value to not be updated when the session is committed. Instead, you should set the expires value when serializing the cookie. You can use \`commitSession(session, { expires })\` if using a session storage object, or \`cookie.serialize("value", { expires })\` if you're using the cookie directly.`
2904
+ );
2905
+ }
2906
+
2907
+ // lib/server-runtime/sessions.ts
2908
+ function flash(name) {
2909
+ return `__flash_${name}__`;
2910
+ }
2911
+ var createSession = (initialData = {}, id = "") => {
2912
+ let map = new Map(Object.entries(initialData));
2913
+ return {
2914
+ get id() {
2915
+ return id;
2916
+ },
2917
+ get data() {
2918
+ return Object.fromEntries(map);
2919
+ },
2920
+ has(name) {
2921
+ return map.has(name) || map.has(flash(name));
2922
+ },
2923
+ get(name) {
2924
+ if (map.has(name)) return map.get(name);
2925
+ let flashName = flash(name);
2926
+ if (map.has(flashName)) {
2927
+ let value = map.get(flashName);
2928
+ map.delete(flashName);
2929
+ return value;
2930
+ }
2931
+ return void 0;
2932
+ },
2933
+ set(name, value) {
2934
+ map.set(name, value);
2935
+ },
2936
+ flash(name, value) {
2937
+ map.set(flash(name), value);
2938
+ },
2939
+ unset(name) {
2940
+ map.delete(name);
2941
+ }
2942
+ };
2943
+ };
2944
+ var isSession = (object) => {
2945
+ return object != null && typeof object.id === "string" && typeof object.data !== "undefined" && typeof object.has === "function" && typeof object.get === "function" && typeof object.set === "function" && typeof object.flash === "function" && typeof object.unset === "function";
2946
+ };
2947
+ function createSessionStorage({
2948
+ cookie: cookieArg,
2949
+ createData,
2950
+ readData,
2951
+ updateData,
2952
+ deleteData
2953
+ }) {
2954
+ let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
2955
+ warnOnceAboutSigningSessionCookie(cookie);
2956
+ return {
2957
+ async getSession(cookieHeader, options) {
2958
+ let id = cookieHeader && await cookie.parse(cookieHeader, options);
2959
+ let data2 = id && await readData(id);
2960
+ return createSession(data2 || {}, id || "");
2961
+ },
2962
+ async commitSession(session, options) {
2963
+ let { id, data: data2 } = session;
2964
+ let expires = options?.maxAge != null ? new Date(Date.now() + options.maxAge * 1e3) : options?.expires != null ? options.expires : cookie.expires;
2965
+ if (id) {
2966
+ await updateData(id, data2, expires);
2967
+ } else {
2968
+ id = await createData(data2, expires);
2969
+ }
2970
+ return cookie.serialize(id, options);
2971
+ },
2972
+ async destroySession(session, options) {
2973
+ await deleteData(session.id);
2974
+ return cookie.serialize("", {
2975
+ ...options,
2976
+ maxAge: void 0,
2977
+ expires: /* @__PURE__ */ new Date(0)
2978
+ });
2979
+ }
2980
+ };
2981
+ }
2982
+ function warnOnceAboutSigningSessionCookie(cookie) {
2983
+ warnOnce(
2984
+ cookie.isSigned,
2985
+ `The "${cookie.name}" cookie is not signed, but session cookies should be signed to prevent tampering on the client before they are sent back to the server. See https://reactrouter.com/explanation/sessions-and-cookies#signing-cookies for more information.`
2986
+ );
2987
+ }
2988
+
2989
+ // lib/server-runtime/sessions/cookieStorage.ts
2990
+ function createCookieSessionStorage({ cookie: cookieArg } = {}) {
2991
+ let cookie = isCookie(cookieArg) ? cookieArg : createCookie(cookieArg?.name || "__session", cookieArg);
2992
+ warnOnceAboutSigningSessionCookie(cookie);
2993
+ return {
2994
+ async getSession(cookieHeader, options) {
2995
+ return createSession(
2996
+ cookieHeader && await cookie.parse(cookieHeader, options) || {}
2997
+ );
2998
+ },
2999
+ async commitSession(session, options) {
3000
+ let serializedCookie = await cookie.serialize(session.data, options);
3001
+ if (serializedCookie.length > 4096) {
3002
+ throw new Error(
3003
+ "Cookie length will exceed browser maximum. Length: " + serializedCookie.length
3004
+ );
3005
+ }
3006
+ return serializedCookie;
3007
+ },
3008
+ async destroySession(_session, options) {
3009
+ return cookie.serialize("", {
3010
+ ...options,
3011
+ maxAge: void 0,
3012
+ expires: /* @__PURE__ */ new Date(0)
3013
+ });
3014
+ }
3015
+ };
3016
+ }
3017
+
3018
+ // lib/server-runtime/sessions/memoryStorage.ts
3019
+ function createMemorySessionStorage({ cookie } = {}) {
3020
+ let map = /* @__PURE__ */ new Map();
3021
+ return createSessionStorage({
3022
+ cookie,
3023
+ async createData(data2, expires) {
3024
+ let id = Math.random().toString(36).substring(2, 10);
3025
+ map.set(id, { data: data2, expires });
3026
+ return id;
3027
+ },
3028
+ async readData(id) {
3029
+ if (map.has(id)) {
3030
+ let { data: data2, expires } = map.get(id);
3031
+ if (!expires || expires > /* @__PURE__ */ new Date()) {
3032
+ return data2;
3033
+ }
3034
+ if (expires) map.delete(id);
3035
+ }
3036
+ return null;
3037
+ },
3038
+ async updateData(id, data2, expires) {
3039
+ map.set(id, { data: data2, expires });
3040
+ },
3041
+ async deleteData(id) {
3042
+ map.delete(id);
3043
+ }
3044
+ });
3045
+ }
3046
+
3047
+ Object.defineProperty(exports, "Await", {
3048
+ enumerable: true,
3049
+ get: function () { return reactServerClient.Await; }
3050
+ });
3051
+ Object.defineProperty(exports, "BrowserRouter", {
3052
+ enumerable: true,
3053
+ get: function () { return reactServerClient.BrowserRouter; }
3054
+ });
3055
+ Object.defineProperty(exports, "Form", {
3056
+ enumerable: true,
3057
+ get: function () { return reactServerClient.Form; }
3058
+ });
3059
+ Object.defineProperty(exports, "HashRouter", {
3060
+ enumerable: true,
3061
+ get: function () { return reactServerClient.HashRouter; }
3062
+ });
3063
+ Object.defineProperty(exports, "Link", {
3064
+ enumerable: true,
3065
+ get: function () { return reactServerClient.Link; }
3066
+ });
3067
+ Object.defineProperty(exports, "Links", {
3068
+ enumerable: true,
3069
+ get: function () { return reactServerClient.Links; }
3070
+ });
3071
+ Object.defineProperty(exports, "MemoryRouter", {
3072
+ enumerable: true,
3073
+ get: function () { return reactServerClient.MemoryRouter; }
3074
+ });
3075
+ Object.defineProperty(exports, "Meta", {
3076
+ enumerable: true,
3077
+ get: function () { return reactServerClient.Meta; }
3078
+ });
3079
+ Object.defineProperty(exports, "NavLink", {
3080
+ enumerable: true,
3081
+ get: function () { return reactServerClient.NavLink; }
3082
+ });
3083
+ Object.defineProperty(exports, "Navigate", {
3084
+ enumerable: true,
3085
+ get: function () { return reactServerClient.Navigate; }
3086
+ });
3087
+ Object.defineProperty(exports, "Outlet", {
3088
+ enumerable: true,
3089
+ get: function () { return reactServerClient.Outlet; }
3090
+ });
3091
+ Object.defineProperty(exports, "Route", {
3092
+ enumerable: true,
3093
+ get: function () { return reactServerClient.Route; }
3094
+ });
3095
+ Object.defineProperty(exports, "Router", {
3096
+ enumerable: true,
3097
+ get: function () { return reactServerClient.Router; }
3098
+ });
3099
+ Object.defineProperty(exports, "RouterProvider", {
3100
+ enumerable: true,
3101
+ get: function () { return reactServerClient.RouterProvider; }
3102
+ });
3103
+ Object.defineProperty(exports, "Routes", {
3104
+ enumerable: true,
3105
+ get: function () { return reactServerClient.Routes; }
3106
+ });
3107
+ Object.defineProperty(exports, "ScrollRestoration", {
3108
+ enumerable: true,
3109
+ get: function () { return reactServerClient.ScrollRestoration; }
3110
+ });
3111
+ Object.defineProperty(exports, "StaticRouter", {
3112
+ enumerable: true,
3113
+ get: function () { return reactServerClient.StaticRouter; }
3114
+ });
3115
+ Object.defineProperty(exports, "StaticRouterProvider", {
3116
+ enumerable: true,
3117
+ get: function () { return reactServerClient.StaticRouterProvider; }
3118
+ });
3119
+ Object.defineProperty(exports, "unstable_HistoryRouter", {
3120
+ enumerable: true,
3121
+ get: function () { return reactServerClient.unstable_HistoryRouter; }
3122
+ });
3123
+ exports.createCookie = createCookie;
3124
+ exports.createCookieSessionStorage = createCookieSessionStorage;
3125
+ exports.createMemorySessionStorage = createMemorySessionStorage;
3126
+ exports.createSession = createSession;
3127
+ exports.createSessionStorage = createSessionStorage;
3128
+ exports.createStaticHandler = createStaticHandler;
3129
+ exports.data = data;
3130
+ exports.isCookie = isCookie;
3131
+ exports.isSession = isSession;
3132
+ exports.matchRoutes = matchRoutes;
3133
+ exports.redirect = redirect2;
3134
+ exports.redirectDocument = redirectDocument2;
3135
+ exports.replace = replace2;
3136
+ exports.unstable_createContext = unstable_createContext;
3137
+ exports.unstable_matchRSCServerRequest = matchRSCServerRequest;