UNPKG

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