@remix-run/router 0.0.0-experimental-48058118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/router.js ADDED
@@ -0,0 +1,4117 @@
1
+ /**
2
+ * @remix-run/router v0.0.0-experimental-48058118
3
+ *
4
+ * Copyright (c) Remix Software Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE.md file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ function _extends() {
12
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
13
+ for (var i = 1; i < arguments.length; i++) {
14
+ var source = arguments[i];
15
+
16
+ for (var key in source) {
17
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
18
+ target[key] = source[key];
19
+ }
20
+ }
21
+ }
22
+
23
+ return target;
24
+ };
25
+ return _extends.apply(this, arguments);
26
+ }
27
+
28
+ ////////////////////////////////////////////////////////////////////////////////
29
+ //#region Types and Constants
30
+ ////////////////////////////////////////////////////////////////////////////////
31
+
32
+ /**
33
+ * Actions represent the type of change to a location value.
34
+ */
35
+ var Action;
36
+
37
+ (function (Action) {
38
+ /**
39
+ * A POP indicates a change to an arbitrary index in the history stack, such
40
+ * as a back or forward navigation. It does not describe the direction of the
41
+ * navigation, only that the current index changed.
42
+ *
43
+ * Note: This is the default action for newly created history objects.
44
+ */
45
+ Action["Pop"] = "POP";
46
+ /**
47
+ * A PUSH indicates a new entry being added to the history stack, such as when
48
+ * a link is clicked and a new page loads. When this happens, all subsequent
49
+ * entries in the stack are lost.
50
+ */
51
+
52
+ Action["Push"] = "PUSH";
53
+ /**
54
+ * A REPLACE indicates the entry at the current index in the history stack
55
+ * being replaced by a new one.
56
+ */
57
+
58
+ Action["Replace"] = "REPLACE";
59
+ })(Action || (Action = {}));
60
+
61
+ const PopStateEventType = "popstate";
62
+ /**
63
+ * Memory history stores the current location in memory. It is designed for use
64
+ * in stateful non-browser environments like tests and React Native.
65
+ */
66
+
67
+ function createMemoryHistory(options) {
68
+ if (options === void 0) {
69
+ options = {};
70
+ }
71
+
72
+ let {
73
+ initialEntries = ["/"],
74
+ initialIndex,
75
+ v5Compat = false
76
+ } = options;
77
+ let entries; // Declare so we can access from createMemoryLocation
78
+
79
+ entries = initialEntries.map((entry, index) => createMemoryLocation(entry, typeof entry === "string" ? null : entry.state, index === 0 ? "default" : undefined));
80
+ let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);
81
+ let action = Action.Pop;
82
+ let listener = null;
83
+
84
+ function clampIndex(n) {
85
+ return Math.min(Math.max(n, 0), entries.length - 1);
86
+ }
87
+
88
+ function getCurrentLocation() {
89
+ return entries[index];
90
+ }
91
+
92
+ function createMemoryLocation(to, state, key) {
93
+ if (state === void 0) {
94
+ state = null;
95
+ }
96
+
97
+ let location = createLocation(entries ? getCurrentLocation().pathname : "/", to, state, key);
98
+ warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in memory history: " + JSON.stringify(to));
99
+ return location;
100
+ }
101
+
102
+ function createHref(to) {
103
+ return typeof to === "string" ? to : createPath(to);
104
+ }
105
+
106
+ let history = {
107
+ get index() {
108
+ return index;
109
+ },
110
+
111
+ get action() {
112
+ return action;
113
+ },
114
+
115
+ get location() {
116
+ return getCurrentLocation();
117
+ },
118
+
119
+ createHref,
120
+
121
+ createURL(to) {
122
+ return new URL(createHref(to), "http://localhost");
123
+ },
124
+
125
+ encodeLocation(to) {
126
+ let path = typeof to === "string" ? parsePath(to) : to;
127
+ return {
128
+ pathname: path.pathname || "",
129
+ search: path.search || "",
130
+ hash: path.hash || ""
131
+ };
132
+ },
133
+
134
+ push(to, state) {
135
+ action = Action.Push;
136
+ let nextLocation = createMemoryLocation(to, state);
137
+ index += 1;
138
+ entries.splice(index, entries.length, nextLocation);
139
+
140
+ if (v5Compat && listener) {
141
+ listener({
142
+ action,
143
+ location: nextLocation,
144
+ delta: 1
145
+ });
146
+ }
147
+ },
148
+
149
+ replace(to, state) {
150
+ action = Action.Replace;
151
+ let nextLocation = createMemoryLocation(to, state);
152
+ entries[index] = nextLocation;
153
+
154
+ if (v5Compat && listener) {
155
+ listener({
156
+ action,
157
+ location: nextLocation,
158
+ delta: 0
159
+ });
160
+ }
161
+ },
162
+
163
+ go(delta) {
164
+ action = Action.Pop;
165
+ let nextIndex = clampIndex(index + delta);
166
+ let nextLocation = entries[nextIndex];
167
+ index = nextIndex;
168
+
169
+ if (listener) {
170
+ listener({
171
+ action,
172
+ location: nextLocation,
173
+ delta
174
+ });
175
+ }
176
+ },
177
+
178
+ listen(fn) {
179
+ listener = fn;
180
+ return () => {
181
+ listener = null;
182
+ };
183
+ }
184
+
185
+ };
186
+ return history;
187
+ }
188
+ /**
189
+ * Browser history stores the location in regular URLs. This is the standard for
190
+ * most web apps, but it requires some configuration on the server to ensure you
191
+ * serve the same app at multiple URLs.
192
+ *
193
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory
194
+ */
195
+
196
+ function createBrowserHistory(options) {
197
+ if (options === void 0) {
198
+ options = {};
199
+ }
200
+
201
+ function createBrowserLocation(window, globalHistory) {
202
+ let {
203
+ pathname,
204
+ search,
205
+ hash
206
+ } = window.location;
207
+ return createLocation("", {
208
+ pathname,
209
+ search,
210
+ hash
211
+ }, // state defaults to `null` because `window.history.state` does
212
+ globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
213
+ }
214
+
215
+ function createBrowserHref(window, to) {
216
+ return typeof to === "string" ? to : createPath(to);
217
+ }
218
+
219
+ return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);
220
+ }
221
+ /**
222
+ * Hash history stores the location in window.location.hash. This makes it ideal
223
+ * for situations where you don't want to send the location to the server for
224
+ * some reason, either because you do cannot configure it or the URL space is
225
+ * reserved for something else.
226
+ *
227
+ * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory
228
+ */
229
+
230
+ function createHashHistory(options) {
231
+ if (options === void 0) {
232
+ options = {};
233
+ }
234
+
235
+ function createHashLocation(window, globalHistory) {
236
+ let {
237
+ pathname = "/",
238
+ search = "",
239
+ hash = ""
240
+ } = parsePath(window.location.hash.substr(1));
241
+ return createLocation("", {
242
+ pathname,
243
+ search,
244
+ hash
245
+ }, // state defaults to `null` because `window.history.state` does
246
+ globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || "default");
247
+ }
248
+
249
+ function createHashHref(window, to) {
250
+ let base = window.document.querySelector("base");
251
+ let href = "";
252
+
253
+ if (base && base.getAttribute("href")) {
254
+ let url = window.location.href;
255
+ let hashIndex = url.indexOf("#");
256
+ href = hashIndex === -1 ? url : url.slice(0, hashIndex);
257
+ }
258
+
259
+ return href + "#" + (typeof to === "string" ? to : createPath(to));
260
+ }
261
+
262
+ function validateHashLocation(location, to) {
263
+ warning$1(location.pathname.charAt(0) === "/", "relative pathnames are not supported in hash history.push(" + JSON.stringify(to) + ")");
264
+ }
265
+
266
+ return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);
267
+ }
268
+ function invariant(value, message) {
269
+ if (value === false || value === null || typeof value === "undefined") {
270
+ throw new Error(message);
271
+ }
272
+ }
273
+
274
+ function warning$1(cond, message) {
275
+ if (!cond) {
276
+ // eslint-disable-next-line no-console
277
+ if (typeof console !== "undefined") console.warn(message);
278
+
279
+ try {
280
+ // Welcome to debugging history!
281
+ //
282
+ // This error is thrown as a convenience so you can more easily
283
+ // find the source for a warning that appears in the console by
284
+ // enabling "pause on exceptions" in your JavaScript debugger.
285
+ throw new Error(message); // eslint-disable-next-line no-empty
286
+ } catch (e) {}
287
+ }
288
+ }
289
+
290
+ function createKey() {
291
+ return Math.random().toString(36).substr(2, 8);
292
+ }
293
+ /**
294
+ * For browser-based histories, we combine the state and key into an object
295
+ */
296
+
297
+
298
+ function getHistoryState(location, index) {
299
+ return {
300
+ usr: location.state,
301
+ key: location.key,
302
+ idx: index
303
+ };
304
+ }
305
+ /**
306
+ * Creates a Location object with a unique key from the given Path
307
+ */
308
+
309
+
310
+ function createLocation(current, to, state, key) {
311
+ if (state === void 0) {
312
+ state = null;
313
+ }
314
+
315
+ let location = _extends({
316
+ pathname: typeof current === "string" ? current : current.pathname,
317
+ search: "",
318
+ hash: ""
319
+ }, typeof to === "string" ? parsePath(to) : to, {
320
+ state,
321
+ // TODO: This could be cleaned up. push/replace should probably just take
322
+ // full Locations now and avoid the need to run through this flow at all
323
+ // But that's a pretty big refactor to the current test suite so going to
324
+ // keep as is for the time being and just let any incoming keys take precedence
325
+ key: to && to.key || key || createKey()
326
+ });
327
+
328
+ return location;
329
+ }
330
+ /**
331
+ * Creates a string URL path from the given pathname, search, and hash components.
332
+ */
333
+
334
+ function createPath(_ref) {
335
+ let {
336
+ pathname = "/",
337
+ search = "",
338
+ hash = ""
339
+ } = _ref;
340
+ if (search && search !== "?") pathname += search.charAt(0) === "?" ? search : "?" + search;
341
+ if (hash && hash !== "#") pathname += hash.charAt(0) === "#" ? hash : "#" + hash;
342
+ return pathname;
343
+ }
344
+ /**
345
+ * Parses a string URL path into its separate pathname, search, and hash components.
346
+ */
347
+
348
+ function parsePath(path) {
349
+ let parsedPath = {};
350
+
351
+ if (path) {
352
+ let hashIndex = path.indexOf("#");
353
+
354
+ if (hashIndex >= 0) {
355
+ parsedPath.hash = path.substr(hashIndex);
356
+ path = path.substr(0, hashIndex);
357
+ }
358
+
359
+ let searchIndex = path.indexOf("?");
360
+
361
+ if (searchIndex >= 0) {
362
+ parsedPath.search = path.substr(searchIndex);
363
+ path = path.substr(0, searchIndex);
364
+ }
365
+
366
+ if (path) {
367
+ parsedPath.pathname = path;
368
+ }
369
+ }
370
+
371
+ return parsedPath;
372
+ }
373
+
374
+ function getUrlBasedHistory(getLocation, createHref, validateLocation, options) {
375
+ if (options === void 0) {
376
+ options = {};
377
+ }
378
+
379
+ let {
380
+ window = document.defaultView,
381
+ v5Compat = false
382
+ } = options;
383
+ let globalHistory = window.history;
384
+ let action = Action.Pop;
385
+ let listener = null;
386
+ let index = getIndex(); // Index should only be null when we initialize. If not, it's because the
387
+ // user called history.pushState or history.replaceState directly, in which
388
+ // case we should log a warning as it will result in bugs.
389
+
390
+ if (index == null) {
391
+ index = 0;
392
+ globalHistory.replaceState(_extends({}, globalHistory.state, {
393
+ idx: index
394
+ }), "");
395
+ }
396
+
397
+ function getIndex() {
398
+ let state = globalHistory.state || {
399
+ idx: null
400
+ };
401
+ return state.idx;
402
+ }
403
+
404
+ function handlePop() {
405
+ action = Action.Pop;
406
+ let nextIndex = getIndex();
407
+ let delta = nextIndex == null ? null : nextIndex - index;
408
+ index = nextIndex;
409
+
410
+ if (listener) {
411
+ listener({
412
+ action,
413
+ location: history.location,
414
+ delta
415
+ });
416
+ }
417
+ }
418
+
419
+ function push(to, state) {
420
+ action = Action.Push;
421
+ let location = createLocation(history.location, to, state);
422
+ if (validateLocation) validateLocation(location, to);
423
+ index = getIndex() + 1;
424
+ let historyState = getHistoryState(location, index);
425
+ let url = history.createHref(location); // try...catch because iOS limits us to 100 pushState calls :/
426
+
427
+ try {
428
+ globalHistory.pushState(historyState, "", url);
429
+ } catch (error) {
430
+ // They are going to lose state here, but there is no real
431
+ // way to warn them about it since the page will refresh...
432
+ window.location.assign(url);
433
+ }
434
+
435
+ if (v5Compat && listener) {
436
+ listener({
437
+ action,
438
+ location: history.location,
439
+ delta: 1
440
+ });
441
+ }
442
+ }
443
+
444
+ function replace(to, state) {
445
+ action = Action.Replace;
446
+ let location = createLocation(history.location, to, state);
447
+ if (validateLocation) validateLocation(location, to);
448
+ index = getIndex();
449
+ let historyState = getHistoryState(location, index);
450
+ let url = history.createHref(location);
451
+ globalHistory.replaceState(historyState, "", url);
452
+
453
+ if (v5Compat && listener) {
454
+ listener({
455
+ action,
456
+ location: history.location,
457
+ delta: 0
458
+ });
459
+ }
460
+ }
461
+
462
+ function createURL(to) {
463
+ // window.location.origin is "null" (the literal string value) in Firefox
464
+ // under certain conditions, notably when serving from a local HTML file
465
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297
466
+ let base = window.location.origin !== "null" ? window.location.origin : window.location.href;
467
+ let href = typeof to === "string" ? to : createPath(to);
468
+ invariant(base, "No window.location.(origin|href) available to create URL for href: " + href);
469
+ return new URL(href, base);
470
+ }
471
+
472
+ let history = {
473
+ get action() {
474
+ return action;
475
+ },
476
+
477
+ get location() {
478
+ return getLocation(window, globalHistory);
479
+ },
480
+
481
+ listen(fn) {
482
+ if (listener) {
483
+ throw new Error("A history only accepts one active listener");
484
+ }
485
+
486
+ window.addEventListener(PopStateEventType, handlePop);
487
+ listener = fn;
488
+ return () => {
489
+ window.removeEventListener(PopStateEventType, handlePop);
490
+ listener = null;
491
+ };
492
+ },
493
+
494
+ createHref(to) {
495
+ return createHref(window, to);
496
+ },
497
+
498
+ createURL,
499
+
500
+ encodeLocation(to) {
501
+ // Encode a Location the same way window.location would
502
+ let url = createURL(to);
503
+ return {
504
+ pathname: url.pathname,
505
+ search: url.search,
506
+ hash: url.hash
507
+ };
508
+ },
509
+
510
+ push,
511
+ replace,
512
+
513
+ go(n) {
514
+ return globalHistory.go(n);
515
+ }
516
+
517
+ };
518
+ return history;
519
+ } //#endregion
520
+
521
+ var ResultType;
522
+
523
+ (function (ResultType) {
524
+ ResultType["data"] = "data";
525
+ ResultType["deferred"] = "deferred";
526
+ ResultType["redirect"] = "redirect";
527
+ ResultType["error"] = "error";
528
+ })(ResultType || (ResultType = {}));
529
+
530
+ function isIndexRoute(route) {
531
+ return route.index === true;
532
+ } // Walk the route tree generating unique IDs where necessary so we are working
533
+ // solely with AgnosticDataRouteObject's within the Router
534
+
535
+
536
+ function convertRoutesToDataRoutes(routes, parentPath, allIds) {
537
+ if (parentPath === void 0) {
538
+ parentPath = [];
539
+ }
540
+
541
+ if (allIds === void 0) {
542
+ allIds = new Set();
543
+ }
544
+
545
+ return routes.map((route, index) => {
546
+ let treePath = [...parentPath, index];
547
+ let id = typeof route.id === "string" ? route.id : treePath.join("-");
548
+ invariant(route.index !== true || !route.children, "Cannot specify children on an index route");
549
+ invariant(!allIds.has(id), "Found a route id collision on id \"" + id + "\". Route " + "id's must be globally unique within Data Router usages");
550
+ allIds.add(id);
551
+
552
+ if (isIndexRoute(route)) {
553
+ let indexRoute = _extends({}, route, {
554
+ id
555
+ });
556
+
557
+ return indexRoute;
558
+ } else {
559
+ let pathOrLayoutRoute = _extends({}, route, {
560
+ id,
561
+ children: route.children ? convertRoutesToDataRoutes(route.children, treePath, allIds) : undefined
562
+ });
563
+
564
+ return pathOrLayoutRoute;
565
+ }
566
+ });
567
+ }
568
+ /**
569
+ * Matches the given routes to a location and returns the match data.
570
+ *
571
+ * @see https://reactrouter.com/utils/match-routes
572
+ */
573
+
574
+ function matchRoutes(routes, locationArg, basename) {
575
+ if (basename === void 0) {
576
+ basename = "/";
577
+ }
578
+
579
+ let location = typeof locationArg === "string" ? parsePath(locationArg) : locationArg;
580
+ let pathname = stripBasename(location.pathname || "/", basename);
581
+
582
+ if (pathname == null) {
583
+ return null;
584
+ }
585
+
586
+ let branches = flattenRoutes(routes);
587
+ rankRouteBranches(branches);
588
+ let matches = null;
589
+
590
+ for (let i = 0; matches == null && i < branches.length; ++i) {
591
+ matches = matchRouteBranch(branches[i], // Incoming pathnames are generally encoded from either window.location
592
+ // or from router.navigate, but we want to match against the unencoded
593
+ // paths in the route definitions. Memory router locations won't be
594
+ // encoded here but there also shouldn't be anything to decode so this
595
+ // should be a safe operation. This avoids needing matchRoutes to be
596
+ // history-aware.
597
+ safelyDecodeURI(pathname));
598
+ }
599
+
600
+ return matches;
601
+ }
602
+
603
+ function flattenRoutes(routes, branches, parentsMeta, parentPath) {
604
+ if (branches === void 0) {
605
+ branches = [];
606
+ }
607
+
608
+ if (parentsMeta === void 0) {
609
+ parentsMeta = [];
610
+ }
611
+
612
+ if (parentPath === void 0) {
613
+ parentPath = "";
614
+ }
615
+
616
+ let flattenRoute = (route, index, relativePath) => {
617
+ let meta = {
618
+ relativePath: relativePath === undefined ? route.path || "" : relativePath,
619
+ caseSensitive: route.caseSensitive === true,
620
+ childrenIndex: index,
621
+ route
622
+ };
623
+
624
+ if (meta.relativePath.startsWith("/")) {
625
+ invariant(meta.relativePath.startsWith(parentPath), "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.");
626
+ meta.relativePath = meta.relativePath.slice(parentPath.length);
627
+ }
628
+
629
+ let path = joinPaths([parentPath, meta.relativePath]);
630
+ let routesMeta = parentsMeta.concat(meta); // Add the children before adding this route to the array so we traverse the
631
+ // route tree depth-first and child routes appear before their parents in
632
+ // the "flattened" version.
633
+
634
+ if (route.children && route.children.length > 0) {
635
+ invariant( // Our types know better, but runtime JS may not!
636
+ // @ts-expect-error
637
+ route.index !== true, "Index routes must not have child routes. Please remove " + ("all child routes from route path \"" + path + "\"."));
638
+ flattenRoutes(route.children, branches, routesMeta, path);
639
+ } // Routes without a path shouldn't ever match by themselves unless they are
640
+ // index routes, so don't add them to the list of possible branches.
641
+
642
+
643
+ if (route.path == null && !route.index) {
644
+ return;
645
+ }
646
+
647
+ branches.push({
648
+ path,
649
+ score: computeScore(path, route.index),
650
+ routesMeta
651
+ });
652
+ };
653
+
654
+ routes.forEach((route, index) => {
655
+ var _route$path;
656
+
657
+ // coarse-grain check for optional params
658
+ if (route.path === "" || !((_route$path = route.path) != null && _route$path.includes("?"))) {
659
+ flattenRoute(route, index);
660
+ } else {
661
+ for (let exploded of explodeOptionalSegments(route.path)) {
662
+ flattenRoute(route, index, exploded);
663
+ }
664
+ }
665
+ });
666
+ return branches;
667
+ }
668
+ /**
669
+ * Computes all combinations of optional path segments for a given path,
670
+ * excluding combinations that are ambiguous and of lower priority.
671
+ *
672
+ * For example, `/one/:two?/three/:four?/:five?` explodes to:
673
+ * - `/one/three`
674
+ * - `/one/:two/three`
675
+ * - `/one/three/:four`
676
+ * - `/one/three/:five`
677
+ * - `/one/:two/three/:four`
678
+ * - `/one/:two/three/:five`
679
+ * - `/one/three/:four/:five`
680
+ * - `/one/:two/three/:four/:five`
681
+ */
682
+
683
+
684
+ function explodeOptionalSegments(path) {
685
+ let segments = path.split("/");
686
+ if (segments.length === 0) return [];
687
+ let [first, ...rest] = segments; // Optional path segments are denoted by a trailing `?`
688
+
689
+ let isOptional = first.endsWith("?"); // Compute the corresponding required segment: `foo?` -> `foo`
690
+
691
+ let required = first.replace(/\?$/, "");
692
+
693
+ if (rest.length === 0) {
694
+ // Intepret empty string as omitting an optional segment
695
+ // `["one", "", "three"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`
696
+ return isOptional ? [required, ""] : [required];
697
+ }
698
+
699
+ let restExploded = explodeOptionalSegments(rest.join("/"));
700
+ let result = []; // All child paths with the prefix. Do this for all children before the
701
+ // optional version for all children so we get consistent ordering where the
702
+ // parent optional aspect is preferred as required. Otherwise, we can get
703
+ // child sections interspersed where deeper optional segments are higher than
704
+ // parent optional segments, where for example, /:two would explodes _earlier_
705
+ // then /:one. By always including the parent as required _for all children_
706
+ // first, we avoid this issue
707
+
708
+ result.push(...restExploded.map(subpath => subpath === "" ? required : [required, subpath].join("/"))); // Then if this is an optional value, add all child versions without
709
+
710
+ if (isOptional) {
711
+ result.push(...restExploded);
712
+ } // for absolute paths, ensure `/` instead of empty segment
713
+
714
+
715
+ return result.map(exploded => path.startsWith("/") && exploded === "" ? "/" : exploded);
716
+ }
717
+
718
+ function rankRouteBranches(branches) {
719
+ branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first
720
+ : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));
721
+ }
722
+
723
+ const paramRe = /^:\w+$/;
724
+ const dynamicSegmentValue = 3;
725
+ const indexRouteValue = 2;
726
+ const emptySegmentValue = 1;
727
+ const staticSegmentValue = 10;
728
+ const splatPenalty = -2;
729
+
730
+ const isSplat = s => s === "*";
731
+
732
+ function computeScore(path, index) {
733
+ let segments = path.split("/");
734
+ let initialScore = segments.length;
735
+
736
+ if (segments.some(isSplat)) {
737
+ initialScore += splatPenalty;
738
+ }
739
+
740
+ if (index) {
741
+ initialScore += indexRouteValue;
742
+ }
743
+
744
+ return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === "" ? emptySegmentValue : staticSegmentValue), initialScore);
745
+ }
746
+
747
+ function compareIndexes(a, b) {
748
+ let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);
749
+ return siblings ? // If two routes are siblings, we should try to match the earlier sibling
750
+ // first. This allows people to have fine-grained control over the matching
751
+ // behavior by simply putting routes with identical paths in the order they
752
+ // want them tried.
753
+ a[a.length - 1] - b[b.length - 1] : // Otherwise, it doesn't really make sense to rank non-siblings by index,
754
+ // so they sort equally.
755
+ 0;
756
+ }
757
+
758
+ function matchRouteBranch(branch, pathname) {
759
+ let {
760
+ routesMeta
761
+ } = branch;
762
+ let matchedParams = {};
763
+ let matchedPathname = "/";
764
+ let matches = [];
765
+
766
+ for (let i = 0; i < routesMeta.length; ++i) {
767
+ let meta = routesMeta[i];
768
+ let end = i === routesMeta.length - 1;
769
+ let remainingPathname = matchedPathname === "/" ? pathname : pathname.slice(matchedPathname.length) || "/";
770
+ let match = matchPath({
771
+ path: meta.relativePath,
772
+ caseSensitive: meta.caseSensitive,
773
+ end
774
+ }, remainingPathname);
775
+ if (!match) return null;
776
+ Object.assign(matchedParams, match.params);
777
+ let route = meta.route;
778
+ matches.push({
779
+ // TODO: Can this as be avoided?
780
+ params: matchedParams,
781
+ pathname: joinPaths([matchedPathname, match.pathname]),
782
+ pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),
783
+ route
784
+ });
785
+
786
+ if (match.pathnameBase !== "/") {
787
+ matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);
788
+ }
789
+ }
790
+
791
+ return matches;
792
+ }
793
+ /**
794
+ * Returns a path with params interpolated.
795
+ *
796
+ * @see https://reactrouter.com/utils/generate-path
797
+ */
798
+
799
+
800
+ function generatePath(originalPath, params) {
801
+ if (params === void 0) {
802
+ params = {};
803
+ }
804
+
805
+ let path = originalPath;
806
+
807
+ if (path.endsWith("*") && path !== "*" && !path.endsWith("/*")) {
808
+ warning(false, "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(/\*$/, "/*") + "\"."));
809
+ path = path.replace(/\*$/, "/*");
810
+ }
811
+
812
+ return path.replace(/^:(\w+)(\??)/g, (_, key, optional) => {
813
+ let param = params[key];
814
+
815
+ if (optional === "?") {
816
+ return param == null ? "" : param;
817
+ }
818
+
819
+ if (param == null) {
820
+ invariant(false, "Missing \":" + key + "\" param");
821
+ }
822
+
823
+ return param;
824
+ }).replace(/\/:(\w+)(\??)/g, (_, key, optional) => {
825
+ let param = params[key];
826
+
827
+ if (optional === "?") {
828
+ return param == null ? "" : "/" + param;
829
+ }
830
+
831
+ if (param == null) {
832
+ invariant(false, "Missing \":" + key + "\" param");
833
+ }
834
+
835
+ return "/" + param;
836
+ }) // Remove any optional markers from optional static segments
837
+ .replace(/\?/g, "").replace(/(\/?)\*/, (_, prefix, __, str) => {
838
+ const star = "*";
839
+
840
+ if (params[star] == null) {
841
+ // If no splat was provided, trim the trailing slash _unless_ it's
842
+ // the entire path
843
+ return str === "/*" ? "/" : "";
844
+ } // Apply the splat
845
+
846
+
847
+ return "" + prefix + params[star];
848
+ });
849
+ }
850
+ /**
851
+ * Performs pattern matching on a URL pathname and returns information about
852
+ * the match.
853
+ *
854
+ * @see https://reactrouter.com/utils/match-path
855
+ */
856
+
857
+ function matchPath(pattern, pathname) {
858
+ if (typeof pattern === "string") {
859
+ pattern = {
860
+ path: pattern,
861
+ caseSensitive: false,
862
+ end: true
863
+ };
864
+ }
865
+
866
+ let [matcher, paramNames] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);
867
+ let match = pathname.match(matcher);
868
+ if (!match) return null;
869
+ let matchedPathname = match[0];
870
+ let pathnameBase = matchedPathname.replace(/(.)\/+$/, "$1");
871
+ let captureGroups = match.slice(1);
872
+ let params = paramNames.reduce((memo, paramName, index) => {
873
+ // We need to compute the pathnameBase here using the raw splat value
874
+ // instead of using params["*"] later because it will be decoded then
875
+ if (paramName === "*") {
876
+ let splatValue = captureGroups[index] || "";
877
+ pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\/+$/, "$1");
878
+ }
879
+
880
+ memo[paramName] = safelyDecodeURIComponent(captureGroups[index] || "", paramName);
881
+ return memo;
882
+ }, {});
883
+ return {
884
+ params,
885
+ pathname: matchedPathname,
886
+ pathnameBase,
887
+ pattern
888
+ };
889
+ }
890
+
891
+ function compilePath(path, caseSensitive, end) {
892
+ if (caseSensitive === void 0) {
893
+ caseSensitive = false;
894
+ }
895
+
896
+ if (end === void 0) {
897
+ end = true;
898
+ }
899
+
900
+ warning(path === "*" || !path.endsWith("*") || path.endsWith("/*"), "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(/\*$/, "/*") + "\"."));
901
+ let paramNames = [];
902
+ let regexpSource = "^" + path.replace(/\/*\*?$/, "") // Ignore trailing / and /*, we'll handle it below
903
+ .replace(/^\/*/, "/") // Make sure it has a leading /
904
+ .replace(/[\\.*+^$?{}|()[\]]/g, "\\$&") // Escape special regex chars
905
+ .replace(/\/:(\w+)/g, (_, paramName) => {
906
+ paramNames.push(paramName);
907
+ return "/([^\\/]+)";
908
+ });
909
+
910
+ if (path.endsWith("*")) {
911
+ paramNames.push("*");
912
+ regexpSource += path === "*" || path === "/*" ? "(.*)$" // Already matched the initial /, just match the rest
913
+ : "(?:\\/(.+)|\\/*)$"; // Don't include the / in params["*"]
914
+ } else if (end) {
915
+ // When matching to the end, ignore trailing slashes
916
+ regexpSource += "\\/*$";
917
+ } else if (path !== "" && path !== "/") {
918
+ // If our path is non-empty and contains anything beyond an initial slash,
919
+ // then we have _some_ form of path in our regex so we should expect to
920
+ // match only if we find the end of this path segment. Look for an optional
921
+ // non-captured trailing slash (to match a portion of the URL) or the end
922
+ // of the path (if we've matched to the end). We used to do this with a
923
+ // word boundary but that gives false positives on routes like
924
+ // /user-preferences since `-` counts as a word boundary.
925
+ regexpSource += "(?:(?=\\/|$))";
926
+ } else ;
927
+
928
+ let matcher = new RegExp(regexpSource, caseSensitive ? undefined : "i");
929
+ return [matcher, paramNames];
930
+ }
931
+
932
+ function safelyDecodeURI(value) {
933
+ try {
934
+ return decodeURI(value);
935
+ } catch (error) {
936
+ warning(false, "The URL path \"" + value + "\" could not be decoded because it is is a " + "malformed URL segment. This is probably due to a bad percent " + ("encoding (" + error + ")."));
937
+ return value;
938
+ }
939
+ }
940
+
941
+ function safelyDecodeURIComponent(value, paramName) {
942
+ try {
943
+ return decodeURIComponent(value);
944
+ } catch (error) {
945
+ warning(false, "The value for the URL param \"" + paramName + "\" will not be decoded because" + (" the string \"" + value + "\" is a malformed URL segment. This is probably") + (" due to a bad percent encoding (" + error + ")."));
946
+ return value;
947
+ }
948
+ }
949
+ /**
950
+ * @private
951
+ */
952
+
953
+
954
+ function stripBasename(pathname, basename) {
955
+ if (basename === "/") return pathname;
956
+
957
+ if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {
958
+ return null;
959
+ } // We want to leave trailing slash behavior in the user's control, so if they
960
+ // specify a basename with a trailing slash, we should support it
961
+
962
+
963
+ let startIndex = basename.endsWith("/") ? basename.length - 1 : basename.length;
964
+ let nextChar = pathname.charAt(startIndex);
965
+
966
+ if (nextChar && nextChar !== "/") {
967
+ // pathname does not start with basename/
968
+ return null;
969
+ }
970
+
971
+ return pathname.slice(startIndex) || "/";
972
+ }
973
+ /**
974
+ * @private
975
+ */
976
+
977
+ function warning(cond, message) {
978
+ if (!cond) {
979
+ // eslint-disable-next-line no-console
980
+ if (typeof console !== "undefined") console.warn(message);
981
+
982
+ try {
983
+ // Welcome to debugging @remix-run/router!
984
+ //
985
+ // This error is thrown as a convenience so you can more easily
986
+ // find the source for a warning that appears in the console by
987
+ // enabling "pause on exceptions" in your JavaScript debugger.
988
+ throw new Error(message); // eslint-disable-next-line no-empty
989
+ } catch (e) {}
990
+ }
991
+ }
992
+ /**
993
+ * Returns a resolved path object relative to the given pathname.
994
+ *
995
+ * @see https://reactrouter.com/utils/resolve-path
996
+ */
997
+
998
+ function resolvePath(to, fromPathname) {
999
+ if (fromPathname === void 0) {
1000
+ fromPathname = "/";
1001
+ }
1002
+
1003
+ let {
1004
+ pathname: toPathname,
1005
+ search = "",
1006
+ hash = ""
1007
+ } = typeof to === "string" ? parsePath(to) : to;
1008
+ let pathname = toPathname ? toPathname.startsWith("/") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;
1009
+ return {
1010
+ pathname,
1011
+ search: normalizeSearch(search),
1012
+ hash: normalizeHash(hash)
1013
+ };
1014
+ }
1015
+
1016
+ function resolvePathname(relativePath, fromPathname) {
1017
+ let segments = fromPathname.replace(/\/+$/, "").split("/");
1018
+ let relativeSegments = relativePath.split("/");
1019
+ relativeSegments.forEach(segment => {
1020
+ if (segment === "..") {
1021
+ // Keep the root "" segment so the pathname starts at /
1022
+ if (segments.length > 1) segments.pop();
1023
+ } else if (segment !== ".") {
1024
+ segments.push(segment);
1025
+ }
1026
+ });
1027
+ return segments.length > 1 ? segments.join("/") : "/";
1028
+ }
1029
+
1030
+ function getInvalidPathError(char, field, dest, path) {
1031
+ return "Cannot include a '" + char + "' character in a manually specified " + ("`to." + field + "` field [" + JSON.stringify(path) + "]. 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.";
1032
+ }
1033
+ /**
1034
+ * @private
1035
+ *
1036
+ * When processing relative navigation we want to ignore ancestor routes that
1037
+ * do not contribute to the path, such that index/pathless layout routes don't
1038
+ * interfere.
1039
+ *
1040
+ * For example, when moving a route element into an index route and/or a
1041
+ * pathless layout route, relative link behavior contained within should stay
1042
+ * the same. Both of the following examples should link back to the root:
1043
+ *
1044
+ * <Route path="/">
1045
+ * <Route path="accounts" element={<Link to=".."}>
1046
+ * </Route>
1047
+ *
1048
+ * <Route path="/">
1049
+ * <Route path="accounts">
1050
+ * <Route element={<AccountsLayout />}> // <-- Does not contribute
1051
+ * <Route index element={<Link to=".."} /> // <-- Does not contribute
1052
+ * </Route
1053
+ * </Route>
1054
+ * </Route>
1055
+ */
1056
+
1057
+
1058
+ function getPathContributingMatches(matches) {
1059
+ return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);
1060
+ }
1061
+ /**
1062
+ * @private
1063
+ */
1064
+
1065
+ function resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {
1066
+ if (isPathRelative === void 0) {
1067
+ isPathRelative = false;
1068
+ }
1069
+
1070
+ let to;
1071
+
1072
+ if (typeof toArg === "string") {
1073
+ to = parsePath(toArg);
1074
+ } else {
1075
+ to = _extends({}, toArg);
1076
+ invariant(!to.pathname || !to.pathname.includes("?"), getInvalidPathError("?", "pathname", "search", to));
1077
+ invariant(!to.pathname || !to.pathname.includes("#"), getInvalidPathError("#", "pathname", "hash", to));
1078
+ invariant(!to.search || !to.search.includes("#"), getInvalidPathError("#", "search", "hash", to));
1079
+ }
1080
+
1081
+ let isEmptyPath = toArg === "" || to.pathname === "";
1082
+ let toPathname = isEmptyPath ? "/" : to.pathname;
1083
+ let from; // Routing is relative to the current pathname if explicitly requested.
1084
+ //
1085
+ // If a pathname is explicitly provided in `to`, it should be relative to the
1086
+ // route context. This is explained in `Note on `<Link to>` values` in our
1087
+ // migration guide from v5 as a means of disambiguation between `to` values
1088
+ // that begin with `/` and those that do not. However, this is problematic for
1089
+ // `to` values that do not provide a pathname. `to` can simply be a search or
1090
+ // hash string, in which case we should assume that the navigation is relative
1091
+ // to the current location's pathname and *not* the route pathname.
1092
+
1093
+ if (isPathRelative || toPathname == null) {
1094
+ from = locationPathname;
1095
+ } else {
1096
+ let routePathnameIndex = routePathnames.length - 1;
1097
+
1098
+ if (toPathname.startsWith("..")) {
1099
+ let toSegments = toPathname.split("/"); // Each leading .. segment means "go up one route" instead of "go up one
1100
+ // URL segment". This is a key difference from how <a href> works and a
1101
+ // major reason we call this a "to" value instead of a "href".
1102
+
1103
+ while (toSegments[0] === "..") {
1104
+ toSegments.shift();
1105
+ routePathnameIndex -= 1;
1106
+ }
1107
+
1108
+ to.pathname = toSegments.join("/");
1109
+ } // If there are more ".." segments than parent routes, resolve relative to
1110
+ // the root / URL.
1111
+
1112
+
1113
+ from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : "/";
1114
+ }
1115
+
1116
+ let path = resolvePath(to, from); // Ensure the pathname has a trailing slash if the original "to" had one
1117
+
1118
+ let hasExplicitTrailingSlash = toPathname && toPathname !== "/" && toPathname.endsWith("/"); // Or if this was a link to the current path which has a trailing slash
1119
+
1120
+ let hasCurrentTrailingSlash = (isEmptyPath || toPathname === ".") && locationPathname.endsWith("/");
1121
+
1122
+ if (!path.pathname.endsWith("/") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {
1123
+ path.pathname += "/";
1124
+ }
1125
+
1126
+ return path;
1127
+ }
1128
+ /**
1129
+ * @private
1130
+ */
1131
+
1132
+ function getToPathname(to) {
1133
+ // Empty strings should be treated the same as / paths
1134
+ return to === "" || to.pathname === "" ? "/" : typeof to === "string" ? parsePath(to).pathname : to.pathname;
1135
+ }
1136
+ /**
1137
+ * @private
1138
+ */
1139
+
1140
+ const joinPaths = paths => paths.join("/").replace(/\/\/+/g, "/");
1141
+ /**
1142
+ * @private
1143
+ */
1144
+
1145
+ const normalizePathname = pathname => pathname.replace(/\/+$/, "").replace(/^\/*/, "/");
1146
+ /**
1147
+ * @private
1148
+ */
1149
+
1150
+ const normalizeSearch = search => !search || search === "?" ? "" : search.startsWith("?") ? search : "?" + search;
1151
+ /**
1152
+ * @private
1153
+ */
1154
+
1155
+ const normalizeHash = hash => !hash || hash === "#" ? "" : hash.startsWith("#") ? hash : "#" + hash;
1156
+ /**
1157
+ * This is a shortcut for creating `application/json` responses. Converts `data`
1158
+ * to JSON and sets the `Content-Type` header.
1159
+ */
1160
+
1161
+ const json = function json(data, init) {
1162
+ if (init === void 0) {
1163
+ init = {};
1164
+ }
1165
+
1166
+ let responseInit = typeof init === "number" ? {
1167
+ status: init
1168
+ } : init;
1169
+ let headers = new Headers(responseInit.headers);
1170
+
1171
+ if (!headers.has("Content-Type")) {
1172
+ headers.set("Content-Type", "application/json; charset=utf-8");
1173
+ }
1174
+
1175
+ return new Response(JSON.stringify(data), _extends({}, responseInit, {
1176
+ headers
1177
+ }));
1178
+ };
1179
+ class AbortedDeferredError extends Error {}
1180
+ class DeferredData {
1181
+ constructor(data, responseInit) {
1182
+ this.pendingKeysSet = new Set();
1183
+ this.subscribers = new Set();
1184
+ this.deferredKeys = [];
1185
+ invariant(data && typeof data === "object" && !Array.isArray(data), "defer() only accepts plain objects"); // Set up an AbortController + Promise we can race against to exit early
1186
+ // cancellation
1187
+
1188
+ let reject;
1189
+ this.abortPromise = new Promise((_, r) => reject = r);
1190
+ this.controller = new AbortController();
1191
+
1192
+ let onAbort = () => reject(new AbortedDeferredError("Deferred data aborted"));
1193
+
1194
+ this.unlistenAbortSignal = () => this.controller.signal.removeEventListener("abort", onAbort);
1195
+
1196
+ this.controller.signal.addEventListener("abort", onAbort);
1197
+ this.data = Object.entries(data).reduce((acc, _ref) => {
1198
+ let [key, value] = _ref;
1199
+ return Object.assign(acc, {
1200
+ [key]: this.trackPromise(key, value)
1201
+ });
1202
+ }, {});
1203
+
1204
+ if (this.done) {
1205
+ // All incoming values were resolved
1206
+ this.unlistenAbortSignal();
1207
+ }
1208
+
1209
+ this.init = responseInit;
1210
+ }
1211
+
1212
+ trackPromise(key, value) {
1213
+ if (!(value instanceof Promise)) {
1214
+ return value;
1215
+ }
1216
+
1217
+ this.deferredKeys.push(key);
1218
+ this.pendingKeysSet.add(key); // We store a little wrapper promise that will be extended with
1219
+ // _data/_error props upon resolve/reject
1220
+
1221
+ let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, null, data), error => this.onSettle(promise, key, error)); // Register rejection listeners to avoid uncaught promise rejections on
1222
+ // errors or aborted deferred values
1223
+
1224
+ promise.catch(() => {});
1225
+ Object.defineProperty(promise, "_tracked", {
1226
+ get: () => true
1227
+ });
1228
+ return promise;
1229
+ }
1230
+
1231
+ onSettle(promise, key, error, data) {
1232
+ if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {
1233
+ this.unlistenAbortSignal();
1234
+ Object.defineProperty(promise, "_error", {
1235
+ get: () => error
1236
+ });
1237
+ return Promise.reject(error);
1238
+ }
1239
+
1240
+ this.pendingKeysSet.delete(key);
1241
+
1242
+ if (this.done) {
1243
+ // Nothing left to abort!
1244
+ this.unlistenAbortSignal();
1245
+ }
1246
+
1247
+ if (error) {
1248
+ Object.defineProperty(promise, "_error", {
1249
+ get: () => error
1250
+ });
1251
+ this.emit(false, key);
1252
+ return Promise.reject(error);
1253
+ }
1254
+
1255
+ Object.defineProperty(promise, "_data", {
1256
+ get: () => data
1257
+ });
1258
+ this.emit(false, key);
1259
+ return data;
1260
+ }
1261
+
1262
+ emit(aborted, settledKey) {
1263
+ this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));
1264
+ }
1265
+
1266
+ subscribe(fn) {
1267
+ this.subscribers.add(fn);
1268
+ return () => this.subscribers.delete(fn);
1269
+ }
1270
+
1271
+ cancel() {
1272
+ this.controller.abort();
1273
+ this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));
1274
+ this.emit(true);
1275
+ }
1276
+
1277
+ async resolveData(signal) {
1278
+ let aborted = false;
1279
+
1280
+ if (!this.done) {
1281
+ let onAbort = () => this.cancel();
1282
+
1283
+ signal.addEventListener("abort", onAbort);
1284
+ aborted = await new Promise(resolve => {
1285
+ this.subscribe(aborted => {
1286
+ signal.removeEventListener("abort", onAbort);
1287
+
1288
+ if (aborted || this.done) {
1289
+ resolve(aborted);
1290
+ }
1291
+ });
1292
+ });
1293
+ }
1294
+
1295
+ return aborted;
1296
+ }
1297
+
1298
+ get done() {
1299
+ return this.pendingKeysSet.size === 0;
1300
+ }
1301
+
1302
+ get unwrappedData() {
1303
+ invariant(this.data !== null && this.done, "Can only unwrap data on initialized and settled deferreds");
1304
+ return Object.entries(this.data).reduce((acc, _ref2) => {
1305
+ let [key, value] = _ref2;
1306
+ return Object.assign(acc, {
1307
+ [key]: unwrapTrackedPromise(value)
1308
+ });
1309
+ }, {});
1310
+ }
1311
+
1312
+ get pendingKeys() {
1313
+ return Array.from(this.pendingKeysSet);
1314
+ }
1315
+
1316
+ }
1317
+
1318
+ function isTrackedPromise(value) {
1319
+ return value instanceof Promise && value._tracked === true;
1320
+ }
1321
+
1322
+ function unwrapTrackedPromise(value) {
1323
+ if (!isTrackedPromise(value)) {
1324
+ return value;
1325
+ }
1326
+
1327
+ if (value._error) {
1328
+ throw value._error;
1329
+ }
1330
+
1331
+ return value._data;
1332
+ }
1333
+
1334
+ const defer = function defer(data, init) {
1335
+ if (init === void 0) {
1336
+ init = {};
1337
+ }
1338
+
1339
+ let responseInit = typeof init === "number" ? {
1340
+ status: init
1341
+ } : init;
1342
+ return new DeferredData(data, responseInit);
1343
+ };
1344
+ /**
1345
+ * A redirect response. Sets the status code and the `Location` header.
1346
+ * Defaults to "302 Found".
1347
+ */
1348
+
1349
+ const redirect = function redirect(url, init) {
1350
+ if (init === void 0) {
1351
+ init = 302;
1352
+ }
1353
+
1354
+ let responseInit = init;
1355
+
1356
+ if (typeof responseInit === "number") {
1357
+ responseInit = {
1358
+ status: responseInit
1359
+ };
1360
+ } else if (typeof responseInit.status === "undefined") {
1361
+ responseInit.status = 302;
1362
+ }
1363
+
1364
+ let headers = new Headers(responseInit.headers);
1365
+ headers.set("Location", url);
1366
+ return new Response(null, _extends({}, responseInit, {
1367
+ headers
1368
+ }));
1369
+ };
1370
+ /**
1371
+ * @private
1372
+ * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies
1373
+ */
1374
+
1375
+ class ErrorResponse {
1376
+ constructor(status, statusText, data, internal) {
1377
+ if (internal === void 0) {
1378
+ internal = false;
1379
+ }
1380
+
1381
+ this.status = status;
1382
+ this.statusText = statusText || "";
1383
+ this.internal = internal;
1384
+
1385
+ if (data instanceof Error) {
1386
+ this.data = data.toString();
1387
+ this.error = data;
1388
+ } else {
1389
+ this.data = data;
1390
+ }
1391
+ }
1392
+
1393
+ }
1394
+ /**
1395
+ * Check if the given error is an ErrorResponse generated from a 4xx/5xx
1396
+ * Response thrown from an action/loader
1397
+ */
1398
+
1399
+ function isRouteErrorResponse(error) {
1400
+ return error != null && typeof error.status === "number" && typeof error.statusText === "string" && typeof error.internal === "boolean" && "data" in error;
1401
+ }
1402
+ /**
1403
+ * Generic class to "hold" a default middleware value and the generic type so
1404
+ * we can enforce typings on middleware.get/set
1405
+ */
1406
+
1407
+ class MiddlewareContextInstance {
1408
+ constructor(defaultValue) {
1409
+ if (typeof defaultValue !== "undefined") {
1410
+ this.defaultValue = defaultValue;
1411
+ }
1412
+ }
1413
+
1414
+ getDefaultValue() {
1415
+ if (typeof this.defaultValue === "undefined") {
1416
+ throw new Error("Unable to find a value in the middleware context");
1417
+ }
1418
+
1419
+ return this.defaultValue;
1420
+ }
1421
+
1422
+ }
1423
+ /**
1424
+ * Create a middleware context that can be used as a "key" to set/get middleware
1425
+ * values in a strongly-typed fashion
1426
+ */
1427
+
1428
+ function createMiddlewareContext(defaultValue) {
1429
+ return new MiddlewareContextInstance(defaultValue);
1430
+ }
1431
+ /**
1432
+ * @internal
1433
+ * PRIVATE - DO NOT USE
1434
+ *
1435
+ * Create a middleware "context" to store values and provide a next() hook
1436
+ */
1437
+
1438
+ function createMiddlewareStore(initialMiddlewareContext) {
1439
+ let store = new Map(initialMiddlewareContext == null ? void 0 : initialMiddlewareContext.entries());
1440
+ let middlewareContext = {
1441
+ get(k) {
1442
+ if (store.has(k)) {
1443
+ return store.get(k);
1444
+ }
1445
+
1446
+ return k.getDefaultValue();
1447
+ },
1448
+
1449
+ set(k, v) {
1450
+ if (typeof v === "undefined") {
1451
+ throw new Error("You cannot set an undefined value in the middleware context");
1452
+ }
1453
+
1454
+ store.set(k, v);
1455
+ },
1456
+
1457
+ next: () => {},
1458
+ entries: () => store.entries()
1459
+ };
1460
+ return middlewareContext;
1461
+ }
1462
+
1463
+ const defaultFutureConfig = {
1464
+ unstable_middleware: false
1465
+ };
1466
+ const validMutationMethodsArr = ["post", "put", "patch", "delete"];
1467
+ const validMutationMethods = new Set(validMutationMethodsArr);
1468
+ const validRequestMethodsArr = ["get", ...validMutationMethodsArr];
1469
+ const validRequestMethods = new Set(validRequestMethodsArr);
1470
+ const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
1471
+ const redirectPreserveMethodStatusCodes = new Set([307, 308]);
1472
+ const IDLE_NAVIGATION = {
1473
+ state: "idle",
1474
+ location: undefined,
1475
+ formMethod: undefined,
1476
+ formAction: undefined,
1477
+ formEncType: undefined,
1478
+ formData: undefined
1479
+ };
1480
+ const IDLE_FETCHER = {
1481
+ state: "idle",
1482
+ data: undefined,
1483
+ formMethod: undefined,
1484
+ formAction: undefined,
1485
+ formEncType: undefined,
1486
+ formData: undefined
1487
+ };
1488
+ const IDLE_BLOCKER = {
1489
+ state: "unblocked",
1490
+ proceed: undefined,
1491
+ reset: undefined,
1492
+ location: undefined
1493
+ };
1494
+ const ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
1495
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
1496
+ const isServer = !isBrowser; //#endregion
1497
+ ////////////////////////////////////////////////////////////////////////////////
1498
+ //#region createRouter
1499
+ ////////////////////////////////////////////////////////////////////////////////
1500
+
1501
+ /**
1502
+ * Create a router and listen to history POP navigations
1503
+ */
1504
+
1505
+ function createRouter(init) {
1506
+ invariant(init.routes.length > 0, "You must provide a non-empty routes array to createRouter");
1507
+ let dataRoutes = convertRoutesToDataRoutes(init.routes);
1508
+
1509
+ let future = _extends({}, defaultFutureConfig, init.future); // Cleanup function for history
1510
+
1511
+
1512
+ let unlistenHistory = null; // Externally-provided functions to call on all state changes
1513
+
1514
+ let subscribers = new Set(); // Externally-provided object to hold scroll restoration locations during routing
1515
+
1516
+ let savedScrollPositions = null; // Externally-provided function to get scroll restoration keys
1517
+
1518
+ let getScrollRestorationKey = null; // Externally-provided function to get current scroll position
1519
+
1520
+ let getScrollPosition = null; // One-time flag to control the initial hydration scroll restoration. Because
1521
+ // we don't get the saved positions from <ScrollRestoration /> until _after_
1522
+ // the initial render, we need to manually trigger a separate updateState to
1523
+ // send along the restoreScrollPosition
1524
+ // Set to true if we have `hydrationData` since we assume we were SSR'd and that
1525
+ // SSR did the initial scroll restoration.
1526
+
1527
+ let initialScrollRestored = init.hydrationData != null;
1528
+ let initialMatches = matchRoutes(dataRoutes, init.history.location, init.basename);
1529
+ let initialErrors = null;
1530
+
1531
+ if (initialMatches == null) {
1532
+ // If we do not match a user-provided-route, fall back to the root
1533
+ // to allow the error boundary to take over
1534
+ let error = getInternalRouterError(404, {
1535
+ pathname: init.history.location.pathname
1536
+ });
1537
+ let {
1538
+ matches,
1539
+ route
1540
+ } = getShortCircuitMatches(dataRoutes);
1541
+ initialMatches = matches;
1542
+ initialErrors = {
1543
+ [route.id]: error
1544
+ };
1545
+ }
1546
+
1547
+ let initialized = !initialMatches.some(m => m.route.loader) || init.hydrationData != null;
1548
+ let router;
1549
+ let state = {
1550
+ historyAction: init.history.action,
1551
+ location: init.history.location,
1552
+ matches: initialMatches,
1553
+ initialized,
1554
+ navigation: IDLE_NAVIGATION,
1555
+ // Don't restore on initial updateState() if we were SSR'd
1556
+ restoreScrollPosition: init.hydrationData != null ? false : null,
1557
+ preventScrollReset: false,
1558
+ revalidation: "idle",
1559
+ loaderData: init.hydrationData && init.hydrationData.loaderData || {},
1560
+ actionData: init.hydrationData && init.hydrationData.actionData || null,
1561
+ errors: init.hydrationData && init.hydrationData.errors || initialErrors,
1562
+ fetchers: new Map(),
1563
+ blockers: new Map()
1564
+ }; // -- Stateful internal variables to manage navigations --
1565
+ // Current navigation in progress (to be committed in completeNavigation)
1566
+
1567
+ let pendingAction = Action.Pop; // Should the current navigation prevent the scroll reset if scroll cannot
1568
+ // be restored?
1569
+
1570
+ let pendingPreventScrollReset = false; // AbortController for the active navigation
1571
+
1572
+ let pendingNavigationController; // We use this to avoid touching history in completeNavigation if a
1573
+ // revalidation is entirely uninterrupted
1574
+
1575
+ let isUninterruptedRevalidation = false; // Use this internal flag to force revalidation of all loaders:
1576
+ // - submissions (completed or interrupted)
1577
+ // - useRevalidate()
1578
+ // - X-Remix-Revalidate (from redirect)
1579
+
1580
+ let isRevalidationRequired = false; // Use this internal array to capture routes that require revalidation due
1581
+ // to a cancelled deferred on action submission
1582
+
1583
+ let cancelledDeferredRoutes = []; // Use this internal array to capture fetcher loads that were cancelled by an
1584
+ // action navigation and require revalidation
1585
+
1586
+ let cancelledFetcherLoads = []; // AbortControllers for any in-flight fetchers
1587
+
1588
+ let fetchControllers = new Map(); // Track loads based on the order in which they started
1589
+
1590
+ let incrementingLoadId = 0; // Track the outstanding pending navigation data load to be compared against
1591
+ // the globally incrementing load when a fetcher load lands after a completed
1592
+ // navigation
1593
+
1594
+ let pendingNavigationLoadId = -1; // Fetchers that triggered data reloads as a result of their actions
1595
+
1596
+ let fetchReloadIds = new Map(); // Fetchers that triggered redirect navigations from their actions
1597
+
1598
+ let fetchRedirectIds = new Set(); // Most recent href/match for fetcher.load calls for fetchers
1599
+
1600
+ let fetchLoadMatches = new Map(); // Store DeferredData instances for active route matches. When a
1601
+ // route loader returns defer() we stick one in here. Then, when a nested
1602
+ // promise resolves we update loaderData. If a new navigation starts we
1603
+ // cancel active deferreds for eliminated routes.
1604
+
1605
+ let activeDeferreds = new Map(); // Store blocker functions in a separate Map outside of router state since
1606
+ // we don't need to update UI state if they change
1607
+
1608
+ let blockerFunctions = new Map(); // Flag to ignore the next history update, so we can revert the URL change on
1609
+ // a POP navigation that was blocked by the user without touching router state
1610
+
1611
+ let ignoreNextHistoryUpdate = false; // Initialize the router, all side effects should be kicked off from here.
1612
+ // Implemented as a Fluent API for ease of:
1613
+ // let router = createRouter(init).initialize();
1614
+
1615
+ function initialize() {
1616
+ // If history informs us of a POP navigation, start the navigation but do not update
1617
+ // state. We'll update our own state once the navigation completes
1618
+ unlistenHistory = init.history.listen(_ref => {
1619
+ let {
1620
+ action: historyAction,
1621
+ location,
1622
+ delta
1623
+ } = _ref;
1624
+
1625
+ // Ignore this event if it was just us resetting the URL from a
1626
+ // blocked POP navigation
1627
+ if (ignoreNextHistoryUpdate) {
1628
+ ignoreNextHistoryUpdate = false;
1629
+ return;
1630
+ }
1631
+
1632
+ warning(blockerFunctions.size === 0 || delta != null, "You are trying to use a blocker on a POP navigation to a location " + "that was not created by @remix-run/router. This will fail silently in " + "production. This can happen if you are navigating outside the router " + "via `window.history.pushState`/`window.location.hash` instead of using " + "router navigation APIs. This can also happen if you are using " + "createHashRouter and the user manually changes the URL.");
1633
+ let blockerKey = shouldBlockNavigation({
1634
+ currentLocation: state.location,
1635
+ nextLocation: location,
1636
+ historyAction
1637
+ });
1638
+
1639
+ if (blockerKey && delta != null) {
1640
+ // Restore the URL to match the current UI, but don't update router state
1641
+ ignoreNextHistoryUpdate = true;
1642
+ init.history.go(delta * -1); // Put the blocker into a blocked state
1643
+
1644
+ updateBlocker(blockerKey, {
1645
+ state: "blocked",
1646
+ location,
1647
+
1648
+ proceed() {
1649
+ updateBlocker(blockerKey, {
1650
+ state: "proceeding",
1651
+ proceed: undefined,
1652
+ reset: undefined,
1653
+ location
1654
+ }); // Re-do the same POP navigation we just blocked
1655
+
1656
+ init.history.go(delta);
1657
+ },
1658
+
1659
+ reset() {
1660
+ deleteBlocker(blockerKey);
1661
+ updateState({
1662
+ blockers: new Map(router.state.blockers)
1663
+ });
1664
+ }
1665
+
1666
+ });
1667
+ return;
1668
+ }
1669
+
1670
+ return startNavigation(historyAction, location);
1671
+ }); // Kick off initial data load if needed. Use Pop to avoid modifying history
1672
+
1673
+ if (!state.initialized) {
1674
+ startNavigation(Action.Pop, state.location);
1675
+ }
1676
+
1677
+ return router;
1678
+ } // Clean up a router and it's side effects
1679
+
1680
+
1681
+ function dispose() {
1682
+ if (unlistenHistory) {
1683
+ unlistenHistory();
1684
+ }
1685
+
1686
+ subscribers.clear();
1687
+ pendingNavigationController && pendingNavigationController.abort();
1688
+ state.fetchers.forEach((_, key) => deleteFetcher(key));
1689
+ state.blockers.forEach((_, key) => deleteBlocker(key));
1690
+ } // Subscribe to state updates for the router
1691
+
1692
+
1693
+ function subscribe(fn) {
1694
+ subscribers.add(fn);
1695
+ return () => subscribers.delete(fn);
1696
+ } // Update our state and notify the calling context of the change
1697
+
1698
+
1699
+ function updateState(newState) {
1700
+ state = _extends({}, state, newState);
1701
+ subscribers.forEach(subscriber => subscriber(state));
1702
+ } // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION
1703
+ // and setting state.[historyAction/location/matches] to the new route.
1704
+ // - Location is a required param
1705
+ // - Navigation will always be set to IDLE_NAVIGATION
1706
+ // - Can pass any other state in newState
1707
+
1708
+
1709
+ function completeNavigation(location, newState) {
1710
+ var _location$state, _location$state2;
1711
+
1712
+ // Deduce if we're in a loading/actionReload state:
1713
+ // - We have committed actionData in the store
1714
+ // - The current navigation was a mutation submission
1715
+ // - We're past the submitting state and into the loading state
1716
+ // - The location being loaded is not the result of a redirect
1717
+ let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === "loading" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;
1718
+ let actionData;
1719
+
1720
+ if (newState.actionData) {
1721
+ if (Object.keys(newState.actionData).length > 0) {
1722
+ actionData = newState.actionData;
1723
+ } else {
1724
+ // Empty actionData -> clear prior actionData due to an action error
1725
+ actionData = null;
1726
+ }
1727
+ } else if (isActionReload) {
1728
+ // Keep the current data if we're wrapping up the action reload
1729
+ actionData = state.actionData;
1730
+ } else {
1731
+ // Clear actionData on any other completed navigations
1732
+ actionData = null;
1733
+ } // Always preserve any existing loaderData from re-used routes
1734
+
1735
+
1736
+ let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData; // On a successful navigation we can assume we got through all blockers
1737
+ // so we can start fresh
1738
+
1739
+ for (let [key] of blockerFunctions) {
1740
+ deleteBlocker(key);
1741
+ } // Always respect the user flag. Otherwise don't reset on mutation
1742
+ // submission navigations unless they redirect
1743
+
1744
+
1745
+ let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;
1746
+ updateState(_extends({}, newState, {
1747
+ actionData,
1748
+ loaderData,
1749
+ historyAction: pendingAction,
1750
+ location,
1751
+ initialized: true,
1752
+ navigation: IDLE_NAVIGATION,
1753
+ revalidation: "idle",
1754
+ restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),
1755
+ preventScrollReset,
1756
+ blockers: new Map(state.blockers)
1757
+ }));
1758
+
1759
+ if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {
1760
+ init.history.push(location, location.state);
1761
+ } else if (pendingAction === Action.Replace) {
1762
+ init.history.replace(location, location.state);
1763
+ } // Reset stateful navigation vars
1764
+
1765
+
1766
+ pendingAction = Action.Pop;
1767
+ pendingPreventScrollReset = false;
1768
+ isUninterruptedRevalidation = false;
1769
+ isRevalidationRequired = false;
1770
+ cancelledDeferredRoutes = [];
1771
+ cancelledFetcherLoads = [];
1772
+ } // Trigger a navigation event, which can either be a numerical POP or a PUSH
1773
+ // replace with an optional submission
1774
+
1775
+
1776
+ async function navigate(to, opts) {
1777
+ if (typeof to === "number") {
1778
+ init.history.go(to);
1779
+ return;
1780
+ }
1781
+
1782
+ let {
1783
+ path,
1784
+ submission,
1785
+ error
1786
+ } = normalizeNavigateOptions(to, opts);
1787
+ let currentLocation = state.location;
1788
+ let nextLocation = createLocation(state.location, path, opts && opts.state); // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded
1789
+ // URL from window.location, so we need to encode it here so the behavior
1790
+ // remains the same as POP and non-data-router usages. new URL() does all
1791
+ // the same encoding we'd get from a history.pushState/window.location read
1792
+ // without having to touch history
1793
+
1794
+ nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));
1795
+ let userReplace = opts && opts.replace != null ? opts.replace : undefined;
1796
+ let historyAction = Action.Push;
1797
+
1798
+ if (userReplace === true) {
1799
+ historyAction = Action.Replace;
1800
+ } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {
1801
+ // By default on submissions to the current location we REPLACE so that
1802
+ // users don't have to double-click the back button to get to the prior
1803
+ // location. If the user redirects to a different location from the
1804
+ // action/loader this will be ignored and the redirect will be a PUSH
1805
+ historyAction = Action.Replace;
1806
+ }
1807
+
1808
+ let preventScrollReset = opts && "preventScrollReset" in opts ? opts.preventScrollReset === true : undefined;
1809
+ let blockerKey = shouldBlockNavigation({
1810
+ currentLocation,
1811
+ nextLocation,
1812
+ historyAction
1813
+ });
1814
+
1815
+ if (blockerKey) {
1816
+ // Put the blocker into a blocked state
1817
+ updateBlocker(blockerKey, {
1818
+ state: "blocked",
1819
+ location: nextLocation,
1820
+
1821
+ proceed() {
1822
+ updateBlocker(blockerKey, {
1823
+ state: "proceeding",
1824
+ proceed: undefined,
1825
+ reset: undefined,
1826
+ location: nextLocation
1827
+ }); // Send the same navigation through
1828
+
1829
+ navigate(to, opts);
1830
+ },
1831
+
1832
+ reset() {
1833
+ deleteBlocker(blockerKey);
1834
+ updateState({
1835
+ blockers: new Map(state.blockers)
1836
+ });
1837
+ }
1838
+
1839
+ });
1840
+ return;
1841
+ }
1842
+
1843
+ return await startNavigation(historyAction, nextLocation, {
1844
+ submission,
1845
+ // Send through the formData serialization error if we have one so we can
1846
+ // render at the right error boundary after we match routes
1847
+ pendingError: error,
1848
+ preventScrollReset,
1849
+ replace: opts && opts.replace
1850
+ });
1851
+ } // Revalidate all current loaders. If a navigation is in progress or if this
1852
+ // is interrupted by a navigation, allow this to "succeed" by calling all
1853
+ // loaders during the next loader round
1854
+
1855
+
1856
+ function revalidate() {
1857
+ interruptActiveLoads();
1858
+ updateState({
1859
+ revalidation: "loading"
1860
+ }); // If we're currently submitting an action, we don't need to start a new
1861
+ // navigation, we'll just let the follow up loader execution call all loaders
1862
+
1863
+ if (state.navigation.state === "submitting") {
1864
+ return;
1865
+ } // If we're currently in an idle state, start a new navigation for the current
1866
+ // action/location and mark it as uninterrupted, which will skip the history
1867
+ // update in completeNavigation
1868
+
1869
+
1870
+ if (state.navigation.state === "idle") {
1871
+ startNavigation(state.historyAction, state.location, {
1872
+ startUninterruptedRevalidation: true
1873
+ });
1874
+ return;
1875
+ } // Otherwise, if we're currently in a loading state, just start a new
1876
+ // navigation to the navigation.location but do not trigger an uninterrupted
1877
+ // revalidation so that history correctly updates once the navigation completes
1878
+
1879
+
1880
+ startNavigation(pendingAction || state.historyAction, state.navigation.location, {
1881
+ overrideNavigation: state.navigation
1882
+ });
1883
+ } // Start a navigation to the given action/location. Can optionally provide a
1884
+ // overrideNavigation which will override the normalLoad in the case of a redirect
1885
+ // navigation
1886
+
1887
+
1888
+ async function startNavigation(historyAction, location, opts) {
1889
+ // Abort any in-progress navigations and start a new one. Unset any ongoing
1890
+ // uninterrupted revalidations unless told otherwise, since we want this
1891
+ // new navigation to update history normally
1892
+ pendingNavigationController && pendingNavigationController.abort();
1893
+ pendingNavigationController = null;
1894
+ pendingAction = historyAction;
1895
+ isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true; // Save the current scroll position every time we start a new navigation,
1896
+ // and track whether we should reset scroll on completion
1897
+
1898
+ saveScrollPosition(state.location, state.matches);
1899
+ pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
1900
+ let loadingNavigation = opts && opts.overrideNavigation;
1901
+ let matches = matchRoutes(dataRoutes, location, init.basename); // Short circuit with a 404 on the root error boundary if we match nothing
1902
+
1903
+ if (!matches) {
1904
+ let error = getInternalRouterError(404, {
1905
+ pathname: location.pathname
1906
+ });
1907
+ let {
1908
+ matches: notFoundMatches,
1909
+ route
1910
+ } = getShortCircuitMatches(dataRoutes); // Cancel all pending deferred on 404s since we don't keep any routes
1911
+
1912
+ cancelActiveDeferreds();
1913
+ completeNavigation(location, {
1914
+ matches: notFoundMatches,
1915
+ loaderData: {},
1916
+ errors: {
1917
+ [route.id]: error
1918
+ }
1919
+ });
1920
+ return;
1921
+ } // Short circuit if it's only a hash change and not a mutation submission
1922
+ // For example, on /page#hash and submit a <Form method="post"> which will
1923
+ // default to a navigation to /page
1924
+
1925
+
1926
+ if (isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {
1927
+ completeNavigation(location, {
1928
+ matches
1929
+ });
1930
+ return;
1931
+ } // Create a controller/Request for this navigation
1932
+
1933
+
1934
+ pendingNavigationController = new AbortController();
1935
+ let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);
1936
+ let pendingActionData;
1937
+ let pendingError;
1938
+
1939
+ if (opts && opts.pendingError) {
1940
+ // If we have a pendingError, it means the user attempted a GET submission
1941
+ // with binary FormData so assign here and skip to handleLoaders. That
1942
+ // way we handle calling loaders above the boundary etc. It's not really
1943
+ // different from an actionError in that sense.
1944
+ pendingError = {
1945
+ [findNearestBoundary(matches).route.id]: opts.pendingError
1946
+ };
1947
+ } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {
1948
+ // Call action if we received an action submission
1949
+ let actionOutput = await handleAction(request, location, opts.submission, matches, {
1950
+ replace: opts.replace
1951
+ });
1952
+
1953
+ if (actionOutput.shortCircuited) {
1954
+ return;
1955
+ }
1956
+
1957
+ pendingActionData = actionOutput.pendingActionData;
1958
+ pendingError = actionOutput.pendingActionError;
1959
+
1960
+ let navigation = _extends({
1961
+ state: "loading",
1962
+ location
1963
+ }, opts.submission);
1964
+
1965
+ loadingNavigation = navigation; // Create a GET request for the loaders
1966
+
1967
+ request = new Request(request.url, {
1968
+ signal: request.signal
1969
+ });
1970
+ } // Call loaders
1971
+
1972
+
1973
+ let {
1974
+ shortCircuited,
1975
+ loaderData,
1976
+ errors
1977
+ } = await handleLoaders(request, location, matches, loadingNavigation, opts && opts.submission, opts && opts.replace, pendingActionData, pendingError);
1978
+
1979
+ if (shortCircuited) {
1980
+ return;
1981
+ } // Clean up now that the action/loaders have completed. Don't clean up if
1982
+ // we short circuited because pendingNavigationController will have already
1983
+ // been assigned to a new controller for the next navigation
1984
+
1985
+
1986
+ pendingNavigationController = null;
1987
+ completeNavigation(location, _extends({
1988
+ matches
1989
+ }, pendingActionData ? {
1990
+ actionData: pendingActionData
1991
+ } : {}, {
1992
+ loaderData,
1993
+ errors
1994
+ }));
1995
+ } // Call the action matched by the leaf route for this navigation and handle
1996
+ // redirects/errors
1997
+
1998
+
1999
+ async function handleAction(request, location, submission, matches, opts) {
2000
+ interruptActiveLoads(); // Put us in a submitting state
2001
+
2002
+ let navigation = _extends({
2003
+ state: "submitting",
2004
+ location
2005
+ }, submission);
2006
+
2007
+ updateState({
2008
+ navigation
2009
+ }); // Call our action and get the result
2010
+
2011
+ let result;
2012
+ let actionMatch = getTargetMatch(matches, location);
2013
+
2014
+ if (!actionMatch.route.action) {
2015
+ result = {
2016
+ type: ResultType.error,
2017
+ error: getInternalRouterError(405, {
2018
+ method: request.method,
2019
+ pathname: location.pathname,
2020
+ routeId: actionMatch.route.id
2021
+ })
2022
+ };
2023
+ } else {
2024
+ result = await callLoaderOrAction("action", request, actionMatch, matches, router.basename, future.unstable_middleware);
2025
+
2026
+ if (request.signal.aborted) {
2027
+ return {
2028
+ shortCircuited: true
2029
+ };
2030
+ }
2031
+ }
2032
+
2033
+ if (isRedirectResult(result)) {
2034
+ let replace;
2035
+
2036
+ if (opts && opts.replace != null) {
2037
+ replace = opts.replace;
2038
+ } else {
2039
+ // If the user didn't explicity indicate replace behavior, replace if
2040
+ // we redirected to the exact same location we're currently at to avoid
2041
+ // double back-buttons
2042
+ replace = result.location === state.location.pathname + state.location.search;
2043
+ }
2044
+
2045
+ await startRedirectNavigation(state, result, {
2046
+ submission,
2047
+ replace
2048
+ });
2049
+ return {
2050
+ shortCircuited: true
2051
+ };
2052
+ }
2053
+
2054
+ if (isErrorResult(result)) {
2055
+ // Store off the pending error - we use it to determine which loaders
2056
+ // to call and will commit it when we complete the navigation
2057
+ let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id); // By default, all submissions are REPLACE navigations, but if the
2058
+ // action threw an error that'll be rendered in an errorElement, we fall
2059
+ // back to PUSH so that the user can use the back button to get back to
2060
+ // the pre-submission form location to try again
2061
+
2062
+ if ((opts && opts.replace) !== true) {
2063
+ pendingAction = Action.Push;
2064
+ }
2065
+
2066
+ return {
2067
+ // Send back an empty object we can use to clear out any prior actionData
2068
+ pendingActionData: {},
2069
+ pendingActionError: {
2070
+ [boundaryMatch.route.id]: result.error
2071
+ }
2072
+ };
2073
+ }
2074
+
2075
+ if (isDeferredResult(result)) {
2076
+ throw getInternalRouterError(400, {
2077
+ type: "defer-action"
2078
+ });
2079
+ }
2080
+
2081
+ return {
2082
+ pendingActionData: {
2083
+ [actionMatch.route.id]: result.data
2084
+ }
2085
+ };
2086
+ } // Call all applicable loaders for the given matches, handling redirects,
2087
+ // errors, etc.
2088
+
2089
+
2090
+ async function handleLoaders(request, location, matches, overrideNavigation, submission, replace, pendingActionData, pendingError) {
2091
+ // Figure out the right navigation we want to use for data loading
2092
+ let loadingNavigation = overrideNavigation;
2093
+
2094
+ if (!loadingNavigation) {
2095
+ let navigation = _extends({
2096
+ state: "loading",
2097
+ location,
2098
+ formMethod: undefined,
2099
+ formAction: undefined,
2100
+ formEncType: undefined,
2101
+ formData: undefined
2102
+ }, submission);
2103
+
2104
+ loadingNavigation = navigation;
2105
+ } // If this was a redirect from an action we don't have a "submission" but
2106
+ // we have it on the loading navigation so use that if available
2107
+
2108
+
2109
+ let activeSubmission = submission ? submission : loadingNavigation.formMethod && loadingNavigation.formAction && loadingNavigation.formData && loadingNavigation.formEncType ? {
2110
+ formMethod: loadingNavigation.formMethod,
2111
+ formAction: loadingNavigation.formAction,
2112
+ formData: loadingNavigation.formData,
2113
+ formEncType: loadingNavigation.formEncType
2114
+ } : undefined;
2115
+ let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches); // Cancel pending deferreds for no-longer-matched routes or routes we're
2116
+ // about to reload. Note that if this is an action reload we would have
2117
+ // already cancelled all pending deferreds so this would be a no-op
2118
+
2119
+ cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId)); // Short circuit if we have no loaders to run
2120
+
2121
+ if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {
2122
+ completeNavigation(location, _extends({
2123
+ matches,
2124
+ loaderData: {},
2125
+ // Commit pending error if we're short circuiting
2126
+ errors: pendingError || null
2127
+ }, pendingActionData ? {
2128
+ actionData: pendingActionData
2129
+ } : {}));
2130
+ return {
2131
+ shortCircuited: true
2132
+ };
2133
+ } // If this is an uninterrupted revalidation, we remain in our current idle
2134
+ // state. If not, we need to switch to our loading state and load data,
2135
+ // preserving any new action data or existing action data (in the case of
2136
+ // a revalidation interrupting an actionReload)
2137
+
2138
+
2139
+ if (!isUninterruptedRevalidation) {
2140
+ revalidatingFetchers.forEach(rf => {
2141
+ let fetcher = state.fetchers.get(rf.key);
2142
+ let revalidatingFetcher = {
2143
+ state: "loading",
2144
+ data: fetcher && fetcher.data,
2145
+ formMethod: undefined,
2146
+ formAction: undefined,
2147
+ formEncType: undefined,
2148
+ formData: undefined,
2149
+ " _hasFetcherDoneAnything ": true
2150
+ };
2151
+ state.fetchers.set(rf.key, revalidatingFetcher);
2152
+ });
2153
+ let actionData = pendingActionData || state.actionData;
2154
+ updateState(_extends({
2155
+ navigation: loadingNavigation
2156
+ }, actionData ? Object.keys(actionData).length === 0 ? {
2157
+ actionData: null
2158
+ } : {
2159
+ actionData
2160
+ } : {}, revalidatingFetchers.length > 0 ? {
2161
+ fetchers: new Map(state.fetchers)
2162
+ } : {}));
2163
+ }
2164
+
2165
+ pendingNavigationLoadId = ++incrementingLoadId;
2166
+ revalidatingFetchers.forEach(rf => fetchControllers.set(rf.key, pendingNavigationController));
2167
+ let {
2168
+ results,
2169
+ loaderResults,
2170
+ fetcherResults
2171
+ } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);
2172
+
2173
+ if (request.signal.aborted) {
2174
+ return {
2175
+ shortCircuited: true
2176
+ };
2177
+ } // Clean up _after_ loaders have completed. Don't clean up if we short
2178
+ // circuited because fetchControllers would have been aborted and
2179
+ // reassigned to new controllers for the next navigation
2180
+
2181
+
2182
+ revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key)); // If any loaders returned a redirect Response, start a new REPLACE navigation
2183
+
2184
+ let redirect = findRedirect(results);
2185
+
2186
+ if (redirect) {
2187
+ await startRedirectNavigation(state, redirect, {
2188
+ replace
2189
+ });
2190
+ return {
2191
+ shortCircuited: true
2192
+ };
2193
+ } // Process and commit output from loaders
2194
+
2195
+
2196
+ let {
2197
+ loaderData,
2198
+ errors
2199
+ } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds); // Wire up subscribers to update loaderData as promises settle
2200
+
2201
+ activeDeferreds.forEach((deferredData, routeId) => {
2202
+ deferredData.subscribe(aborted => {
2203
+ // Note: No need to updateState here since the TrackedPromise on
2204
+ // loaderData is stable across resolve/reject
2205
+ // Remove this instance if we were aborted or if promises have settled
2206
+ if (aborted || deferredData.done) {
2207
+ activeDeferreds.delete(routeId);
2208
+ }
2209
+ });
2210
+ });
2211
+ markFetchRedirectsDone();
2212
+ let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);
2213
+ return _extends({
2214
+ loaderData,
2215
+ errors
2216
+ }, didAbortFetchLoads || revalidatingFetchers.length > 0 ? {
2217
+ fetchers: new Map(state.fetchers)
2218
+ } : {});
2219
+ }
2220
+
2221
+ function getFetcher(key) {
2222
+ return state.fetchers.get(key) || IDLE_FETCHER;
2223
+ } // Trigger a fetcher load/submit for the given fetcher key
2224
+
2225
+
2226
+ function fetch(key, routeId, href, opts) {
2227
+ if (isServer) {
2228
+ throw new Error("router.fetch() was called during the server render, but it shouldn't be. " + "You are likely calling a useFetcher() method in the body of your component. " + "Try moving it to a useEffect or a callback.");
2229
+ }
2230
+
2231
+ if (fetchControllers.has(key)) abortFetcher(key);
2232
+ let matches = matchRoutes(dataRoutes, href, init.basename);
2233
+
2234
+ if (!matches) {
2235
+ setFetcherError(key, routeId, getInternalRouterError(404, {
2236
+ pathname: href
2237
+ }));
2238
+ return;
2239
+ }
2240
+
2241
+ let {
2242
+ path,
2243
+ submission
2244
+ } = normalizeNavigateOptions(href, opts, true);
2245
+ let match = getTargetMatch(matches, path);
2246
+ pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;
2247
+
2248
+ if (submission && isMutationMethod(submission.formMethod)) {
2249
+ return handleFetcherAction(key, routeId, path, match, matches, submission);
2250
+ } // Store off the match so we can call it's shouldRevalidate on subsequent
2251
+ // revalidations
2252
+
2253
+
2254
+ fetchLoadMatches.set(key, {
2255
+ routeId,
2256
+ path,
2257
+ match,
2258
+ matches
2259
+ });
2260
+ return handleFetcherLoader(key, routeId, path, match, matches, submission);
2261
+ } // Call the action for the matched fetcher.submit(), and then handle redirects,
2262
+ // errors, and revalidation
2263
+
2264
+
2265
+ async function handleFetcherAction(key, routeId, path, match, requestMatches, submission) {
2266
+ interruptActiveLoads();
2267
+ fetchLoadMatches.delete(key);
2268
+
2269
+ if (!match.route.action) {
2270
+ let error = getInternalRouterError(405, {
2271
+ method: submission.formMethod,
2272
+ pathname: path,
2273
+ routeId: routeId
2274
+ });
2275
+ setFetcherError(key, routeId, error);
2276
+ return;
2277
+ } // Put this fetcher into it's submitting state
2278
+
2279
+
2280
+ let existingFetcher = state.fetchers.get(key);
2281
+
2282
+ let fetcher = _extends({
2283
+ state: "submitting"
2284
+ }, submission, {
2285
+ data: existingFetcher && existingFetcher.data,
2286
+ " _hasFetcherDoneAnything ": true
2287
+ });
2288
+
2289
+ state.fetchers.set(key, fetcher);
2290
+ updateState({
2291
+ fetchers: new Map(state.fetchers)
2292
+ }); // Call the action for the fetcher
2293
+
2294
+ let abortController = new AbortController();
2295
+ let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);
2296
+ fetchControllers.set(key, abortController);
2297
+ let actionResult = await callLoaderOrAction("action", fetchRequest, match, requestMatches, router.basename, future.unstable_middleware);
2298
+
2299
+ if (fetchRequest.signal.aborted) {
2300
+ // We can delete this so long as we weren't aborted by ou our own fetcher
2301
+ // re-submit which would have put _new_ controller is in fetchControllers
2302
+ if (fetchControllers.get(key) === abortController) {
2303
+ fetchControllers.delete(key);
2304
+ }
2305
+
2306
+ return;
2307
+ }
2308
+
2309
+ if (isRedirectResult(actionResult)) {
2310
+ fetchControllers.delete(key);
2311
+ fetchRedirectIds.add(key);
2312
+
2313
+ let loadingFetcher = _extends({
2314
+ state: "loading"
2315
+ }, submission, {
2316
+ data: undefined,
2317
+ " _hasFetcherDoneAnything ": true
2318
+ });
2319
+
2320
+ state.fetchers.set(key, loadingFetcher);
2321
+ updateState({
2322
+ fetchers: new Map(state.fetchers)
2323
+ });
2324
+ return startRedirectNavigation(state, actionResult, {
2325
+ isFetchActionRedirect: true
2326
+ });
2327
+ } // Process any non-redirect errors thrown
2328
+
2329
+
2330
+ if (isErrorResult(actionResult)) {
2331
+ setFetcherError(key, routeId, actionResult.error);
2332
+ return;
2333
+ }
2334
+
2335
+ if (isDeferredResult(actionResult)) {
2336
+ throw getInternalRouterError(400, {
2337
+ type: "defer-action"
2338
+ });
2339
+ } // Start the data load for current matches, or the next location if we're
2340
+ // in the middle of a navigation
2341
+
2342
+
2343
+ let nextLocation = state.navigation.location || state.location;
2344
+ let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);
2345
+ let matches = state.navigation.state !== "idle" ? matchRoutes(dataRoutes, state.navigation.location, init.basename) : state.matches;
2346
+ invariant(matches, "Didn't find any matches after fetcher action");
2347
+ let loadId = ++incrementingLoadId;
2348
+ fetchReloadIds.set(key, loadId);
2349
+
2350
+ let loadFetcher = _extends({
2351
+ state: "loading",
2352
+ data: actionResult.data
2353
+ }, submission, {
2354
+ " _hasFetcherDoneAnything ": true
2355
+ });
2356
+
2357
+ state.fetchers.set(key, loadFetcher);
2358
+ let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, {
2359
+ [match.route.id]: actionResult.data
2360
+ }, undefined, // No need to send through errors since we short circuit above
2361
+ fetchLoadMatches); // Put all revalidating fetchers into the loading state, except for the
2362
+ // current fetcher which we want to keep in it's current loading state which
2363
+ // contains it's action submission info + action data
2364
+
2365
+ revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {
2366
+ let staleKey = rf.key;
2367
+ let existingFetcher = state.fetchers.get(staleKey);
2368
+ let revalidatingFetcher = {
2369
+ state: "loading",
2370
+ data: existingFetcher && existingFetcher.data,
2371
+ formMethod: undefined,
2372
+ formAction: undefined,
2373
+ formEncType: undefined,
2374
+ formData: undefined,
2375
+ " _hasFetcherDoneAnything ": true
2376
+ };
2377
+ state.fetchers.set(staleKey, revalidatingFetcher);
2378
+ fetchControllers.set(staleKey, abortController);
2379
+ });
2380
+ updateState({
2381
+ fetchers: new Map(state.fetchers)
2382
+ });
2383
+ let {
2384
+ results,
2385
+ loaderResults,
2386
+ fetcherResults
2387
+ } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);
2388
+
2389
+ if (abortController.signal.aborted) {
2390
+ return;
2391
+ }
2392
+
2393
+ fetchReloadIds.delete(key);
2394
+ fetchControllers.delete(key);
2395
+ revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));
2396
+ let redirect = findRedirect(results);
2397
+
2398
+ if (redirect) {
2399
+ return startRedirectNavigation(state, redirect);
2400
+ } // Process and commit output from loaders
2401
+
2402
+
2403
+ let {
2404
+ loaderData,
2405
+ errors
2406
+ } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);
2407
+ let doneFetcher = {
2408
+ state: "idle",
2409
+ data: actionResult.data,
2410
+ formMethod: undefined,
2411
+ formAction: undefined,
2412
+ formEncType: undefined,
2413
+ formData: undefined,
2414
+ " _hasFetcherDoneAnything ": true
2415
+ };
2416
+ state.fetchers.set(key, doneFetcher);
2417
+ let didAbortFetchLoads = abortStaleFetchLoads(loadId); // If we are currently in a navigation loading state and this fetcher is
2418
+ // more recent than the navigation, we want the newer data so abort the
2419
+ // navigation and complete it with the fetcher data
2420
+
2421
+ if (state.navigation.state === "loading" && loadId > pendingNavigationLoadId) {
2422
+ invariant(pendingAction, "Expected pending action");
2423
+ pendingNavigationController && pendingNavigationController.abort();
2424
+ completeNavigation(state.navigation.location, {
2425
+ matches,
2426
+ loaderData,
2427
+ errors,
2428
+ fetchers: new Map(state.fetchers)
2429
+ });
2430
+ } else {
2431
+ // otherwise just update with the fetcher data, preserving any existing
2432
+ // loaderData for loaders that did not need to reload. We have to
2433
+ // manually merge here since we aren't going through completeNavigation
2434
+ updateState(_extends({
2435
+ errors,
2436
+ loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors)
2437
+ }, didAbortFetchLoads ? {
2438
+ fetchers: new Map(state.fetchers)
2439
+ } : {}));
2440
+ isRevalidationRequired = false;
2441
+ }
2442
+ } // Call the matched loader for fetcher.load(), handling redirects, errors, etc.
2443
+
2444
+
2445
+ async function handleFetcherLoader(key, routeId, path, match, matches, submission) {
2446
+ let existingFetcher = state.fetchers.get(key); // Put this fetcher into it's loading state
2447
+
2448
+ let loadingFetcher = _extends({
2449
+ state: "loading",
2450
+ formMethod: undefined,
2451
+ formAction: undefined,
2452
+ formEncType: undefined,
2453
+ formData: undefined
2454
+ }, submission, {
2455
+ data: existingFetcher && existingFetcher.data,
2456
+ " _hasFetcherDoneAnything ": true
2457
+ });
2458
+
2459
+ state.fetchers.set(key, loadingFetcher);
2460
+ updateState({
2461
+ fetchers: new Map(state.fetchers)
2462
+ }); // Call the loader for this fetcher route match
2463
+
2464
+ let abortController = new AbortController();
2465
+ let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);
2466
+ fetchControllers.set(key, abortController);
2467
+ let result = await callLoaderOrAction("loader", fetchRequest, match, matches, router.basename, future.unstable_middleware); // Deferred isn't supported for fetcher loads, await everything and treat it
2468
+ // as a normal load. resolveDeferredData will return undefined if this
2469
+ // fetcher gets aborted, so we just leave result untouched and short circuit
2470
+ // below if that happens
2471
+
2472
+ if (isDeferredResult(result)) {
2473
+ result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;
2474
+ } // We can delete this so long as we weren't aborted by ou our own fetcher
2475
+ // re-load which would have put _new_ controller is in fetchControllers
2476
+
2477
+
2478
+ if (fetchControllers.get(key) === abortController) {
2479
+ fetchControllers.delete(key);
2480
+ }
2481
+
2482
+ if (fetchRequest.signal.aborted) {
2483
+ return;
2484
+ } // If the loader threw a redirect Response, start a new REPLACE navigation
2485
+
2486
+
2487
+ if (isRedirectResult(result)) {
2488
+ await startRedirectNavigation(state, result);
2489
+ return;
2490
+ } // Process any non-redirect errors thrown
2491
+
2492
+
2493
+ if (isErrorResult(result)) {
2494
+ let boundaryMatch = findNearestBoundary(state.matches, routeId);
2495
+ state.fetchers.delete(key); // TODO: In remix, this would reset to IDLE_NAVIGATION if it was a catch -
2496
+ // do we need to behave any differently with our non-redirect errors?
2497
+ // What if it was a non-redirect Response?
2498
+
2499
+ updateState({
2500
+ fetchers: new Map(state.fetchers),
2501
+ errors: {
2502
+ [boundaryMatch.route.id]: result.error
2503
+ }
2504
+ });
2505
+ return;
2506
+ }
2507
+
2508
+ invariant(!isDeferredResult(result), "Unhandled fetcher deferred data"); // Put the fetcher back into an idle state
2509
+
2510
+ let doneFetcher = {
2511
+ state: "idle",
2512
+ data: result.data,
2513
+ formMethod: undefined,
2514
+ formAction: undefined,
2515
+ formEncType: undefined,
2516
+ formData: undefined,
2517
+ " _hasFetcherDoneAnything ": true
2518
+ };
2519
+ state.fetchers.set(key, doneFetcher);
2520
+ updateState({
2521
+ fetchers: new Map(state.fetchers)
2522
+ });
2523
+ }
2524
+ /**
2525
+ * Utility function to handle redirects returned from an action or loader.
2526
+ * Normally, a redirect "replaces" the navigation that triggered it. So, for
2527
+ * example:
2528
+ *
2529
+ * - user is on /a
2530
+ * - user clicks a link to /b
2531
+ * - loader for /b redirects to /c
2532
+ *
2533
+ * In a non-JS app the browser would track the in-flight navigation to /b and
2534
+ * then replace it with /c when it encountered the redirect response. In
2535
+ * the end it would only ever update the URL bar with /c.
2536
+ *
2537
+ * In client-side routing using pushState/replaceState, we aim to emulate
2538
+ * this behavior and we also do not update history until the end of the
2539
+ * navigation (including processed redirects). This means that we never
2540
+ * actually touch history until we've processed redirects, so we just use
2541
+ * the history action from the original navigation (PUSH or REPLACE).
2542
+ */
2543
+
2544
+
2545
+ async function startRedirectNavigation(state, redirect, _temp) {
2546
+ var _window;
2547
+
2548
+ let {
2549
+ submission,
2550
+ replace,
2551
+ isFetchActionRedirect
2552
+ } = _temp === void 0 ? {} : _temp;
2553
+
2554
+ if (redirect.revalidate) {
2555
+ isRevalidationRequired = true;
2556
+ }
2557
+
2558
+ let redirectLocation = createLocation(state.location, redirect.location, // TODO: This can be removed once we get rid of useTransition in Remix v2
2559
+ _extends({
2560
+ _isRedirect: true
2561
+ }, isFetchActionRedirect ? {
2562
+ _isFetchActionRedirect: true
2563
+ } : {}));
2564
+ invariant(redirectLocation, "Expected a location on the redirect navigation"); // Check if this an absolute external redirect that goes to a new origin
2565
+
2566
+ if (ABSOLUTE_URL_REGEX.test(redirect.location) && isBrowser && typeof ((_window = window) == null ? void 0 : _window.location) !== "undefined") {
2567
+ let newOrigin = init.history.createURL(redirect.location).origin;
2568
+
2569
+ if (window.location.origin !== newOrigin) {
2570
+ if (replace) {
2571
+ window.location.replace(redirect.location);
2572
+ } else {
2573
+ window.location.assign(redirect.location);
2574
+ }
2575
+
2576
+ return;
2577
+ }
2578
+ } // There's no need to abort on redirects, since we don't detect the
2579
+ // redirect until the action/loaders have settled
2580
+
2581
+
2582
+ pendingNavigationController = null;
2583
+ let redirectHistoryAction = replace === true ? Action.Replace : Action.Push; // Use the incoming submission if provided, fallback on the active one in
2584
+ // state.navigation
2585
+
2586
+ let {
2587
+ formMethod,
2588
+ formAction,
2589
+ formEncType,
2590
+ formData
2591
+ } = state.navigation;
2592
+
2593
+ if (!submission && formMethod && formAction && formData && formEncType) {
2594
+ submission = {
2595
+ formMethod,
2596
+ formAction,
2597
+ formEncType,
2598
+ formData
2599
+ };
2600
+ } // If this was a 307/308 submission we want to preserve the HTTP method and
2601
+ // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the
2602
+ // redirected location
2603
+
2604
+
2605
+ if (redirectPreserveMethodStatusCodes.has(redirect.status) && submission && isMutationMethod(submission.formMethod)) {
2606
+ await startNavigation(redirectHistoryAction, redirectLocation, {
2607
+ submission: _extends({}, submission, {
2608
+ formAction: redirect.location
2609
+ }),
2610
+ // Preserve this flag across redirects
2611
+ preventScrollReset: pendingPreventScrollReset
2612
+ });
2613
+ } else {
2614
+ // Otherwise, we kick off a new loading navigation, preserving the
2615
+ // submission info for the duration of this navigation
2616
+ await startNavigation(redirectHistoryAction, redirectLocation, {
2617
+ overrideNavigation: {
2618
+ state: "loading",
2619
+ location: redirectLocation,
2620
+ formMethod: submission ? submission.formMethod : undefined,
2621
+ formAction: submission ? submission.formAction : undefined,
2622
+ formEncType: submission ? submission.formEncType : undefined,
2623
+ formData: submission ? submission.formData : undefined
2624
+ },
2625
+ // Preserve this flag across redirects
2626
+ preventScrollReset: pendingPreventScrollReset
2627
+ });
2628
+ }
2629
+ }
2630
+
2631
+ async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {
2632
+ // Call all navigation loaders and revalidating fetcher loaders in parallel,
2633
+ // then slice off the results into separate arrays so we can handle them
2634
+ // accordingly
2635
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, router.basename, future.unstable_middleware)), ...fetchersToLoad.map(f => callLoaderOrAction("loader", createClientSideRequest(init.history, f.path, request.signal), f.match, f.matches, router.basename, future.unstable_middleware))]);
2636
+ let loaderResults = results.slice(0, matchesToLoad.length);
2637
+ let fetcherResults = results.slice(matchesToLoad.length);
2638
+ await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, request.signal, false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, request.signal, true)]);
2639
+ return {
2640
+ results,
2641
+ loaderResults,
2642
+ fetcherResults
2643
+ };
2644
+ }
2645
+
2646
+ function interruptActiveLoads() {
2647
+ // Every interruption triggers a revalidation
2648
+ isRevalidationRequired = true; // Cancel pending route-level deferreds and mark cancelled routes for
2649
+ // revalidation
2650
+
2651
+ cancelledDeferredRoutes.push(...cancelActiveDeferreds()); // Abort in-flight fetcher loads
2652
+
2653
+ fetchLoadMatches.forEach((_, key) => {
2654
+ if (fetchControllers.has(key)) {
2655
+ cancelledFetcherLoads.push(key);
2656
+ abortFetcher(key);
2657
+ }
2658
+ });
2659
+ }
2660
+
2661
+ function setFetcherError(key, routeId, error) {
2662
+ let boundaryMatch = findNearestBoundary(state.matches, routeId);
2663
+ deleteFetcher(key);
2664
+ updateState({
2665
+ errors: {
2666
+ [boundaryMatch.route.id]: error
2667
+ },
2668
+ fetchers: new Map(state.fetchers)
2669
+ });
2670
+ }
2671
+
2672
+ function deleteFetcher(key) {
2673
+ if (fetchControllers.has(key)) abortFetcher(key);
2674
+ fetchLoadMatches.delete(key);
2675
+ fetchReloadIds.delete(key);
2676
+ fetchRedirectIds.delete(key);
2677
+ state.fetchers.delete(key);
2678
+ }
2679
+
2680
+ function abortFetcher(key) {
2681
+ let controller = fetchControllers.get(key);
2682
+ invariant(controller, "Expected fetch controller: " + key);
2683
+ controller.abort();
2684
+ fetchControllers.delete(key);
2685
+ }
2686
+
2687
+ function markFetchersDone(keys) {
2688
+ for (let key of keys) {
2689
+ let fetcher = getFetcher(key);
2690
+ let doneFetcher = {
2691
+ state: "idle",
2692
+ data: fetcher.data,
2693
+ formMethod: undefined,
2694
+ formAction: undefined,
2695
+ formEncType: undefined,
2696
+ formData: undefined,
2697
+ " _hasFetcherDoneAnything ": true
2698
+ };
2699
+ state.fetchers.set(key, doneFetcher);
2700
+ }
2701
+ }
2702
+
2703
+ function markFetchRedirectsDone() {
2704
+ let doneKeys = [];
2705
+
2706
+ for (let key of fetchRedirectIds) {
2707
+ let fetcher = state.fetchers.get(key);
2708
+ invariant(fetcher, "Expected fetcher: " + key);
2709
+
2710
+ if (fetcher.state === "loading") {
2711
+ fetchRedirectIds.delete(key);
2712
+ doneKeys.push(key);
2713
+ }
2714
+ }
2715
+
2716
+ markFetchersDone(doneKeys);
2717
+ }
2718
+
2719
+ function abortStaleFetchLoads(landedId) {
2720
+ let yeetedKeys = [];
2721
+
2722
+ for (let [key, id] of fetchReloadIds) {
2723
+ if (id < landedId) {
2724
+ let fetcher = state.fetchers.get(key);
2725
+ invariant(fetcher, "Expected fetcher: " + key);
2726
+
2727
+ if (fetcher.state === "loading") {
2728
+ abortFetcher(key);
2729
+ fetchReloadIds.delete(key);
2730
+ yeetedKeys.push(key);
2731
+ }
2732
+ }
2733
+ }
2734
+
2735
+ markFetchersDone(yeetedKeys);
2736
+ return yeetedKeys.length > 0;
2737
+ }
2738
+
2739
+ function getBlocker(key, fn) {
2740
+ let blocker = state.blockers.get(key) || IDLE_BLOCKER;
2741
+
2742
+ if (blockerFunctions.get(key) !== fn) {
2743
+ blockerFunctions.set(key, fn);
2744
+ }
2745
+
2746
+ return blocker;
2747
+ }
2748
+
2749
+ function deleteBlocker(key) {
2750
+ state.blockers.delete(key);
2751
+ blockerFunctions.delete(key);
2752
+ } // Utility function to update blockers, ensuring valid state transitions
2753
+
2754
+
2755
+ function updateBlocker(key, newBlocker) {
2756
+ let blocker = state.blockers.get(key) || IDLE_BLOCKER; // Poor mans state machine :)
2757
+ // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM
2758
+
2759
+ invariant(blocker.state === "unblocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "blocked" || blocker.state === "blocked" && newBlocker.state === "proceeding" || blocker.state === "blocked" && newBlocker.state === "unblocked" || blocker.state === "proceeding" && newBlocker.state === "unblocked", "Invalid blocker state transition: " + blocker.state + " -> " + newBlocker.state);
2760
+ state.blockers.set(key, newBlocker);
2761
+ updateState({
2762
+ blockers: new Map(state.blockers)
2763
+ });
2764
+ }
2765
+
2766
+ function shouldBlockNavigation(_ref2) {
2767
+ let {
2768
+ currentLocation,
2769
+ nextLocation,
2770
+ historyAction
2771
+ } = _ref2;
2772
+
2773
+ if (blockerFunctions.size === 0) {
2774
+ return;
2775
+ } // We ony support a single active blocker at the moment since we don't have
2776
+ // any compelling use cases for multi-blocker yet
2777
+
2778
+
2779
+ if (blockerFunctions.size > 1) {
2780
+ warning(false, "A router only supports one blocker at a time");
2781
+ }
2782
+
2783
+ let entries = Array.from(blockerFunctions.entries());
2784
+ let [blockerKey, blockerFunction] = entries[entries.length - 1];
2785
+ let blocker = state.blockers.get(blockerKey);
2786
+
2787
+ if (blocker && blocker.state === "proceeding") {
2788
+ // If the blocker is currently proceeding, we don't need to re-check
2789
+ // it and can let this navigation continue
2790
+ return;
2791
+ } // At this point, we know we're unblocked/blocked so we need to check the
2792
+ // user-provided blocker function
2793
+
2794
+
2795
+ if (blockerFunction({
2796
+ currentLocation,
2797
+ nextLocation,
2798
+ historyAction
2799
+ })) {
2800
+ return blockerKey;
2801
+ }
2802
+ }
2803
+
2804
+ function cancelActiveDeferreds(predicate) {
2805
+ let cancelledRouteIds = [];
2806
+ activeDeferreds.forEach((dfd, routeId) => {
2807
+ if (!predicate || predicate(routeId)) {
2808
+ // Cancel the deferred - but do not remove from activeDeferreds here -
2809
+ // we rely on the subscribers to do that so our tests can assert proper
2810
+ // cleanup via _internalActiveDeferreds
2811
+ dfd.cancel();
2812
+ cancelledRouteIds.push(routeId);
2813
+ activeDeferreds.delete(routeId);
2814
+ }
2815
+ });
2816
+ return cancelledRouteIds;
2817
+ } // Opt in to capturing and reporting scroll positions during navigations,
2818
+ // used by the <ScrollRestoration> component
2819
+
2820
+
2821
+ function enableScrollRestoration(positions, getPosition, getKey) {
2822
+ savedScrollPositions = positions;
2823
+ getScrollPosition = getPosition;
2824
+
2825
+ getScrollRestorationKey = getKey || (location => location.key); // Perform initial hydration scroll restoration, since we miss the boat on
2826
+ // the initial updateState() because we've not yet rendered <ScrollRestoration/>
2827
+ // and therefore have no savedScrollPositions available
2828
+
2829
+
2830
+ if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {
2831
+ initialScrollRestored = true;
2832
+ let y = getSavedScrollPosition(state.location, state.matches);
2833
+
2834
+ if (y != null) {
2835
+ updateState({
2836
+ restoreScrollPosition: y
2837
+ });
2838
+ }
2839
+ }
2840
+
2841
+ return () => {
2842
+ savedScrollPositions = null;
2843
+ getScrollPosition = null;
2844
+ getScrollRestorationKey = null;
2845
+ };
2846
+ }
2847
+
2848
+ function saveScrollPosition(location, matches) {
2849
+ if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
2850
+ let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
2851
+ let key = getScrollRestorationKey(location, userMatches) || location.key;
2852
+ savedScrollPositions[key] = getScrollPosition();
2853
+ }
2854
+ }
2855
+
2856
+ function getSavedScrollPosition(location, matches) {
2857
+ if (savedScrollPositions && getScrollRestorationKey && getScrollPosition) {
2858
+ let userMatches = matches.map(m => createUseMatchesMatch(m, state.loaderData));
2859
+ let key = getScrollRestorationKey(location, userMatches) || location.key;
2860
+ let y = savedScrollPositions[key];
2861
+
2862
+ if (typeof y === "number") {
2863
+ return y;
2864
+ }
2865
+ }
2866
+
2867
+ return null;
2868
+ }
2869
+
2870
+ router = {
2871
+ get basename() {
2872
+ return init.basename;
2873
+ },
2874
+
2875
+ get state() {
2876
+ return state;
2877
+ },
2878
+
2879
+ get routes() {
2880
+ return dataRoutes;
2881
+ },
2882
+
2883
+ initialize,
2884
+ subscribe,
2885
+ enableScrollRestoration,
2886
+ navigate,
2887
+ fetch,
2888
+ revalidate,
2889
+ // Passthrough to history-aware createHref used by useHref so we get proper
2890
+ // hash-aware URLs in DOM paths
2891
+ createHref: to => init.history.createHref(to),
2892
+ encodeLocation: to => init.history.encodeLocation(to),
2893
+ getFetcher,
2894
+ deleteFetcher,
2895
+ dispose,
2896
+ getBlocker,
2897
+ deleteBlocker,
2898
+ _internalFetchControllers: fetchControllers,
2899
+ _internalActiveDeferreds: activeDeferreds
2900
+ };
2901
+ return router;
2902
+ } //#endregion
2903
+ ////////////////////////////////////////////////////////////////////////////////
2904
+ //#region createStaticHandler
2905
+ ////////////////////////////////////////////////////////////////////////////////
2906
+
2907
+ const UNSAFE_DEFERRED_SYMBOL = Symbol("deferred");
2908
+ function createStaticHandler(routes, init) {
2909
+ invariant(routes.length > 0, "You must provide a non-empty routes array to createStaticHandler");
2910
+ let dataRoutes = convertRoutesToDataRoutes(routes);
2911
+ let basename = (init ? init.basename : null) || "/";
2912
+
2913
+ let future = _extends({}, defaultFutureConfig, init && init.future ? init.future : null);
2914
+ /**
2915
+ * The query() method is intended for document requests, in which we want to
2916
+ * call an optional action and potentially multiple loaders for all nested
2917
+ * routes. It returns a StaticHandlerContext object, which is very similar
2918
+ * to the router state (location, loaderData, actionData, errors, etc.) and
2919
+ * also adds SSR-specific information such as the statusCode and headers
2920
+ * from action/loaders Responses.
2921
+ *
2922
+ * It _should_ never throw and should report all errors through the
2923
+ * returned context.errors object, properly associating errors to their error
2924
+ * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be
2925
+ * used to emulate React error boundaries during SSr by performing a second
2926
+ * pass only down to the boundaryId.
2927
+ *
2928
+ * The one exception where we do not return a StaticHandlerContext is when a
2929
+ * redirect response is returned or thrown from any action/loader. We
2930
+ * propagate that out and return the raw Response so the HTTP server can
2931
+ * return it directly.
2932
+ */
2933
+
2934
+
2935
+ async function query(request, _temp2) {
2936
+ let {
2937
+ requestContext,
2938
+ middlewareContext
2939
+ } = _temp2 === void 0 ? {} : _temp2;
2940
+ let url = new URL(request.url);
2941
+ let method = request.method.toLowerCase();
2942
+ let location = createLocation("", createPath(url), null, "default");
2943
+ let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't
2944
+
2945
+ if (!isValidMethod(method) && method !== "head") {
2946
+ let error = getInternalRouterError(405, {
2947
+ method
2948
+ });
2949
+ let {
2950
+ matches: methodNotAllowedMatches,
2951
+ route
2952
+ } = getShortCircuitMatches(dataRoutes);
2953
+ return {
2954
+ basename,
2955
+ location,
2956
+ matches: methodNotAllowedMatches,
2957
+ loaderData: {},
2958
+ actionData: null,
2959
+ errors: {
2960
+ [route.id]: error
2961
+ },
2962
+ statusCode: error.status,
2963
+ loaderHeaders: {},
2964
+ actionHeaders: {},
2965
+ activeDeferreds: null
2966
+ };
2967
+ } else if (!matches) {
2968
+ let error = getInternalRouterError(404, {
2969
+ pathname: location.pathname
2970
+ });
2971
+ let {
2972
+ matches: notFoundMatches,
2973
+ route
2974
+ } = getShortCircuitMatches(dataRoutes);
2975
+ return {
2976
+ basename,
2977
+ location,
2978
+ matches: notFoundMatches,
2979
+ loaderData: {},
2980
+ actionData: null,
2981
+ errors: {
2982
+ [route.id]: error
2983
+ },
2984
+ statusCode: error.status,
2985
+ loaderHeaders: {},
2986
+ actionHeaders: {},
2987
+ activeDeferreds: null
2988
+ };
2989
+ }
2990
+
2991
+ let result = await queryImpl(request, location, matches, requestContext, middlewareContext);
2992
+
2993
+ if (isResponse(result)) {
2994
+ return result;
2995
+ } // When returning StaticHandlerContext, we patch back in the location here
2996
+ // since we need it for React Context. But this helps keep our submit and
2997
+ // loadRouteData operating on a Request instead of a Location
2998
+
2999
+
3000
+ return _extends({
3001
+ location,
3002
+ basename
3003
+ }, result);
3004
+ }
3005
+ /**
3006
+ * The queryRoute() method is intended for targeted route requests, either
3007
+ * for fetch ?_data requests or resource route requests. In this case, we
3008
+ * are only ever calling a single action or loader, and we are returning the
3009
+ * returned value directly. In most cases, this will be a Response returned
3010
+ * from the action/loader, but it may be a primitive or other value as well -
3011
+ * and in such cases the calling context should handle that accordingly.
3012
+ *
3013
+ * We do respect the throw/return differentiation, so if an action/loader
3014
+ * throws, then this method will throw the value. This is important so we
3015
+ * can do proper boundary identification in Remix where a thrown Response
3016
+ * must go to the Catch Boundary but a returned Response is happy-path.
3017
+ *
3018
+ * One thing to note is that any Router-initiated Errors that make sense
3019
+ * to associate with a status code will be thrown as an ErrorResponse
3020
+ * instance which include the raw Error, such that the calling context can
3021
+ * serialize the error as they see fit while including the proper response
3022
+ * code. Examples here are 404 and 405 errors that occur prior to reaching
3023
+ * any user-defined loaders.
3024
+ */
3025
+
3026
+
3027
+ async function queryRoute(request, _temp3) {
3028
+ let {
3029
+ routeId,
3030
+ requestContext,
3031
+ middlewareContext
3032
+ } = _temp3 === void 0 ? {} : _temp3;
3033
+ let url = new URL(request.url);
3034
+ let method = request.method.toLowerCase();
3035
+ let location = createLocation("", createPath(url), null, "default");
3036
+ let matches = matchRoutes(dataRoutes, location, basename); // SSR supports HEAD requests while SPA doesn't
3037
+
3038
+ if (!isValidMethod(method) && method !== "head" && method !== "options") {
3039
+ throw getInternalRouterError(405, {
3040
+ method
3041
+ });
3042
+ } else if (!matches) {
3043
+ throw getInternalRouterError(404, {
3044
+ pathname: location.pathname
3045
+ });
3046
+ }
3047
+
3048
+ let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);
3049
+
3050
+ if (routeId && !match) {
3051
+ throw getInternalRouterError(403, {
3052
+ pathname: location.pathname,
3053
+ routeId
3054
+ });
3055
+ } else if (!match) {
3056
+ // This should never hit I don't think?
3057
+ throw getInternalRouterError(404, {
3058
+ pathname: location.pathname
3059
+ });
3060
+ }
3061
+
3062
+ let result = await queryImpl(request, location, matches, requestContext, middlewareContext, match);
3063
+
3064
+ if (isResponse(result)) {
3065
+ return result;
3066
+ }
3067
+
3068
+ let error = result.errors ? Object.values(result.errors)[0] : undefined;
3069
+
3070
+ if (error !== undefined) {
3071
+ // If we got back result.errors, that means the loader/action threw
3072
+ // _something_ that wasn't a Response, but it's not guaranteed/required
3073
+ // to be an `instanceof Error` either, so we have to use throw here to
3074
+ // preserve the "error" state outside of queryImpl.
3075
+ throw error;
3076
+ } // Pick off the right state value to return
3077
+
3078
+
3079
+ if (result.actionData) {
3080
+ return Object.values(result.actionData)[0];
3081
+ }
3082
+
3083
+ if (result.loaderData) {
3084
+ var _result$activeDeferre;
3085
+
3086
+ let data = Object.values(result.loaderData)[0];
3087
+
3088
+ if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {
3089
+ data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];
3090
+ }
3091
+
3092
+ return data;
3093
+ }
3094
+
3095
+ return undefined;
3096
+ }
3097
+
3098
+ async function queryImpl(request, location, matches, requestContext, middlewareContext, routeMatch) {
3099
+ invariant(request.signal, "query()/queryRoute() requests must contain an AbortController signal");
3100
+
3101
+ try {
3102
+ if (isMutationMethod(request.method.toLowerCase())) {
3103
+ let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, middlewareContext, routeMatch != null);
3104
+ return result;
3105
+ }
3106
+
3107
+ let result = await loadRouteData(request, matches, requestContext, middlewareContext, routeMatch);
3108
+ return isResponse(result) ? result : _extends({}, result, {
3109
+ actionData: null,
3110
+ actionHeaders: {}
3111
+ });
3112
+ } catch (e) {
3113
+ // If the user threw/returned a Response in callLoaderOrAction, we throw
3114
+ // it to bail out and then return or throw here based on whether the user
3115
+ // returned or threw
3116
+ if (isQueryRouteResponse(e)) {
3117
+ if (e.type === ResultType.error && !isRedirectResponse(e.response)) {
3118
+ throw e.response;
3119
+ }
3120
+
3121
+ return e.response;
3122
+ } // Redirects are always returned since they don't propagate to catch
3123
+ // boundaries
3124
+
3125
+
3126
+ if (isRedirectResponse(e)) {
3127
+ return e;
3128
+ }
3129
+
3130
+ throw e;
3131
+ }
3132
+ }
3133
+
3134
+ async function submit(request, matches, actionMatch, requestContext, middlewareContext, isRouteRequest) {
3135
+ let result;
3136
+
3137
+ if (!actionMatch.route.action) {
3138
+ let error = getInternalRouterError(405, {
3139
+ method: request.method,
3140
+ pathname: new URL(request.url).pathname,
3141
+ routeId: actionMatch.route.id
3142
+ });
3143
+
3144
+ if (isRouteRequest) {
3145
+ throw error;
3146
+ }
3147
+
3148
+ result = {
3149
+ type: ResultType.error,
3150
+ error
3151
+ };
3152
+ } else {
3153
+ result = await callLoaderOrAction("action", request, actionMatch, matches, basename, future.unstable_middleware, true, isRouteRequest, requestContext, middlewareContext);
3154
+
3155
+ if (request.signal.aborted) {
3156
+ let method = isRouteRequest ? "queryRoute" : "query";
3157
+ throw new Error(method + "() call aborted");
3158
+ }
3159
+ }
3160
+
3161
+ if (isRedirectResult(result)) {
3162
+ // Uhhhh - this should never happen, we should always throw these from
3163
+ // callLoaderOrAction, but the type narrowing here keeps TS happy and we
3164
+ // can get back on the "throw all redirect responses" train here should
3165
+ // this ever happen :/
3166
+ throw new Response(null, {
3167
+ status: result.status,
3168
+ headers: {
3169
+ Location: result.location
3170
+ }
3171
+ });
3172
+ }
3173
+
3174
+ if (isDeferredResult(result)) {
3175
+ let error = getInternalRouterError(400, {
3176
+ type: "defer-action"
3177
+ });
3178
+
3179
+ if (isRouteRequest) {
3180
+ throw error;
3181
+ }
3182
+
3183
+ result = {
3184
+ type: ResultType.error,
3185
+ error
3186
+ };
3187
+ }
3188
+
3189
+ if (isRouteRequest) {
3190
+ // Note: This should only be non-Response values if we get here, since
3191
+ // isRouteRequest should throw any Response received in callLoaderOrAction
3192
+ if (isErrorResult(result)) {
3193
+ throw result.error;
3194
+ }
3195
+
3196
+ return {
3197
+ matches: [actionMatch],
3198
+ loaderData: {},
3199
+ actionData: {
3200
+ [actionMatch.route.id]: result.data
3201
+ },
3202
+ errors: null,
3203
+ // Note: statusCode + headers are unused here since queryRoute will
3204
+ // return the raw Response or value
3205
+ statusCode: 200,
3206
+ loaderHeaders: {},
3207
+ actionHeaders: {},
3208
+ activeDeferreds: null
3209
+ };
3210
+ }
3211
+
3212
+ if (isErrorResult(result)) {
3213
+ // Store off the pending error - we use it to determine which loaders
3214
+ // to call and will commit it when we complete the navigation
3215
+ let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);
3216
+ let context = await loadRouteData(request, matches, requestContext, middlewareContext, undefined, {
3217
+ [boundaryMatch.route.id]: result.error
3218
+ }); // action status codes take precedence over loader status codes
3219
+
3220
+ return _extends({}, context, {
3221
+ statusCode: isRouteErrorResponse(result.error) ? result.error.status : 500,
3222
+ actionData: null,
3223
+ actionHeaders: _extends({}, result.headers ? {
3224
+ [actionMatch.route.id]: result.headers
3225
+ } : {})
3226
+ });
3227
+ } // Create a GET request for the loaders
3228
+
3229
+
3230
+ let loaderRequest = new Request(request.url, {
3231
+ headers: request.headers,
3232
+ redirect: request.redirect,
3233
+ signal: request.signal
3234
+ });
3235
+ let context = await loadRouteData(loaderRequest, matches, requestContext, middlewareContext);
3236
+ return _extends({}, context, result.statusCode ? {
3237
+ statusCode: result.statusCode
3238
+ } : {}, {
3239
+ actionData: {
3240
+ [actionMatch.route.id]: result.data
3241
+ },
3242
+ actionHeaders: _extends({}, result.headers ? {
3243
+ [actionMatch.route.id]: result.headers
3244
+ } : {})
3245
+ });
3246
+ }
3247
+
3248
+ async function loadRouteData(request, matches, requestContext, middlewareContext, routeMatch, pendingActionError) {
3249
+ let isRouteRequest = routeMatch != null; // Short circuit if we have no loaders to run (queryRoute())
3250
+
3251
+ if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader)) {
3252
+ throw getInternalRouterError(400, {
3253
+ method: request.method,
3254
+ pathname: new URL(request.url).pathname,
3255
+ routeId: routeMatch == null ? void 0 : routeMatch.route.id
3256
+ });
3257
+ }
3258
+
3259
+ let requestMatches = routeMatch ? [routeMatch] : getLoaderMatchesUntilBoundary(matches, Object.keys(pendingActionError || {})[0]);
3260
+ let matchesToLoad = requestMatches.filter(m => m.route.loader); // Short circuit if we have no loaders to run (query())
3261
+
3262
+ if (matchesToLoad.length === 0) {
3263
+ return {
3264
+ matches,
3265
+ // Add a null for all matched routes for proper revalidation on the client
3266
+ loaderData: matches.reduce((acc, m) => Object.assign(acc, {
3267
+ [m.route.id]: null
3268
+ }), {}),
3269
+ errors: pendingActionError || null,
3270
+ statusCode: 200,
3271
+ loaderHeaders: {},
3272
+ activeDeferreds: null
3273
+ };
3274
+ }
3275
+
3276
+ let results = await Promise.all([...matchesToLoad.map(match => callLoaderOrAction("loader", request, match, matches, basename, future.unstable_middleware, true, isRouteRequest, requestContext, middlewareContext))]);
3277
+
3278
+ if (request.signal.aborted) {
3279
+ let method = isRouteRequest ? "queryRoute" : "query";
3280
+ throw new Error(method + "() call aborted");
3281
+ } // Process and commit output from loaders
3282
+
3283
+
3284
+ let activeDeferreds = new Map();
3285
+ let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionError, activeDeferreds); // Add a null for any non-loader matches for proper revalidation on the client
3286
+
3287
+ let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));
3288
+ matches.forEach(match => {
3289
+ if (!executedLoaders.has(match.route.id)) {
3290
+ context.loaderData[match.route.id] = null;
3291
+ }
3292
+ });
3293
+ return _extends({}, context, {
3294
+ matches,
3295
+ activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null
3296
+ });
3297
+ }
3298
+
3299
+ return {
3300
+ dataRoutes,
3301
+ query,
3302
+ queryRoute
3303
+ };
3304
+ } //#endregion
3305
+ ////////////////////////////////////////////////////////////////////////////////
3306
+ //#region Helpers
3307
+ ////////////////////////////////////////////////////////////////////////////////
3308
+
3309
+ /**
3310
+ * Given an existing StaticHandlerContext and an error thrown at render time,
3311
+ * provide an updated StaticHandlerContext suitable for a second SSR render
3312
+ */
3313
+
3314
+ function getStaticContextFromError(routes, context, error) {
3315
+ let newContext = _extends({}, context, {
3316
+ statusCode: 500,
3317
+ errors: {
3318
+ [context._deepestRenderedBoundaryId || routes[0].id]: error
3319
+ }
3320
+ });
3321
+
3322
+ return newContext;
3323
+ }
3324
+
3325
+ function isSubmissionNavigation(opts) {
3326
+ return opts != null && "formData" in opts;
3327
+ } // Normalize navigation options by converting formMethod=GET formData objects to
3328
+ // URLSearchParams so they behave identically to links with query params
3329
+
3330
+
3331
+ function normalizeNavigateOptions(to, opts, isFetcher) {
3332
+ if (isFetcher === void 0) {
3333
+ isFetcher = false;
3334
+ }
3335
+
3336
+ let path = typeof to === "string" ? to : createPath(to); // Return location verbatim on non-submission navigations
3337
+
3338
+ if (!opts || !isSubmissionNavigation(opts)) {
3339
+ return {
3340
+ path
3341
+ };
3342
+ }
3343
+
3344
+ if (opts.formMethod && !isValidMethod(opts.formMethod)) {
3345
+ return {
3346
+ path,
3347
+ error: getInternalRouterError(405, {
3348
+ method: opts.formMethod
3349
+ })
3350
+ };
3351
+ } // Create a Submission on non-GET navigations
3352
+
3353
+
3354
+ let submission;
3355
+
3356
+ if (opts.formData) {
3357
+ submission = {
3358
+ formMethod: opts.formMethod || "get",
3359
+ formAction: stripHashFromPath(path),
3360
+ formEncType: opts && opts.formEncType || "application/x-www-form-urlencoded",
3361
+ formData: opts.formData
3362
+ };
3363
+
3364
+ if (isMutationMethod(submission.formMethod)) {
3365
+ return {
3366
+ path,
3367
+ submission
3368
+ };
3369
+ }
3370
+ } // Flatten submission onto URLSearchParams for GET submissions
3371
+
3372
+
3373
+ let parsedPath = parsePath(path);
3374
+ let searchParams = convertFormDataToSearchParams(opts.formData); // Since fetcher GET submissions only run a single loader (as opposed to
3375
+ // navigation GET submissions which run all loaders), we need to preserve
3376
+ // any incoming ?index params
3377
+
3378
+ if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {
3379
+ searchParams.append("index", "");
3380
+ }
3381
+
3382
+ parsedPath.search = "?" + searchParams;
3383
+ return {
3384
+ path: createPath(parsedPath),
3385
+ submission
3386
+ };
3387
+ } // Filter out all routes below any caught error as they aren't going to
3388
+ // render so we don't need to load them
3389
+
3390
+
3391
+ function getLoaderMatchesUntilBoundary(matches, boundaryId) {
3392
+ let boundaryMatches = matches;
3393
+
3394
+ if (boundaryId) {
3395
+ let index = matches.findIndex(m => m.route.id === boundaryId);
3396
+
3397
+ if (index >= 0) {
3398
+ boundaryMatches = matches.slice(0, index);
3399
+ }
3400
+ }
3401
+
3402
+ return boundaryMatches;
3403
+ }
3404
+
3405
+ function getMatchesToLoad(history, state, matches, submission, location, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, pendingActionData, pendingError, fetchLoadMatches) {
3406
+ let actionResult = pendingError ? Object.values(pendingError)[0] : pendingActionData ? Object.values(pendingActionData)[0] : undefined;
3407
+ let currentUrl = history.createURL(state.location);
3408
+ let nextUrl = history.createURL(location);
3409
+ let defaultShouldRevalidate = // Forced revalidation due to submission, useRevalidate, or X-Remix-Revalidate
3410
+ isRevalidationRequired || // Clicked the same link, resubmitted a GET form
3411
+ currentUrl.toString() === nextUrl.toString() || // Search params affect all loaders
3412
+ currentUrl.search !== nextUrl.search; // Pick navigation matches that are net-new or qualify for revalidation
3413
+
3414
+ let boundaryId = pendingError ? Object.keys(pendingError)[0] : undefined;
3415
+ let boundaryMatches = getLoaderMatchesUntilBoundary(matches, boundaryId);
3416
+ let navigationMatches = boundaryMatches.filter((match, index) => {
3417
+ if (match.route.loader == null) {
3418
+ return false;
3419
+ } // Always call the loader on new route instances and pending defer cancellations
3420
+
3421
+
3422
+ if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {
3423
+ return true;
3424
+ } // This is the default implementation for when we revalidate. If the route
3425
+ // provides it's own implementation, then we give them full control but
3426
+ // provide this value so they can leverage it if needed after they check
3427
+ // their own specific use cases
3428
+
3429
+
3430
+ let currentRouteMatch = state.matches[index];
3431
+ let nextRouteMatch = match;
3432
+ return shouldRevalidateLoader(match, _extends({
3433
+ currentUrl,
3434
+ currentParams: currentRouteMatch.params,
3435
+ nextUrl,
3436
+ nextParams: nextRouteMatch.params
3437
+ }, submission, {
3438
+ actionResult,
3439
+ defaultShouldRevalidate: defaultShouldRevalidate || isNewRouteInstance(currentRouteMatch, nextRouteMatch)
3440
+ }));
3441
+ }); // Pick fetcher.loads that need to be revalidated
3442
+
3443
+ let revalidatingFetchers = [];
3444
+ fetchLoadMatches && fetchLoadMatches.forEach((f, key) => {
3445
+ if (!matches.some(m => m.route.id === f.routeId)) {
3446
+ // This fetcher is not going to be present in the subsequent render so
3447
+ // there's no need to revalidate it
3448
+ return;
3449
+ } else if (cancelledFetcherLoads.includes(key)) {
3450
+ // This fetcher was cancelled from a prior action submission - force reload
3451
+ revalidatingFetchers.push(_extends({
3452
+ key
3453
+ }, f));
3454
+ } else {
3455
+ // Revalidating fetchers are decoupled from the route matches since they
3456
+ // hit a static href, so they _always_ check shouldRevalidate and the
3457
+ // default is strictly if a revalidation is explicitly required (action
3458
+ // submissions, useRevalidator, X-Remix-Revalidate).
3459
+ let shouldRevalidate = shouldRevalidateLoader(f.match, _extends({
3460
+ currentUrl,
3461
+ currentParams: state.matches[state.matches.length - 1].params,
3462
+ nextUrl,
3463
+ nextParams: matches[matches.length - 1].params
3464
+ }, submission, {
3465
+ actionResult,
3466
+ defaultShouldRevalidate
3467
+ }));
3468
+
3469
+ if (shouldRevalidate) {
3470
+ revalidatingFetchers.push(_extends({
3471
+ key
3472
+ }, f));
3473
+ }
3474
+ }
3475
+ });
3476
+ return [navigationMatches, revalidatingFetchers];
3477
+ }
3478
+
3479
+ function isNewLoader(currentLoaderData, currentMatch, match) {
3480
+ let isNew = // [a] -> [a, b]
3481
+ !currentMatch || // [a, b] -> [a, c]
3482
+ match.route.id !== currentMatch.route.id; // Handle the case that we don't have data for a re-used route, potentially
3483
+ // from a prior error or from a cancelled pending deferred
3484
+
3485
+ let isMissingData = currentLoaderData[match.route.id] === undefined; // Always load if this is a net-new route or we don't yet have data
3486
+
3487
+ return isNew || isMissingData;
3488
+ }
3489
+
3490
+ function isNewRouteInstance(currentMatch, match) {
3491
+ let currentPath = currentMatch.route.path;
3492
+ return (// param change for this match, /users/123 -> /users/456
3493
+ currentMatch.pathname !== match.pathname || // splat param changed, which is not present in match.path
3494
+ // e.g. /files/images/avatar.jpg -> files/finances.xls
3495
+ currentPath != null && currentPath.endsWith("*") && currentMatch.params["*"] !== match.params["*"]
3496
+ );
3497
+ }
3498
+
3499
+ function shouldRevalidateLoader(loaderMatch, arg) {
3500
+ if (loaderMatch.route.shouldRevalidate) {
3501
+ let routeChoice = loaderMatch.route.shouldRevalidate(arg);
3502
+
3503
+ if (typeof routeChoice === "boolean") {
3504
+ return routeChoice;
3505
+ }
3506
+ }
3507
+
3508
+ return arg.defaultShouldRevalidate;
3509
+ }
3510
+
3511
+ async function callRouteSubPipeline(request, matches, params, middlewareContext, handler) {
3512
+ if (request.signal.aborted) {
3513
+ throw new Error("Request aborted");
3514
+ }
3515
+
3516
+ if (matches.length === 0) {
3517
+ // We reached the end of our middlewares, call the handler
3518
+ middlewareContext.next = () => {
3519
+ throw new Error("You may only call `next()` once per middleware and you may not call " + "it in an action or loader");
3520
+ };
3521
+
3522
+ return handler({
3523
+ request,
3524
+ params,
3525
+ context: middlewareContext
3526
+ });
3527
+ } // We've still got matches, continue on the middleware train. The `next()`
3528
+ // function will "bubble" back up the middlewares after handlers have executed
3529
+
3530
+
3531
+ let nextCalled = false;
3532
+
3533
+ let next = () => {
3534
+ nextCalled = true;
3535
+ return callRouteSubPipeline(request, matches.slice(1), params, middlewareContext, handler);
3536
+ };
3537
+
3538
+ if (!matches[0].route.middleware) {
3539
+ return next();
3540
+ }
3541
+
3542
+ middlewareContext.next = next;
3543
+ let res = await matches[0].route.middleware({
3544
+ request,
3545
+ params,
3546
+ context: middlewareContext
3547
+ });
3548
+
3549
+ if (nextCalled) {
3550
+ return res;
3551
+ } else {
3552
+ return next();
3553
+ }
3554
+ }
3555
+
3556
+ function disabledMiddlewareFn() {
3557
+ throw new Error("Middleware must be enabled via the `future.unstable_middleware` flag)");
3558
+ }
3559
+
3560
+ const disabledMiddlewareContext = {
3561
+ // @ts-expect-error
3562
+ get: disabledMiddlewareFn,
3563
+ set: disabledMiddlewareFn,
3564
+ next: disabledMiddlewareFn
3565
+ };
3566
+
3567
+ async function callLoaderOrAction(type, request, match, matches, basename, enableMiddleware, isStaticRequest, isRouteRequest, requestContext, middlewareContext) {
3568
+ if (basename === void 0) {
3569
+ basename = "/";
3570
+ }
3571
+
3572
+ if (isStaticRequest === void 0) {
3573
+ isStaticRequest = false;
3574
+ }
3575
+
3576
+ if (isRouteRequest === void 0) {
3577
+ isRouteRequest = false;
3578
+ }
3579
+
3580
+ let resultType;
3581
+ let result; // Setup a promise we can race against so that abort signals short circuit
3582
+
3583
+ let reject;
3584
+ let abortPromise = new Promise((_, r) => reject = r);
3585
+
3586
+ let onReject = () => reject();
3587
+
3588
+ request.signal.addEventListener("abort", onReject);
3589
+
3590
+ try {
3591
+ let handler = match.route[type];
3592
+ invariant(handler, "Could not find the " + type + " to run on the \"" + match.route.id + "\" route"); // Only call the pipeline for the matches up to this specific match
3593
+
3594
+ let idx = matches.findIndex(m => m.route.id === match.route.id);
3595
+ let dataPromise;
3596
+
3597
+ if (enableMiddleware) {
3598
+ dataPromise = callRouteSubPipeline(request, matches.slice(0, idx + 1), matches[0].params, createMiddlewareStore(middlewareContext), handler);
3599
+ } else {
3600
+ dataPromise = handler({
3601
+ request,
3602
+ params: match.params,
3603
+ context: requestContext || disabledMiddlewareContext
3604
+ });
3605
+ }
3606
+
3607
+ result = await Promise.race([dataPromise, abortPromise]);
3608
+ invariant(result !== undefined, "You defined " + (type === "action" ? "an action" : "a loader") + " for route " + ("\"" + match.route.id + "\" but didn't return anything from your `" + type + "` ") + "function. Please return a value or `null`.");
3609
+ } catch (e) {
3610
+ resultType = ResultType.error;
3611
+ result = e;
3612
+ } finally {
3613
+ request.signal.removeEventListener("abort", onReject);
3614
+ }
3615
+
3616
+ if (isResponse(result)) {
3617
+ let status = result.status; // Process redirects
3618
+
3619
+ if (redirectStatusCodes.has(status)) {
3620
+ let location = result.headers.get("Location");
3621
+ invariant(location, "Redirects returned/thrown from loaders/actions must have a Location header"); // Support relative routing in internal redirects
3622
+
3623
+ if (!ABSOLUTE_URL_REGEX.test(location)) {
3624
+ let activeMatches = matches.slice(0, matches.indexOf(match) + 1);
3625
+ let routePathnames = getPathContributingMatches(activeMatches).map(match => match.pathnameBase);
3626
+ let resolvedLocation = resolveTo(location, routePathnames, new URL(request.url).pathname);
3627
+ invariant(createPath(resolvedLocation), "Unable to resolve redirect location: " + location); // Prepend the basename to the redirect location if we have one
3628
+
3629
+ if (basename) {
3630
+ let path = resolvedLocation.pathname;
3631
+ resolvedLocation.pathname = path === "/" ? basename : joinPaths([basename, path]);
3632
+ }
3633
+
3634
+ location = createPath(resolvedLocation);
3635
+ } else if (!isStaticRequest) {
3636
+ // Strip off the protocol+origin for same-origin absolute redirects.
3637
+ // If this is a static reques, we can let it go back to the browser
3638
+ // as-is
3639
+ let currentUrl = new URL(request.url);
3640
+ let url = location.startsWith("//") ? new URL(currentUrl.protocol + location) : new URL(location);
3641
+
3642
+ if (url.origin === currentUrl.origin) {
3643
+ location = url.pathname + url.search + url.hash;
3644
+ }
3645
+ } // Don't process redirects in the router during static requests requests.
3646
+ // Instead, throw the Response and let the server handle it with an HTTP
3647
+ // redirect. We also update the Location header in place in this flow so
3648
+ // basename and relative routing is taken into account
3649
+
3650
+
3651
+ if (isStaticRequest) {
3652
+ result.headers.set("Location", location);
3653
+ throw result;
3654
+ }
3655
+
3656
+ return {
3657
+ type: ResultType.redirect,
3658
+ status,
3659
+ location,
3660
+ revalidate: result.headers.get("X-Remix-Revalidate") !== null
3661
+ };
3662
+ } // For SSR single-route requests, we want to hand Responses back directly
3663
+ // without unwrapping. We do this with the QueryRouteResponse wrapper
3664
+ // interface so we can know whether it was returned or thrown
3665
+
3666
+
3667
+ if (isRouteRequest) {
3668
+ // eslint-disable-next-line no-throw-literal
3669
+ throw {
3670
+ type: resultType || ResultType.data,
3671
+ response: result
3672
+ };
3673
+ }
3674
+
3675
+ let data;
3676
+ let contentType = result.headers.get("Content-Type"); // Check between word boundaries instead of startsWith() due to the last
3677
+ // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type
3678
+
3679
+ if (contentType && /\bapplication\/json\b/.test(contentType)) {
3680
+ data = await result.json();
3681
+ } else {
3682
+ data = await result.text();
3683
+ }
3684
+
3685
+ if (resultType === ResultType.error) {
3686
+ return {
3687
+ type: resultType,
3688
+ error: new ErrorResponse(status, result.statusText, data),
3689
+ headers: result.headers
3690
+ };
3691
+ }
3692
+
3693
+ return {
3694
+ type: ResultType.data,
3695
+ data,
3696
+ statusCode: result.status,
3697
+ headers: result.headers
3698
+ };
3699
+ }
3700
+
3701
+ if (resultType === ResultType.error) {
3702
+ return {
3703
+ type: resultType,
3704
+ error: result
3705
+ };
3706
+ }
3707
+
3708
+ if (result instanceof DeferredData) {
3709
+ return {
3710
+ type: ResultType.deferred,
3711
+ deferredData: result
3712
+ };
3713
+ }
3714
+
3715
+ return {
3716
+ type: ResultType.data,
3717
+ data: result
3718
+ };
3719
+ } // Utility method for creating the Request instances for loaders/actions during
3720
+ // client-side navigations and fetches. During SSR we will always have a
3721
+ // Request instance from the static handler (query/queryRoute)
3722
+
3723
+
3724
+ function createClientSideRequest(history, location, signal, submission) {
3725
+ let url = history.createURL(stripHashFromPath(location)).toString();
3726
+ let init = {
3727
+ signal
3728
+ };
3729
+
3730
+ if (submission && isMutationMethod(submission.formMethod)) {
3731
+ let {
3732
+ formMethod,
3733
+ formEncType,
3734
+ formData
3735
+ } = submission;
3736
+ init.method = formMethod.toUpperCase();
3737
+ init.body = formEncType === "application/x-www-form-urlencoded" ? convertFormDataToSearchParams(formData) : formData;
3738
+ } // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)
3739
+
3740
+
3741
+ return new Request(url, init);
3742
+ }
3743
+
3744
+ function convertFormDataToSearchParams(formData) {
3745
+ let searchParams = new URLSearchParams();
3746
+
3747
+ for (let [key, value] of formData.entries()) {
3748
+ // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs
3749
+ searchParams.append(key, value instanceof File ? value.name : value);
3750
+ }
3751
+
3752
+ return searchParams;
3753
+ }
3754
+
3755
+ function processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds) {
3756
+ // Fill in loaderData/errors from our loaders
3757
+ let loaderData = {};
3758
+ let errors = null;
3759
+ let statusCode;
3760
+ let foundError = false;
3761
+ let loaderHeaders = {}; // Process loader results into state.loaderData/state.errors
3762
+
3763
+ results.forEach((result, index) => {
3764
+ let id = matchesToLoad[index].route.id;
3765
+ invariant(!isRedirectResult(result), "Cannot handle redirect results in processLoaderData");
3766
+
3767
+ if (isErrorResult(result)) {
3768
+ // Look upwards from the matched route for the closest ancestor
3769
+ // error boundary, defaulting to the root match
3770
+ let boundaryMatch = findNearestBoundary(matches, id);
3771
+ let error = result.error; // If we have a pending action error, we report it at the highest-route
3772
+ // that throws a loader error, and then clear it out to indicate that
3773
+ // it was consumed
3774
+
3775
+ if (pendingError) {
3776
+ error = Object.values(pendingError)[0];
3777
+ pendingError = undefined;
3778
+ }
3779
+
3780
+ errors = errors || {}; // Prefer higher error values if lower errors bubble to the same boundary
3781
+
3782
+ if (errors[boundaryMatch.route.id] == null) {
3783
+ errors[boundaryMatch.route.id] = error;
3784
+ } // Clear our any prior loaderData for the throwing route
3785
+
3786
+
3787
+ loaderData[id] = undefined; // Once we find our first (highest) error, we set the status code and
3788
+ // prevent deeper status codes from overriding
3789
+
3790
+ if (!foundError) {
3791
+ foundError = true;
3792
+ statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;
3793
+ }
3794
+
3795
+ if (result.headers) {
3796
+ loaderHeaders[id] = result.headers;
3797
+ }
3798
+ } else {
3799
+ if (isDeferredResult(result)) {
3800
+ activeDeferreds.set(id, result.deferredData);
3801
+ loaderData[id] = result.deferredData.data;
3802
+ } else {
3803
+ loaderData[id] = result.data;
3804
+ } // Error status codes always override success status codes, but if all
3805
+ // loaders are successful we take the deepest status code.
3806
+
3807
+
3808
+ if (result.statusCode != null && result.statusCode !== 200 && !foundError) {
3809
+ statusCode = result.statusCode;
3810
+ }
3811
+
3812
+ if (result.headers) {
3813
+ loaderHeaders[id] = result.headers;
3814
+ }
3815
+ }
3816
+ }); // If we didn't consume the pending action error (i.e., all loaders
3817
+ // resolved), then consume it here. Also clear out any loaderData for the
3818
+ // throwing route
3819
+
3820
+ if (pendingError) {
3821
+ errors = pendingError;
3822
+ loaderData[Object.keys(pendingError)[0]] = undefined;
3823
+ }
3824
+
3825
+ return {
3826
+ loaderData,
3827
+ errors,
3828
+ statusCode: statusCode || 200,
3829
+ loaderHeaders
3830
+ };
3831
+ }
3832
+
3833
+ function processLoaderData(state, matches, matchesToLoad, results, pendingError, revalidatingFetchers, fetcherResults, activeDeferreds) {
3834
+ let {
3835
+ loaderData,
3836
+ errors
3837
+ } = processRouteLoaderData(matches, matchesToLoad, results, pendingError, activeDeferreds); // Process results from our revalidating fetchers
3838
+
3839
+ for (let index = 0; index < revalidatingFetchers.length; index++) {
3840
+ let {
3841
+ key,
3842
+ match
3843
+ } = revalidatingFetchers[index];
3844
+ invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, "Did not find corresponding fetcher result");
3845
+ let result = fetcherResults[index]; // Process fetcher non-redirect errors
3846
+
3847
+ if (isErrorResult(result)) {
3848
+ let boundaryMatch = findNearestBoundary(state.matches, match.route.id);
3849
+
3850
+ if (!(errors && errors[boundaryMatch.route.id])) {
3851
+ errors = _extends({}, errors, {
3852
+ [boundaryMatch.route.id]: result.error
3853
+ });
3854
+ }
3855
+
3856
+ state.fetchers.delete(key);
3857
+ } else if (isRedirectResult(result)) {
3858
+ // Should never get here, redirects should get processed above, but we
3859
+ // keep this to type narrow to a success result in the else
3860
+ invariant(false, "Unhandled fetcher revalidation redirect");
3861
+ } else if (isDeferredResult(result)) {
3862
+ // Should never get here, deferred data should be awaited for fetchers
3863
+ // in resolveDeferredResults
3864
+ invariant(false, "Unhandled fetcher deferred data");
3865
+ } else {
3866
+ let doneFetcher = {
3867
+ state: "idle",
3868
+ data: result.data,
3869
+ formMethod: undefined,
3870
+ formAction: undefined,
3871
+ formEncType: undefined,
3872
+ formData: undefined,
3873
+ " _hasFetcherDoneAnything ": true
3874
+ };
3875
+ state.fetchers.set(key, doneFetcher);
3876
+ }
3877
+ }
3878
+
3879
+ return {
3880
+ loaderData,
3881
+ errors
3882
+ };
3883
+ }
3884
+
3885
+ function mergeLoaderData(loaderData, newLoaderData, matches, errors) {
3886
+ let mergedLoaderData = _extends({}, newLoaderData);
3887
+
3888
+ for (let match of matches) {
3889
+ let id = match.route.id;
3890
+
3891
+ if (newLoaderData.hasOwnProperty(id)) {
3892
+ if (newLoaderData[id] !== undefined) {
3893
+ mergedLoaderData[id] = newLoaderData[id];
3894
+ }
3895
+ } else if (loaderData[id] !== undefined) {
3896
+ mergedLoaderData[id] = loaderData[id];
3897
+ }
3898
+
3899
+ if (errors && errors.hasOwnProperty(id)) {
3900
+ // Don't keep any loader data below the boundary
3901
+ break;
3902
+ }
3903
+ }
3904
+
3905
+ return mergedLoaderData;
3906
+ } // Find the nearest error boundary, looking upwards from the leaf route (or the
3907
+ // route specified by routeId) for the closest ancestor error boundary,
3908
+ // defaulting to the root match
3909
+
3910
+
3911
+ function findNearestBoundary(matches, routeId) {
3912
+ let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];
3913
+ return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];
3914
+ }
3915
+
3916
+ function getShortCircuitMatches(routes) {
3917
+ // Prefer a root layout route if present, otherwise shim in a route object
3918
+ let route = routes.find(r => r.index || !r.path || r.path === "/") || {
3919
+ id: "__shim-error-route__"
3920
+ };
3921
+ return {
3922
+ matches: [{
3923
+ params: {},
3924
+ pathname: "",
3925
+ pathnameBase: "",
3926
+ route
3927
+ }],
3928
+ route
3929
+ };
3930
+ }
3931
+
3932
+ function getInternalRouterError(status, _temp4) {
3933
+ let {
3934
+ pathname,
3935
+ routeId,
3936
+ method,
3937
+ type
3938
+ } = _temp4 === void 0 ? {} : _temp4;
3939
+ let statusText = "Unknown Server Error";
3940
+ let errorMessage = "Unknown @remix-run/router error";
3941
+
3942
+ if (status === 400) {
3943
+ statusText = "Bad Request";
3944
+
3945
+ if (method && pathname && routeId) {
3946
+ 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.";
3947
+ } else if (type === "defer-action") {
3948
+ errorMessage = "defer() is not supported in actions";
3949
+ }
3950
+ } else if (status === 403) {
3951
+ statusText = "Forbidden";
3952
+ errorMessage = "Route \"" + routeId + "\" does not match URL \"" + pathname + "\"";
3953
+ } else if (status === 404) {
3954
+ statusText = "Not Found";
3955
+ errorMessage = "No route matches URL \"" + pathname + "\"";
3956
+ } else if (status === 405) {
3957
+ statusText = "Method Not Allowed";
3958
+
3959
+ if (method && pathname && routeId) {
3960
+ 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.";
3961
+ } else if (method) {
3962
+ errorMessage = "Invalid request method \"" + method.toUpperCase() + "\"";
3963
+ }
3964
+ }
3965
+
3966
+ return new ErrorResponse(status || 500, statusText, new Error(errorMessage), true);
3967
+ } // Find any returned redirect errors, starting from the lowest match
3968
+
3969
+
3970
+ function findRedirect(results) {
3971
+ for (let i = results.length - 1; i >= 0; i--) {
3972
+ let result = results[i];
3973
+
3974
+ if (isRedirectResult(result)) {
3975
+ return result;
3976
+ }
3977
+ }
3978
+ }
3979
+
3980
+ function stripHashFromPath(path) {
3981
+ let parsedPath = typeof path === "string" ? parsePath(path) : path;
3982
+ return createPath(_extends({}, parsedPath, {
3983
+ hash: ""
3984
+ }));
3985
+ }
3986
+
3987
+ function isHashChangeOnly(a, b) {
3988
+ return a.pathname === b.pathname && a.search === b.search && a.hash !== b.hash;
3989
+ }
3990
+
3991
+ function isDeferredResult(result) {
3992
+ return result.type === ResultType.deferred;
3993
+ }
3994
+
3995
+ function isErrorResult(result) {
3996
+ return result.type === ResultType.error;
3997
+ }
3998
+
3999
+ function isRedirectResult(result) {
4000
+ return (result && result.type) === ResultType.redirect;
4001
+ }
4002
+
4003
+ function isResponse(value) {
4004
+ return value != null && typeof value.status === "number" && typeof value.statusText === "string" && typeof value.headers === "object" && typeof value.body !== "undefined";
4005
+ }
4006
+
4007
+ function isRedirectResponse(result) {
4008
+ if (!isResponse(result)) {
4009
+ return false;
4010
+ }
4011
+
4012
+ let status = result.status;
4013
+ let location = result.headers.get("Location");
4014
+ return status >= 300 && status <= 399 && location != null;
4015
+ }
4016
+
4017
+ function isQueryRouteResponse(obj) {
4018
+ return obj && isResponse(obj.response) && (obj.type === ResultType.data || ResultType.error);
4019
+ }
4020
+
4021
+ function isValidMethod(method) {
4022
+ return validRequestMethods.has(method);
4023
+ }
4024
+
4025
+ function isMutationMethod(method) {
4026
+ return validMutationMethods.has(method);
4027
+ }
4028
+
4029
+ async function resolveDeferredResults(currentMatches, matchesToLoad, results, signal, isFetcher, currentLoaderData) {
4030
+ for (let index = 0; index < results.length; index++) {
4031
+ let result = results[index];
4032
+ let match = matchesToLoad[index];
4033
+ let currentMatch = currentMatches.find(m => m.route.id === match.route.id);
4034
+ let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;
4035
+
4036
+ if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {
4037
+ // Note: we do not have to touch activeDeferreds here since we race them
4038
+ // against the signal in resolveDeferredData and they'll get aborted
4039
+ // there if needed
4040
+ await resolveDeferredData(result, signal, isFetcher).then(result => {
4041
+ if (result) {
4042
+ results[index] = result || results[index];
4043
+ }
4044
+ });
4045
+ }
4046
+ }
4047
+ }
4048
+
4049
+ async function resolveDeferredData(result, signal, unwrap) {
4050
+ if (unwrap === void 0) {
4051
+ unwrap = false;
4052
+ }
4053
+
4054
+ let aborted = await result.deferredData.resolveData(signal);
4055
+
4056
+ if (aborted) {
4057
+ return;
4058
+ }
4059
+
4060
+ if (unwrap) {
4061
+ try {
4062
+ return {
4063
+ type: ResultType.data,
4064
+ data: result.deferredData.unwrappedData
4065
+ };
4066
+ } catch (e) {
4067
+ // Handle any TrackedPromise._error values encountered while unwrapping
4068
+ return {
4069
+ type: ResultType.error,
4070
+ error: e
4071
+ };
4072
+ }
4073
+ }
4074
+
4075
+ return {
4076
+ type: ResultType.data,
4077
+ data: result.deferredData.data
4078
+ };
4079
+ }
4080
+
4081
+ function hasNakedIndexQuery(search) {
4082
+ return new URLSearchParams(search).getAll("index").some(v => v === "");
4083
+ } // Note: This should match the format exported by useMatches, so if you change
4084
+ // this please also change that :) Eventually we'll DRY this up
4085
+
4086
+
4087
+ function createUseMatchesMatch(match, loaderData) {
4088
+ let {
4089
+ route,
4090
+ pathname,
4091
+ params
4092
+ } = match;
4093
+ return {
4094
+ id: route.id,
4095
+ pathname,
4096
+ params,
4097
+ data: loaderData[route.id],
4098
+ handle: route.handle
4099
+ };
4100
+ }
4101
+
4102
+ function getTargetMatch(matches, location) {
4103
+ let search = typeof location === "string" ? parsePath(location).search : location.search;
4104
+
4105
+ if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || "")) {
4106
+ // Return the leaf index route when index is present
4107
+ return matches[matches.length - 1];
4108
+ } // Otherwise grab the deepest "path contributing" match (ignoring index and
4109
+ // pathless layout routes)
4110
+
4111
+
4112
+ let pathMatches = getPathContributingMatches(matches);
4113
+ return pathMatches[pathMatches.length - 1];
4114
+ } //#endregion
4115
+
4116
+ export { AbortedDeferredError, Action, ErrorResponse, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, createMiddlewareStore as UNSAFE_createMiddlewareStore, getPathContributingMatches as UNSAFE_getPathContributingMatches, createBrowserHistory, createHashHistory, createMemoryHistory, createMiddlewareContext, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, invariant, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, resolvePath, resolveTo, stripBasename, warning };
4117
+ //# sourceMappingURL=router.js.map