UNPKG

55.9 kBJavaScriptView Raw
1/**
2 * React Router v6.8.0
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 (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@remix-run/router'), require('react')) :
13 typeof define === 'function' && define.amd ? define(['exports', '@remix-run/router', 'react'], factory) :
14 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactRouter = {}, global.RemixRouter, global.React));
15})(this, (function (exports, router, React) { 'use strict';
16
17 function _interopNamespace(e) {
18 if (e && e.__esModule) return e;
19 var n = Object.create(null);
20 if (e) {
21 Object.keys(e).forEach(function (k) {
22 if (k !== 'default') {
23 var d = Object.getOwnPropertyDescriptor(e, k);
24 Object.defineProperty(n, k, d.get ? d : {
25 enumerable: true,
26 get: function () { return e[k]; }
27 });
28 }
29 });
30 }
31 n["default"] = e;
32 return Object.freeze(n);
33 }
34
35 var React__namespace = /*#__PURE__*/_interopNamespace(React);
36
37 function _extends() {
38 _extends = Object.assign ? Object.assign.bind() : function (target) {
39 for (var i = 1; i < arguments.length; i++) {
40 var source = arguments[i];
41
42 for (var key in source) {
43 if (Object.prototype.hasOwnProperty.call(source, key)) {
44 target[key] = source[key];
45 }
46 }
47 }
48
49 return target;
50 };
51 return _extends.apply(this, arguments);
52 }
53
54 /**
55 * Copyright (c) Facebook, Inc. and its affiliates.
56 *
57 * This source code is licensed under the MIT license found in the
58 * LICENSE file in the root directory of this source tree.
59 */
60 /**
61 * inlined Object.is polyfill to avoid requiring consumers ship their own
62 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
63 */
64
65 function isPolyfill(x, y) {
66 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
67 ;
68 }
69
70 const is = typeof Object.is === "function" ? Object.is : isPolyfill; // Intentionally not using named imports because Rollup uses dynamic
71 // dispatch for CommonJS interop named imports.
72
73 const {
74 useState,
75 useEffect,
76 useLayoutEffect,
77 useDebugValue
78 } = React__namespace;
79 let didWarnOld18Alpha = false;
80 let didWarnUncachedGetSnapshot = false; // Disclaimer: This shim breaks many of the rules of React, and only works
81 // because of a very particular set of implementation details and assumptions
82 // -- change any one of them and it will break. The most important assumption
83 // is that updates are always synchronous, because concurrent rendering is
84 // only available in versions of React that also have a built-in
85 // useSyncExternalStore API. And we only use this shim when the built-in API
86 // does not exist.
87 //
88 // Do not assume that the clever hacks used by this hook also work in general.
89 // The point of this shim is to replace the need for hacks by other libraries.
90
91 function useSyncExternalStore$2(subscribe, getSnapshot, // Note: The shim does not use getServerSnapshot, because pre-18 versions of
92 // React do not expose a way to check if we're hydrating. So users of the shim
93 // will need to track that themselves and return the correct value
94 // from `getSnapshot`.
95 getServerSnapshot) {
96 {
97 if (!didWarnOld18Alpha) {
98 if ("startTransition" in React__namespace) {
99 didWarnOld18Alpha = true;
100 console.error("You are using an outdated, pre-release alpha of React 18 that " + "does not support useSyncExternalStore. The " + "use-sync-external-store shim will not work correctly. Upgrade " + "to a newer pre-release.");
101 }
102 }
103 } // Read the current snapshot from the store on every render. Again, this
104 // breaks the rules of React, and only works here because of specific
105 // implementation details, most importantly that updates are
106 // always synchronous.
107
108
109 const value = getSnapshot();
110
111 {
112 if (!didWarnUncachedGetSnapshot) {
113 const cachedValue = getSnapshot();
114
115 if (!is(value, cachedValue)) {
116 console.error("The result of getSnapshot should be cached to avoid an infinite loop");
117 didWarnUncachedGetSnapshot = true;
118 }
119 }
120 } // Because updates are synchronous, we don't queue them. Instead we force a
121 // re-render whenever the subscribed state changes by updating an some
122 // arbitrary useState hook. Then, during render, we call getSnapshot to read
123 // the current value.
124 //
125 // Because we don't actually use the state returned by the useState hook, we
126 // can save a bit of memory by storing other stuff in that slot.
127 //
128 // To implement the early bailout, we need to track some things on a mutable
129 // object. Usually, we would put that in a useRef hook, but we can stash it in
130 // our useState hook instead.
131 //
132 // To force a re-render, we call forceUpdate({inst}). That works because the
133 // new object always fails an equality check.
134
135
136 const [{
137 inst
138 }, forceUpdate] = useState({
139 inst: {
140 value,
141 getSnapshot
142 }
143 }); // Track the latest getSnapshot function with a ref. This needs to be updated
144 // in the layout phase so we can access it during the tearing check that
145 // happens on subscribe.
146
147 useLayoutEffect(() => {
148 inst.value = value;
149 inst.getSnapshot = getSnapshot; // Whenever getSnapshot or subscribe changes, we need to check in the
150 // commit phase if there was an interleaved mutation. In concurrent mode
151 // this can happen all the time, but even in synchronous mode, an earlier
152 // effect may have mutated the store.
153
154 if (checkIfSnapshotChanged(inst)) {
155 // Force a re-render.
156 forceUpdate({
157 inst
158 });
159 } // eslint-disable-next-line react-hooks/exhaustive-deps
160
161 }, [subscribe, value, getSnapshot]);
162 useEffect(() => {
163 // Check for changes right before subscribing. Subsequent changes will be
164 // detected in the subscription handler.
165 if (checkIfSnapshotChanged(inst)) {
166 // Force a re-render.
167 forceUpdate({
168 inst
169 });
170 }
171
172 const handleStoreChange = () => {
173 // TODO: Because there is no cross-renderer API for batching updates, it's
174 // up to the consumer of this library to wrap their subscription event
175 // with unstable_batchedUpdates. Should we try to detect when this isn't
176 // the case and print a warning in development?
177 // The store changed. Check if the snapshot changed since the last time we
178 // read from the store.
179 if (checkIfSnapshotChanged(inst)) {
180 // Force a re-render.
181 forceUpdate({
182 inst
183 });
184 }
185 }; // Subscribe to the store and return a clean-up function.
186
187
188 return subscribe(handleStoreChange); // eslint-disable-next-line react-hooks/exhaustive-deps
189 }, [subscribe]);
190 useDebugValue(value);
191 return value;
192 }
193
194 function checkIfSnapshotChanged(inst) {
195 const latestGetSnapshot = inst.getSnapshot;
196 const prevValue = inst.value;
197
198 try {
199 const nextValue = latestGetSnapshot();
200 return !is(prevValue, nextValue);
201 } catch (error) {
202 return true;
203 }
204 }
205
206 /**
207 * Copyright (c) Facebook, Inc. and its affiliates.
208 *
209 * This source code is licensed under the MIT license found in the
210 * LICENSE file in the root directory of this source tree.
211 *
212 * @flow
213 */
214 function useSyncExternalStore$1(subscribe, getSnapshot, getServerSnapshot) {
215 // Note: The shim does not use getServerSnapshot, because pre-18 versions of
216 // React do not expose a way to check if we're hydrating. So users of the shim
217 // will need to track that themselves and return the correct value
218 // from `getSnapshot`.
219 return getSnapshot();
220 }
221
222 /**
223 * Inlined into the react-router repo since use-sync-external-store does not
224 * provide a UMD-compatible package, so we need this to be able to distribute
225 * UMD react-router bundles
226 */
227 const canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined");
228 const isServerEnvironment = !canUseDOM;
229 const shim = isServerEnvironment ? useSyncExternalStore$1 : useSyncExternalStore$2;
230 const useSyncExternalStore = "useSyncExternalStore" in React__namespace ? (module => module.useSyncExternalStore)(React__namespace) : shim;
231
232 const DataRouterContext = /*#__PURE__*/React__namespace.createContext(null);
233
234 {
235 DataRouterContext.displayName = "DataRouter";
236 }
237
238 const DataRouterStateContext = /*#__PURE__*/React__namespace.createContext(null);
239
240 {
241 DataRouterStateContext.displayName = "DataRouterState";
242 }
243
244 const AwaitContext = /*#__PURE__*/React__namespace.createContext(null);
245
246 {
247 AwaitContext.displayName = "Await";
248 }
249
250 const NavigationContext = /*#__PURE__*/React__namespace.createContext(null);
251
252 {
253 NavigationContext.displayName = "Navigation";
254 }
255
256 const LocationContext = /*#__PURE__*/React__namespace.createContext(null);
257
258 {
259 LocationContext.displayName = "Location";
260 }
261
262 const RouteContext = /*#__PURE__*/React__namespace.createContext({
263 outlet: null,
264 matches: []
265 });
266
267 {
268 RouteContext.displayName = "Route";
269 }
270
271 const RouteErrorContext = /*#__PURE__*/React__namespace.createContext(null);
272
273 {
274 RouteErrorContext.displayName = "RouteError";
275 }
276
277 /**
278 * Returns the full href for the given "to" value. This is useful for building
279 * custom links that are also accessible and preserve right-click behavior.
280 *
281 * @see https://reactrouter.com/hooks/use-href
282 */
283
284 function useHref(to, _temp) {
285 let {
286 relative
287 } = _temp === void 0 ? {} : _temp;
288 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
289 // router loaded. We can help them understand how to avoid that.
290 "useHref() may be used only in the context of a <Router> component.") : void 0;
291 let {
292 basename,
293 navigator
294 } = React__namespace.useContext(NavigationContext);
295 let {
296 hash,
297 pathname,
298 search
299 } = useResolvedPath(to, {
300 relative
301 });
302 let joinedPathname = pathname; // If we're operating within a basename, prepend it to the pathname prior
303 // to creating the href. If this is a root navigation, then just use the raw
304 // basename which allows the basename to have full control over the presence
305 // of a trailing slash on root links
306
307 if (basename !== "/") {
308 joinedPathname = pathname === "/" ? basename : router.joinPaths([basename, pathname]);
309 }
310
311 return navigator.createHref({
312 pathname: joinedPathname,
313 search,
314 hash
315 });
316 }
317 /**
318 * Returns true if this component is a descendant of a <Router>.
319 *
320 * @see https://reactrouter.com/hooks/use-in-router-context
321 */
322
323 function useInRouterContext() {
324 return React__namespace.useContext(LocationContext) != null;
325 }
326 /**
327 * Returns the current location object, which represents the current URL in web
328 * browsers.
329 *
330 * Note: If you're using this it may mean you're doing some of your own
331 * "routing" in your app, and we'd like to know what your use case is. We may
332 * be able to provide something higher-level to better suit your needs.
333 *
334 * @see https://reactrouter.com/hooks/use-location
335 */
336
337 function useLocation() {
338 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
339 // router loaded. We can help them understand how to avoid that.
340 "useLocation() may be used only in the context of a <Router> component.") : void 0;
341 return React__namespace.useContext(LocationContext).location;
342 }
343 /**
344 * Returns the current navigation action which describes how the router came to
345 * the current location, either by a pop, push, or replace on the history stack.
346 *
347 * @see https://reactrouter.com/hooks/use-navigation-type
348 */
349
350 function useNavigationType() {
351 return React__namespace.useContext(LocationContext).navigationType;
352 }
353 /**
354 * Returns a PathMatch object if the given pattern matches the current URL.
355 * This is useful for components that need to know "active" state, e.g.
356 * <NavLink>.
357 *
358 * @see https://reactrouter.com/hooks/use-match
359 */
360
361 function useMatch(pattern) {
362 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
363 // router loaded. We can help them understand how to avoid that.
364 "useMatch() may be used only in the context of a <Router> component.") : void 0;
365 let {
366 pathname
367 } = useLocation();
368 return React__namespace.useMemo(() => router.matchPath(pattern, pathname), [pathname, pattern]);
369 }
370 /**
371 * The interface for the navigate() function returned from useNavigate().
372 */
373
374 /**
375 * Returns an imperative method for changing the location. Used by <Link>s, but
376 * may also be used by other elements to change the location.
377 *
378 * @see https://reactrouter.com/hooks/use-navigate
379 */
380 function useNavigate() {
381 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
382 // router loaded. We can help them understand how to avoid that.
383 "useNavigate() may be used only in the context of a <Router> component.") : void 0;
384 let {
385 basename,
386 navigator
387 } = React__namespace.useContext(NavigationContext);
388 let {
389 matches
390 } = React__namespace.useContext(RouteContext);
391 let {
392 pathname: locationPathname
393 } = useLocation();
394 let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
395 let activeRef = React__namespace.useRef(false);
396 React__namespace.useEffect(() => {
397 activeRef.current = true;
398 });
399 let navigate = React__namespace.useCallback(function (to, options) {
400 if (options === void 0) {
401 options = {};
402 }
403
404 router.warning(activeRef.current, "You should call navigate() in a React.useEffect(), not when " + "your component is first rendered.") ;
405 if (!activeRef.current) return;
406
407 if (typeof to === "number") {
408 navigator.go(to);
409 return;
410 }
411
412 let path = router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === "path"); // If we're operating within a basename, prepend it to the pathname prior
413 // to handing off to history. If this is a root navigation, then we
414 // navigate to the raw basename which allows the basename to have full
415 // control over the presence of a trailing slash on root links
416
417 if (basename !== "/") {
418 path.pathname = path.pathname === "/" ? basename : router.joinPaths([basename, path.pathname]);
419 }
420
421 (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);
422 }, [basename, navigator, routePathnamesJson, locationPathname]);
423 return navigate;
424 }
425 const OutletContext = /*#__PURE__*/React__namespace.createContext(null);
426 /**
427 * Returns the context (if provided) for the child route at this level of the route
428 * hierarchy.
429 * @see https://reactrouter.com/hooks/use-outlet-context
430 */
431
432 function useOutletContext() {
433 return React__namespace.useContext(OutletContext);
434 }
435 /**
436 * Returns the element for the child route at this level of the route
437 * hierarchy. Used internally by <Outlet> to render child routes.
438 *
439 * @see https://reactrouter.com/hooks/use-outlet
440 */
441
442 function useOutlet(context) {
443 let outlet = React__namespace.useContext(RouteContext).outlet;
444
445 if (outlet) {
446 return /*#__PURE__*/React__namespace.createElement(OutletContext.Provider, {
447 value: context
448 }, outlet);
449 }
450
451 return outlet;
452 }
453 /**
454 * Returns an object of key/value pairs of the dynamic params from the current
455 * URL that were matched by the route path.
456 *
457 * @see https://reactrouter.com/hooks/use-params
458 */
459
460 function useParams() {
461 let {
462 matches
463 } = React__namespace.useContext(RouteContext);
464 let routeMatch = matches[matches.length - 1];
465 return routeMatch ? routeMatch.params : {};
466 }
467 /**
468 * Resolves the pathname of the given `to` value against the current location.
469 *
470 * @see https://reactrouter.com/hooks/use-resolved-path
471 */
472
473 function useResolvedPath(to, _temp2) {
474 let {
475 relative
476 } = _temp2 === void 0 ? {} : _temp2;
477 let {
478 matches
479 } = React__namespace.useContext(RouteContext);
480 let {
481 pathname: locationPathname
482 } = useLocation();
483 let routePathnamesJson = JSON.stringify(router.UNSAFE_getPathContributingMatches(matches).map(match => match.pathnameBase));
484 return React__namespace.useMemo(() => router.resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === "path"), [to, routePathnamesJson, locationPathname, relative]);
485 }
486 /**
487 * Returns the element of the route that matched the current location, prepared
488 * with the correct context to render the remainder of the route tree. Route
489 * elements in the tree must render an <Outlet> to render their child route's
490 * element.
491 *
492 * @see https://reactrouter.com/hooks/use-routes
493 */
494
495 function useRoutes(routes, locationArg) {
496 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of the
497 // router loaded. We can help them understand how to avoid that.
498 "useRoutes() may be used only in the context of a <Router> component.") : void 0;
499 let {
500 navigator
501 } = React__namespace.useContext(NavigationContext);
502 let dataRouterStateContext = React__namespace.useContext(DataRouterStateContext);
503 let {
504 matches: parentMatches
505 } = React__namespace.useContext(RouteContext);
506 let routeMatch = parentMatches[parentMatches.length - 1];
507 let parentParams = routeMatch ? routeMatch.params : {};
508 let parentPathname = routeMatch ? routeMatch.pathname : "/";
509 let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : "/";
510 let parentRoute = routeMatch && routeMatch.route;
511
512 {
513 // You won't get a warning about 2 different <Routes> under a <Route>
514 // without a trailing *, but this is a best-effort warning anyway since we
515 // cannot even give the warning unless they land at the parent route.
516 //
517 // Example:
518 //
519 // <Routes>
520 // {/* This route path MUST end with /* because otherwise
521 // it will never match /blog/post/123 */}
522 // <Route path="blog" element={<Blog />} />
523 // <Route path="blog/feed" element={<BlogFeed />} />
524 // </Routes>
525 //
526 // function Blog() {
527 // return (
528 // <Routes>
529 // <Route path="post/:id" element={<Post />} />
530 // </Routes>
531 // );
532 // }
533 let parentPath = parentRoute && parentRoute.path || "";
534 warningOnce(parentPathname, !parentRoute || parentPath.endsWith("*"), "You rendered descendant <Routes> (or called `useRoutes()`) at " + ("\"" + parentPathname + "\" (under <Route path=\"" + parentPath + "\">) but the ") + "parent route path has no trailing \"*\". This means if you navigate " + "deeper, the parent won't match anymore and therefore the child " + "routes will never render.\n\n" + ("Please change the parent <Route path=\"" + parentPath + "\"> to <Route ") + ("path=\"" + (parentPath === "/" ? "*" : parentPath + "/*") + "\">."));
535 }
536
537 let locationFromContext = useLocation();
538 let location;
539
540 if (locationArg) {
541 var _parsedLocationArg$pa;
542
543 let parsedLocationArg = typeof locationArg === "string" ? router.parsePath(locationArg) : locationArg;
544 !(parentPathnameBase === "/" || ((_parsedLocationArg$pa = parsedLocationArg.pathname) == null ? void 0 : _parsedLocationArg$pa.startsWith(parentPathnameBase))) ? router.invariant(false, "When overriding the location using `<Routes location>` or `useRoutes(routes, location)`, " + "the location pathname must begin with the portion of the URL pathname that was " + ("matched by all parent routes. The current pathname base is \"" + parentPathnameBase + "\" ") + ("but pathname \"" + parsedLocationArg.pathname + "\" was given in the `location` prop.")) : void 0;
545 location = parsedLocationArg;
546 } else {
547 location = locationFromContext;
548 }
549
550 let pathname = location.pathname || "/";
551 let remainingPathname = parentPathnameBase === "/" ? pathname : pathname.slice(parentPathnameBase.length) || "/";
552 let matches = router.matchRoutes(routes, {
553 pathname: remainingPathname
554 });
555
556 {
557 router.warning(parentRoute || matches != null, "No routes matched location \"" + location.pathname + location.search + location.hash + "\" ") ;
558 router.warning(matches == null || matches[matches.length - 1].route.element !== undefined, "Matched leaf route at location \"" + location.pathname + location.search + location.hash + "\" does not have an element. " + "This means it will render an <Outlet /> with a null value by default resulting in an \"empty\" page.") ;
559 }
560
561 let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {
562 params: Object.assign({}, parentParams, match.params),
563 pathname: router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
564 navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),
565 pathnameBase: match.pathnameBase === "/" ? parentPathnameBase : router.joinPaths([parentPathnameBase, // Re-encode pathnames that were decoded inside matchRoutes
566 navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])
567 })), parentMatches, dataRouterStateContext || undefined); // When a user passes in a `locationArg`, the associated routes need to
568 // be wrapped in a new `LocationContext.Provider` in order for `useLocation`
569 // to use the scoped location instead of the global location.
570
571
572 if (locationArg && renderedMatches) {
573 return /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
574 value: {
575 location: _extends({
576 pathname: "/",
577 search: "",
578 hash: "",
579 state: null,
580 key: "default"
581 }, location),
582 navigationType: router.Action.Pop
583 }
584 }, renderedMatches);
585 }
586
587 return renderedMatches;
588 }
589
590 function DefaultErrorElement() {
591 let error = useRouteError();
592 let message = router.isRouteErrorResponse(error) ? error.status + " " + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);
593 let stack = error instanceof Error ? error.stack : null;
594 let lightgrey = "rgba(200,200,200, 0.5)";
595 let preStyles = {
596 padding: "0.5rem",
597 backgroundColor: lightgrey
598 };
599 let codeStyles = {
600 padding: "2px 4px",
601 backgroundColor: lightgrey
602 };
603 let devInfo = null;
604
605 {
606 devInfo = /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("p", null, "\uD83D\uDCBF Hey developer \uD83D\uDC4B"), /*#__PURE__*/React__namespace.createElement("p", null, "You can provide a way better UX than this when your app throws errors by providing your own\xA0", /*#__PURE__*/React__namespace.createElement("code", {
607 style: codeStyles
608 }, "errorElement"), " props on\xA0", /*#__PURE__*/React__namespace.createElement("code", {
609 style: codeStyles
610 }, "<Route>")));
611 }
612
613 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement("h2", null, "Unexpected Application Error!"), /*#__PURE__*/React__namespace.createElement("h3", {
614 style: {
615 fontStyle: "italic"
616 }
617 }, message), stack ? /*#__PURE__*/React__namespace.createElement("pre", {
618 style: preStyles
619 }, stack) : null, devInfo);
620 }
621
622 class RenderErrorBoundary extends React__namespace.Component {
623 constructor(props) {
624 super(props);
625 this.state = {
626 location: props.location,
627 error: props.error
628 };
629 }
630
631 static getDerivedStateFromError(error) {
632 return {
633 error: error
634 };
635 }
636
637 static getDerivedStateFromProps(props, state) {
638 // When we get into an error state, the user will likely click "back" to the
639 // previous page that didn't have an error. Because this wraps the entire
640 // application, that will have no effect--the error page continues to display.
641 // This gives us a mechanism to recover from the error when the location changes.
642 //
643 // Whether we're in an error state or not, we update the location in state
644 // so that when we are in an error state, it gets reset when a new location
645 // comes in and the user recovers from the error.
646 if (state.location !== props.location) {
647 return {
648 error: props.error,
649 location: props.location
650 };
651 } // If we're not changing locations, preserve the location but still surface
652 // any new errors that may come through. We retain the existing error, we do
653 // this because the error provided from the app state may be cleared without
654 // the location changing.
655
656
657 return {
658 error: props.error || state.error,
659 location: state.location
660 };
661 }
662
663 componentDidCatch(error, errorInfo) {
664 console.error("React Router caught the following error during render", error, errorInfo);
665 }
666
667 render() {
668 return this.state.error ? /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
669 value: this.props.routeContext
670 }, /*#__PURE__*/React__namespace.createElement(RouteErrorContext.Provider, {
671 value: this.state.error,
672 children: this.props.component
673 })) : this.props.children;
674 }
675
676 }
677
678 function RenderedRoute(_ref) {
679 let {
680 routeContext,
681 match,
682 children
683 } = _ref;
684 let dataRouterContext = React__namespace.useContext(DataRouterContext); // Track how deep we got in our render pass to emulate SSR componentDidCatch
685 // in a DataStaticRouter
686
687 if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && match.route.errorElement) {
688 dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;
689 }
690
691 return /*#__PURE__*/React__namespace.createElement(RouteContext.Provider, {
692 value: routeContext
693 }, children);
694 }
695
696 function _renderMatches(matches, parentMatches, dataRouterState) {
697 if (parentMatches === void 0) {
698 parentMatches = [];
699 }
700
701 if (matches == null) {
702 if (dataRouterState != null && dataRouterState.errors) {
703 // Don't bail if we have data router errors so we can render them in the
704 // boundary. Use the pre-matched (or shimmed) matches
705 matches = dataRouterState.matches;
706 } else {
707 return null;
708 }
709 }
710
711 let renderedMatches = matches; // If we have data errors, trim matches to the highest error boundary
712
713 let errors = dataRouterState == null ? void 0 : dataRouterState.errors;
714
715 if (errors != null) {
716 let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]));
717 !(errorIndex >= 0) ? router.invariant(false, "Could not find a matching route for the current errors: " + errors) : void 0;
718 renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));
719 }
720
721 return renderedMatches.reduceRight((outlet, match, index) => {
722 let error = match.route.id ? errors == null ? void 0 : errors[match.route.id] : null; // Only data routers handle errors
723
724 let errorElement = dataRouterState ? match.route.errorElement || /*#__PURE__*/React__namespace.createElement(DefaultErrorElement, null) : null;
725 let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));
726
727 let getChildren = () => /*#__PURE__*/React__namespace.createElement(RenderedRoute, {
728 match: match,
729 routeContext: {
730 outlet,
731 matches
732 }
733 }, error ? errorElement : match.route.element !== undefined ? match.route.element : outlet); // Only wrap in an error boundary within data router usages when we have an
734 // errorElement on this route. Otherwise let it bubble up to an ancestor
735 // errorElement
736
737
738 return dataRouterState && (match.route.errorElement || index === 0) ? /*#__PURE__*/React__namespace.createElement(RenderErrorBoundary, {
739 location: dataRouterState.location,
740 component: errorElement,
741 error: error,
742 children: getChildren(),
743 routeContext: {
744 outlet: null,
745 matches
746 }
747 }) : getChildren();
748 }, null);
749 }
750 var DataRouterHook;
751
752 (function (DataRouterHook) {
753 DataRouterHook["UseBlocker"] = "useBlocker";
754 DataRouterHook["UseRevalidator"] = "useRevalidator";
755 })(DataRouterHook || (DataRouterHook = {}));
756
757 var DataRouterStateHook;
758
759 (function (DataRouterStateHook) {
760 DataRouterStateHook["UseLoaderData"] = "useLoaderData";
761 DataRouterStateHook["UseActionData"] = "useActionData";
762 DataRouterStateHook["UseRouteError"] = "useRouteError";
763 DataRouterStateHook["UseNavigation"] = "useNavigation";
764 DataRouterStateHook["UseRouteLoaderData"] = "useRouteLoaderData";
765 DataRouterStateHook["UseMatches"] = "useMatches";
766 DataRouterStateHook["UseRevalidator"] = "useRevalidator";
767 })(DataRouterStateHook || (DataRouterStateHook = {}));
768
769 function getDataRouterConsoleError(hookName) {
770 return hookName + " must be used within a data router. See https://reactrouter.com/routers/picking-a-router.";
771 }
772
773 function useDataRouterContext(hookName) {
774 let ctx = React__namespace.useContext(DataRouterContext);
775 !ctx ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
776 return ctx;
777 }
778
779 function useDataRouterState(hookName) {
780 let state = React__namespace.useContext(DataRouterStateContext);
781 !state ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
782 return state;
783 }
784
785 function useRouteContext(hookName) {
786 let route = React__namespace.useContext(RouteContext);
787 !route ? router.invariant(false, getDataRouterConsoleError(hookName)) : void 0;
788 return route;
789 }
790
791 function useCurrentRouteId(hookName) {
792 let route = useRouteContext(hookName);
793 let thisRoute = route.matches[route.matches.length - 1];
794 !thisRoute.route.id ? router.invariant(false, hookName + " can only be used on routes that contain a unique \"id\"") : void 0;
795 return thisRoute.route.id;
796 }
797 /**
798 * Returns the current navigation, defaulting to an "idle" navigation when
799 * no navigation is in progress
800 */
801
802
803 function useNavigation() {
804 let state = useDataRouterState(DataRouterStateHook.UseNavigation);
805 return state.navigation;
806 }
807 /**
808 * Returns a revalidate function for manually triggering revalidation, as well
809 * as the current state of any manual revalidations
810 */
811
812 function useRevalidator() {
813 let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);
814 let state = useDataRouterState(DataRouterStateHook.UseRevalidator);
815 return {
816 revalidate: dataRouterContext.router.revalidate,
817 state: state.revalidation
818 };
819 }
820 /**
821 * Returns the active route matches, useful for accessing loaderData for
822 * parent/child routes or the route "handle" property
823 */
824
825 function useMatches() {
826 let {
827 matches,
828 loaderData
829 } = useDataRouterState(DataRouterStateHook.UseMatches);
830 return React__namespace.useMemo(() => matches.map(match => {
831 let {
832 pathname,
833 params
834 } = match; // Note: This structure matches that created by createUseMatchesMatch
835 // in the @remix-run/router , so if you change this please also change
836 // that :) Eventually we'll DRY this up
837
838 return {
839 id: match.route.id,
840 pathname,
841 params,
842 data: loaderData[match.route.id],
843 handle: match.route.handle
844 };
845 }), [matches, loaderData]);
846 }
847 /**
848 * Returns the loader data for the nearest ancestor Route loader
849 */
850
851 function useLoaderData() {
852 let state = useDataRouterState(DataRouterStateHook.UseLoaderData);
853 let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);
854
855 if (state.errors && state.errors[routeId] != null) {
856 console.error("You cannot `useLoaderData` in an errorElement (routeId: " + routeId + ")");
857 return undefined;
858 }
859
860 return state.loaderData[routeId];
861 }
862 /**
863 * Returns the loaderData for the given routeId
864 */
865
866 function useRouteLoaderData(routeId) {
867 let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);
868 return state.loaderData[routeId];
869 }
870 /**
871 * Returns the action data for the nearest ancestor Route action
872 */
873
874 function useActionData() {
875 let state = useDataRouterState(DataRouterStateHook.UseActionData);
876 let route = React__namespace.useContext(RouteContext);
877 !route ? router.invariant(false, "useActionData must be used inside a RouteContext") : void 0;
878 return Object.values((state == null ? void 0 : state.actionData) || {})[0];
879 }
880 /**
881 * Returns the nearest ancestor Route error, which could be a loader/action
882 * error or a render error. This is intended to be called from your
883 * errorElement to display a proper error message.
884 */
885
886 function useRouteError() {
887 var _state$errors;
888
889 let error = React__namespace.useContext(RouteErrorContext);
890 let state = useDataRouterState(DataRouterStateHook.UseRouteError);
891 let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError); // If this was a render error, we put it in a RouteError context inside
892 // of RenderErrorBoundary
893
894 if (error) {
895 return error;
896 } // Otherwise look for errors from our data router state
897
898
899 return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];
900 }
901 /**
902 * Returns the happy-path data from the nearest ancestor <Await /> value
903 */
904
905 function useAsyncValue() {
906 let value = React__namespace.useContext(AwaitContext);
907 return value == null ? void 0 : value._data;
908 }
909 /**
910 * Returns the error from the nearest ancestor <Await /> value
911 */
912
913 function useAsyncError() {
914 let value = React__namespace.useContext(AwaitContext);
915 return value == null ? void 0 : value._error;
916 } // useBlocker() is a singleton for now since we don't have any compelling use
917 // cases for multi-blocker yet
918
919 let blockerKey = "blocker-singleton";
920 /**
921 * Allow the application to block navigations within the SPA and present the
922 * user a confirmation dialog to confirm the navigation. Mostly used to avoid
923 * using half-filled form data. This does not handle hard-reloads or
924 * cross-origin navigations.
925 */
926
927 function useBlocker(shouldBlock) {
928 let {
929 router
930 } = useDataRouterContext(DataRouterHook.UseBlocker);
931 let blockerFunction = React__namespace.useCallback(args => {
932 return typeof shouldBlock === "function" ? !!shouldBlock(args) : !!shouldBlock;
933 }, [shouldBlock]);
934 let blocker = router.getBlocker(blockerKey, blockerFunction); // Cleanup on unmount
935
936 React__namespace.useEffect(() => () => router.deleteBlocker(blockerKey), [router]);
937 return blocker;
938 }
939 const alreadyWarned = {};
940
941 function warningOnce(key, cond, message) {
942 if (!cond && !alreadyWarned[key]) {
943 alreadyWarned[key] = true;
944 router.warning(false, message) ;
945 }
946 }
947
948 /**
949 * Given a Remix Router instance, render the appropriate UI
950 */
951 function RouterProvider(_ref) {
952 let {
953 fallbackElement,
954 router
955 } = _ref;
956 // Sync router state to our component state to force re-renders
957 let state = useSyncExternalStore(router.subscribe, () => router.state, // We have to provide this so React@18 doesn't complain during hydration,
958 // but we pass our serialized hydration data into the router so state here
959 // is already synced with what the server saw
960 () => router.state);
961 let navigator = React__namespace.useMemo(() => {
962 return {
963 createHref: router.createHref,
964 encodeLocation: router.encodeLocation,
965 go: n => router.navigate(n),
966 push: (to, state, opts) => router.navigate(to, {
967 state,
968 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
969 }),
970 replace: (to, state, opts) => router.navigate(to, {
971 replace: true,
972 state,
973 preventScrollReset: opts == null ? void 0 : opts.preventScrollReset
974 })
975 };
976 }, [router]);
977 let basename = router.basename || "/"; // The fragment and {null} here are important! We need them to keep React 18's
978 // useId happy when we are server-rendering since we may have a <script> here
979 // containing the hydrated server-side staticContext (from StaticRouterProvider).
980 // useId relies on the component tree structure to generate deterministic id's
981 // so we need to ensure it remains the same on the client even though
982 // we don't need the <script> tag
983
984 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(DataRouterContext.Provider, {
985 value: {
986 router,
987 navigator,
988 static: false,
989 // Do we need this?
990 basename
991 }
992 }, /*#__PURE__*/React__namespace.createElement(DataRouterStateContext.Provider, {
993 value: state
994 }, /*#__PURE__*/React__namespace.createElement(Router, {
995 basename: router.basename,
996 location: router.state.location,
997 navigationType: router.state.historyAction,
998 navigator: navigator
999 }, router.state.initialized ? /*#__PURE__*/React__namespace.createElement(Routes, null) : fallbackElement))), null);
1000 }
1001
1002 /**
1003 * A <Router> that stores all entries in memory.
1004 *
1005 * @see https://reactrouter.com/router-components/memory-router
1006 */
1007 function MemoryRouter(_ref2) {
1008 let {
1009 basename,
1010 children,
1011 initialEntries,
1012 initialIndex
1013 } = _ref2;
1014 let historyRef = React__namespace.useRef();
1015
1016 if (historyRef.current == null) {
1017 historyRef.current = router.createMemoryHistory({
1018 initialEntries,
1019 initialIndex,
1020 v5Compat: true
1021 });
1022 }
1023
1024 let history = historyRef.current;
1025 let [state, setState] = React__namespace.useState({
1026 action: history.action,
1027 location: history.location
1028 });
1029 React__namespace.useLayoutEffect(() => history.listen(setState), [history]);
1030 return /*#__PURE__*/React__namespace.createElement(Router, {
1031 basename: basename,
1032 children: children,
1033 location: state.location,
1034 navigationType: state.action,
1035 navigator: history
1036 });
1037 }
1038
1039 /**
1040 * Changes the current location.
1041 *
1042 * Note: This API is mostly useful in React.Component subclasses that are not
1043 * able to use hooks. In functional components, we recommend you use the
1044 * `useNavigate` hook instead.
1045 *
1046 * @see https://reactrouter.com/components/navigate
1047 */
1048 function Navigate(_ref3) {
1049 let {
1050 to,
1051 replace,
1052 state,
1053 relative
1054 } = _ref3;
1055 !useInRouterContext() ? router.invariant(false, // TODO: This error is probably because they somehow have 2 versions of
1056 // the router loaded. We can help them understand how to avoid that.
1057 "<Navigate> may be used only in the context of a <Router> component.") : void 0;
1058 router.warning(!React__namespace.useContext(NavigationContext).static, "<Navigate> must not be used on the initial render in a <StaticRouter>. " + "This is a no-op, but you should modify your code so the <Navigate> is " + "only ever rendered in response to some user interaction or state change.") ;
1059 let dataRouterState = React__namespace.useContext(DataRouterStateContext);
1060 let navigate = useNavigate();
1061 React__namespace.useEffect(() => {
1062 // Avoid kicking off multiple navigations if we're in the middle of a
1063 // data-router navigation, since components get re-rendered when we enter
1064 // a submitting/loading state
1065 if (dataRouterState && dataRouterState.navigation.state !== "idle") {
1066 return;
1067 }
1068
1069 navigate(to, {
1070 replace,
1071 state,
1072 relative
1073 });
1074 });
1075 return null;
1076 }
1077
1078 /**
1079 * Renders the child route's element, if there is one.
1080 *
1081 * @see https://reactrouter.com/components/outlet
1082 */
1083 function Outlet(props) {
1084 return useOutlet(props.context);
1085 }
1086
1087 /**
1088 * Declares an element that should be rendered at a certain URL path.
1089 *
1090 * @see https://reactrouter.com/components/route
1091 */
1092 function Route(_props) {
1093 router.invariant(false, "A <Route> is only ever to be used as the child of <Routes> element, " + "never rendered directly. Please wrap your <Route> in a <Routes>.") ;
1094 }
1095
1096 /**
1097 * Provides location context for the rest of the app.
1098 *
1099 * Note: You usually won't render a <Router> directly. Instead, you'll render a
1100 * router that is more specific to your environment such as a <BrowserRouter>
1101 * in web browsers or a <StaticRouter> for server rendering.
1102 *
1103 * @see https://reactrouter.com/router-components/router
1104 */
1105 function Router(_ref4) {
1106 let {
1107 basename: basenameProp = "/",
1108 children = null,
1109 location: locationProp,
1110 navigationType = router.Action.Pop,
1111 navigator,
1112 static: staticProp = false
1113 } = _ref4;
1114 !!useInRouterContext() ? router.invariant(false, "You cannot render a <Router> inside another <Router>." + " You should never have more than one in your app.") : void 0; // Preserve trailing slashes on basename, so we can let the user control
1115 // the enforcement of trailing slashes throughout the app
1116
1117 let basename = basenameProp.replace(/^\/*/, "/");
1118 let navigationContext = React__namespace.useMemo(() => ({
1119 basename,
1120 navigator,
1121 static: staticProp
1122 }), [basename, navigator, staticProp]);
1123
1124 if (typeof locationProp === "string") {
1125 locationProp = router.parsePath(locationProp);
1126 }
1127
1128 let {
1129 pathname = "/",
1130 search = "",
1131 hash = "",
1132 state = null,
1133 key = "default"
1134 } = locationProp;
1135 let location = React__namespace.useMemo(() => {
1136 let trailingPathname = router.stripBasename(pathname, basename);
1137
1138 if (trailingPathname == null) {
1139 return null;
1140 }
1141
1142 return {
1143 pathname: trailingPathname,
1144 search,
1145 hash,
1146 state,
1147 key
1148 };
1149 }, [basename, pathname, search, hash, state, key]);
1150 router.warning(location != null, "<Router basename=\"" + basename + "\"> is not able to match the URL " + ("\"" + pathname + search + hash + "\" because it does not start with the ") + "basename, so the <Router> won't render anything.") ;
1151
1152 if (location == null) {
1153 return null;
1154 }
1155
1156 return /*#__PURE__*/React__namespace.createElement(NavigationContext.Provider, {
1157 value: navigationContext
1158 }, /*#__PURE__*/React__namespace.createElement(LocationContext.Provider, {
1159 children: children,
1160 value: {
1161 location,
1162 navigationType
1163 }
1164 }));
1165 }
1166
1167 /**
1168 * A container for a nested tree of <Route> elements that renders the branch
1169 * that best matches the current location.
1170 *
1171 * @see https://reactrouter.com/components/routes
1172 */
1173 function Routes(_ref5) {
1174 let {
1175 children,
1176 location
1177 } = _ref5;
1178 let dataRouterContext = React__namespace.useContext(DataRouterContext); // When in a DataRouterContext _without_ children, we use the router routes
1179 // directly. If we have children, then we're in a descendant tree and we
1180 // need to use child routes.
1181
1182 let routes = dataRouterContext && !children ? dataRouterContext.router.routes : createRoutesFromChildren(children);
1183 return useRoutes(routes, location);
1184 }
1185
1186 /**
1187 * Component to use for rendering lazily loaded data from returning defer()
1188 * in a loader function
1189 */
1190 function Await(_ref6) {
1191 let {
1192 children,
1193 errorElement,
1194 resolve
1195 } = _ref6;
1196 return /*#__PURE__*/React__namespace.createElement(AwaitErrorBoundary, {
1197 resolve: resolve,
1198 errorElement: errorElement
1199 }, /*#__PURE__*/React__namespace.createElement(ResolveAwait, null, children));
1200 }
1201 var AwaitRenderStatus;
1202
1203 (function (AwaitRenderStatus) {
1204 AwaitRenderStatus[AwaitRenderStatus["pending"] = 0] = "pending";
1205 AwaitRenderStatus[AwaitRenderStatus["success"] = 1] = "success";
1206 AwaitRenderStatus[AwaitRenderStatus["error"] = 2] = "error";
1207 })(AwaitRenderStatus || (AwaitRenderStatus = {}));
1208
1209 const neverSettledPromise = new Promise(() => {});
1210
1211 class AwaitErrorBoundary extends React__namespace.Component {
1212 constructor(props) {
1213 super(props);
1214 this.state = {
1215 error: null
1216 };
1217 }
1218
1219 static getDerivedStateFromError(error) {
1220 return {
1221 error
1222 };
1223 }
1224
1225 componentDidCatch(error, errorInfo) {
1226 console.error("<Await> caught the following error during render", error, errorInfo);
1227 }
1228
1229 render() {
1230 let {
1231 children,
1232 errorElement,
1233 resolve
1234 } = this.props;
1235 let promise = null;
1236 let status = AwaitRenderStatus.pending;
1237
1238 if (!(resolve instanceof Promise)) {
1239 // Didn't get a promise - provide as a resolved promise
1240 status = AwaitRenderStatus.success;
1241 promise = Promise.resolve();
1242 Object.defineProperty(promise, "_tracked", {
1243 get: () => true
1244 });
1245 Object.defineProperty(promise, "_data", {
1246 get: () => resolve
1247 });
1248 } else if (this.state.error) {
1249 // Caught a render error, provide it as a rejected promise
1250 status = AwaitRenderStatus.error;
1251 let renderError = this.state.error;
1252 promise = Promise.reject().catch(() => {}); // Avoid unhandled rejection warnings
1253
1254 Object.defineProperty(promise, "_tracked", {
1255 get: () => true
1256 });
1257 Object.defineProperty(promise, "_error", {
1258 get: () => renderError
1259 });
1260 } else if (resolve._tracked) {
1261 // Already tracked promise - check contents
1262 promise = resolve;
1263 status = promise._error !== undefined ? AwaitRenderStatus.error : promise._data !== undefined ? AwaitRenderStatus.success : AwaitRenderStatus.pending;
1264 } else {
1265 // Raw (untracked) promise - track it
1266 status = AwaitRenderStatus.pending;
1267 Object.defineProperty(resolve, "_tracked", {
1268 get: () => true
1269 });
1270 promise = resolve.then(data => Object.defineProperty(resolve, "_data", {
1271 get: () => data
1272 }), error => Object.defineProperty(resolve, "_error", {
1273 get: () => error
1274 }));
1275 }
1276
1277 if (status === AwaitRenderStatus.error && promise._error instanceof router.AbortedDeferredError) {
1278 // Freeze the UI by throwing a never resolved promise
1279 throw neverSettledPromise;
1280 }
1281
1282 if (status === AwaitRenderStatus.error && !errorElement) {
1283 // No errorElement, throw to the nearest route-level error boundary
1284 throw promise._error;
1285 }
1286
1287 if (status === AwaitRenderStatus.error) {
1288 // Render via our errorElement
1289 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1290 value: promise,
1291 children: errorElement
1292 });
1293 }
1294
1295 if (status === AwaitRenderStatus.success) {
1296 // Render children with resolved value
1297 return /*#__PURE__*/React__namespace.createElement(AwaitContext.Provider, {
1298 value: promise,
1299 children: children
1300 });
1301 } // Throw to the suspense boundary
1302
1303
1304 throw promise;
1305 }
1306
1307 }
1308 /**
1309 * @private
1310 * Indirection to leverage useAsyncValue for a render-prop API on <Await>
1311 */
1312
1313
1314 function ResolveAwait(_ref7) {
1315 let {
1316 children
1317 } = _ref7;
1318 let data = useAsyncValue();
1319 let toRender = typeof children === "function" ? children(data) : children;
1320 return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, toRender);
1321 } ///////////////////////////////////////////////////////////////////////////////
1322 // UTILS
1323 ///////////////////////////////////////////////////////////////////////////////
1324
1325 /**
1326 * Creates a route config from a React "children" object, which is usually
1327 * either a `<Route>` element or an array of them. Used internally by
1328 * `<Routes>` to create a route config from its children.
1329 *
1330 * @see https://reactrouter.com/utils/create-routes-from-children
1331 */
1332
1333
1334 function createRoutesFromChildren(children, parentPath) {
1335 if (parentPath === void 0) {
1336 parentPath = [];
1337 }
1338
1339 let routes = [];
1340 React__namespace.Children.forEach(children, (element, index) => {
1341 if (! /*#__PURE__*/React__namespace.isValidElement(element)) {
1342 // Ignore non-elements. This allows people to more easily inline
1343 // conditionals in their route config.
1344 return;
1345 }
1346
1347 if (element.type === React__namespace.Fragment) {
1348 // Transparently support React.Fragment and its children.
1349 routes.push.apply(routes, createRoutesFromChildren(element.props.children, parentPath));
1350 return;
1351 }
1352
1353 !(element.type === Route) ? router.invariant(false, "[" + (typeof element.type === "string" ? element.type : element.type.name) + "] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>") : void 0;
1354 !(!element.props.index || !element.props.children) ? router.invariant(false, "An index route cannot have child routes.") : void 0;
1355 let treePath = [...parentPath, index];
1356 let route = {
1357 id: element.props.id || treePath.join("-"),
1358 caseSensitive: element.props.caseSensitive,
1359 element: element.props.element,
1360 index: element.props.index,
1361 path: element.props.path,
1362 loader: element.props.loader,
1363 action: element.props.action,
1364 errorElement: element.props.errorElement,
1365 hasErrorBoundary: element.props.errorElement != null,
1366 shouldRevalidate: element.props.shouldRevalidate,
1367 handle: element.props.handle
1368 };
1369
1370 if (element.props.children) {
1371 route.children = createRoutesFromChildren(element.props.children, treePath);
1372 }
1373
1374 routes.push(route);
1375 });
1376 return routes;
1377 }
1378 /**
1379 * Renders the result of `matchRoutes()` into a React element.
1380 */
1381
1382 function renderMatches(matches) {
1383 return _renderMatches(matches);
1384 }
1385 /**
1386 * @private
1387 * Walk the route tree and add hasErrorBoundary if it's not provided, so that
1388 * users providing manual route arrays can just specify errorElement
1389 */
1390
1391 function enhanceManualRouteObjects(routes) {
1392 return routes.map(route => {
1393 let routeClone = _extends({}, route);
1394
1395 if (routeClone.hasErrorBoundary == null) {
1396 routeClone.hasErrorBoundary = routeClone.errorElement != null;
1397 }
1398
1399 if (routeClone.children) {
1400 routeClone.children = enhanceManualRouteObjects(routeClone.children);
1401 }
1402
1403 return routeClone;
1404 });
1405 }
1406
1407 function createMemoryRouter(routes, opts) {
1408 return router.createRouter({
1409 basename: opts == null ? void 0 : opts.basename,
1410 history: router.createMemoryHistory({
1411 initialEntries: opts == null ? void 0 : opts.initialEntries,
1412 initialIndex: opts == null ? void 0 : opts.initialIndex
1413 }),
1414 hydrationData: opts == null ? void 0 : opts.hydrationData,
1415 routes: enhanceManualRouteObjects(routes)
1416 }).initialize();
1417 } ///////////////////////////////////////////////////////////////////////////////
1418
1419 Object.defineProperty(exports, 'AbortedDeferredError', {
1420 enumerable: true,
1421 get: function () { return router.AbortedDeferredError; }
1422 });
1423 Object.defineProperty(exports, 'NavigationType', {
1424 enumerable: true,
1425 get: function () { return router.Action; }
1426 });
1427 Object.defineProperty(exports, 'createPath', {
1428 enumerable: true,
1429 get: function () { return router.createPath; }
1430 });
1431 Object.defineProperty(exports, 'defer', {
1432 enumerable: true,
1433 get: function () { return router.defer; }
1434 });
1435 Object.defineProperty(exports, 'generatePath', {
1436 enumerable: true,
1437 get: function () { return router.generatePath; }
1438 });
1439 Object.defineProperty(exports, 'isRouteErrorResponse', {
1440 enumerable: true,
1441 get: function () { return router.isRouteErrorResponse; }
1442 });
1443 Object.defineProperty(exports, 'json', {
1444 enumerable: true,
1445 get: function () { return router.json; }
1446 });
1447 Object.defineProperty(exports, 'matchPath', {
1448 enumerable: true,
1449 get: function () { return router.matchPath; }
1450 });
1451 Object.defineProperty(exports, 'matchRoutes', {
1452 enumerable: true,
1453 get: function () { return router.matchRoutes; }
1454 });
1455 Object.defineProperty(exports, 'parsePath', {
1456 enumerable: true,
1457 get: function () { return router.parsePath; }
1458 });
1459 Object.defineProperty(exports, 'redirect', {
1460 enumerable: true,
1461 get: function () { return router.redirect; }
1462 });
1463 Object.defineProperty(exports, 'resolvePath', {
1464 enumerable: true,
1465 get: function () { return router.resolvePath; }
1466 });
1467 exports.Await = Await;
1468 exports.MemoryRouter = MemoryRouter;
1469 exports.Navigate = Navigate;
1470 exports.Outlet = Outlet;
1471 exports.Route = Route;
1472 exports.Router = Router;
1473 exports.RouterProvider = RouterProvider;
1474 exports.Routes = Routes;
1475 exports.UNSAFE_DataRouterContext = DataRouterContext;
1476 exports.UNSAFE_DataRouterStateContext = DataRouterStateContext;
1477 exports.UNSAFE_LocationContext = LocationContext;
1478 exports.UNSAFE_NavigationContext = NavigationContext;
1479 exports.UNSAFE_RouteContext = RouteContext;
1480 exports.UNSAFE_enhanceManualRouteObjects = enhanceManualRouteObjects;
1481 exports.createMemoryRouter = createMemoryRouter;
1482 exports.createRoutesFromChildren = createRoutesFromChildren;
1483 exports.createRoutesFromElements = createRoutesFromChildren;
1484 exports.renderMatches = renderMatches;
1485 exports.unstable_useBlocker = useBlocker;
1486 exports.useActionData = useActionData;
1487 exports.useAsyncError = useAsyncError;
1488 exports.useAsyncValue = useAsyncValue;
1489 exports.useHref = useHref;
1490 exports.useInRouterContext = useInRouterContext;
1491 exports.useLoaderData = useLoaderData;
1492 exports.useLocation = useLocation;
1493 exports.useMatch = useMatch;
1494 exports.useMatches = useMatches;
1495 exports.useNavigate = useNavigate;
1496 exports.useNavigation = useNavigation;
1497 exports.useNavigationType = useNavigationType;
1498 exports.useOutlet = useOutlet;
1499 exports.useOutletContext = useOutletContext;
1500 exports.useParams = useParams;
1501 exports.useResolvedPath = useResolvedPath;
1502 exports.useRevalidator = useRevalidator;
1503 exports.useRouteError = useRouteError;
1504 exports.useRouteLoaderData = useRouteLoaderData;
1505 exports.useRoutes = useRoutes;
1506
1507 Object.defineProperty(exports, '__esModule', { value: true });
1508
1509}));
1510//# sourceMappingURL=react-router.development.js.map