{"version":3,"file":"index-D-MHGtOX.js","sources":["../node_modules/react/cjs/react.production.min.js","../node_modules/react/index.js","../node_modules/react/cjs/react-jsx-runtime.production.min.js","../node_modules/react/jsx-runtime.js","../node_modules/redux-persist/es/constants.js","../node_modules/redux-persist/es/stateReconciler/autoMergeLevel1.js","../node_modules/redux-persist/es/createPersistoid.js","../node_modules/redux-persist/es/getStoredState.js","../node_modules/redux-persist/es/purgeStoredState.js","../node_modules/redux-persist/es/persistReducer.js","../node_modules/redux/dist/redux.mjs","../node_modules/redux-persist/es/persistStore.js","../node_modules/immer/dist/immer.mjs","../node_modules/reselect/dist/reselect.mjs","../node_modules/redux-thunk/dist/redux-thunk.mjs","../node_modules/@reduxjs/toolkit/dist/redux-toolkit.modern.mjs","../src/host/store/app.slice.ts","../src/apps/path-finder/models/enum.ts","../src/apps/path-finder/config.ts","../src/apps/path-finder/helpers/grid.helper.ts","../src/apps/path-finder/store/path-finder.slice.ts","../src/apps/sorting-visualizer/store/global.state.ts","../src/lib/helpers/simulator.ts","../src/lib/helpers/async.ts","../src/apps/sorting-visualizer/helpers/algorithm-helpers.ts","../src/apps/sorting-visualizer/sorting-algorithms/heap.ts","../src/apps/sorting-visualizer/sorting-algorithms/merge.ts","../src/apps/sorting-visualizer/sorting-algorithms/algo-list.ts","../src/apps/sorting-visualizer/sorting-algorithms/bubble.ts","../src/apps/sorting-visualizer/sorting-algorithms/selection.ts","../src/apps/sorting-visualizer/sorting-algorithms/insertion.ts","../src/apps/sorting-visualizer/sorting-algorithms/quick.ts","../src/apps/sorting-visualizer/sorting-algorithms/shell.ts","../src/apps/sorting-visualizer/sorting-algorithms/cocktail.ts","../src/apps/sorting-visualizer/config.ts","../src/apps/sorting-visualizer/store/sorting-visualizer.slice.ts","../node_modules/redux-persist/lib/storage/getStorage.js","../node_modules/redux-persist/lib/storage/createWebStorage.js","../node_modules/redux-persist/lib/storage/index.js","../src/host/store/store.ts","../node_modules/scheduler/cjs/scheduler.production.min.js","../node_modules/scheduler/index.js","../node_modules/react-dom/cjs/react-dom.production.min.js","../node_modules/react-dom/index.js","../node_modules/@remix-run/router/dist/router.js","../node_modules/react-router/dist/index.js","../node_modules/react-router-dom/dist/index.js","../src/host/components/challenges/challenge-card.tsx","../src/host/config.ts","../src/host/components/challenges/challenges.tsx","../node_modules/lucide-react/dist/esm/defaultAttributes.js","../node_modules/lucide-react/dist/esm/shared/src/utils.js","../node_modules/lucide-react/dist/esm/createLucideIcon.js","../node_modules/lucide-react/dist/esm/icons/home.js","../node_modules/lucide-react/dist/esm/icons/info.js","../node_modules/lucide-react/dist/esm/icons/moon.js","../node_modules/lucide-react/dist/esm/icons/play.js","../node_modules/lucide-react/dist/esm/icons/refresh-ccw.js","../node_modules/lucide-react/dist/esm/icons/sun.js","../node_modules/lucide-react/dist/esm/icons/trash.js","../node_modules/lucide-react/dist/esm/icons/x.js","../src/lib/components/title/title.tsx","../src/lib/components/navbar/navbar.tsx","../node_modules/use-sync-external-store/cjs/use-sync-external-store-with-selector.production.min.js","../node_modules/use-sync-external-store/with-selector.js","../node_modules/react-redux/dist/react-redux.mjs","../src/host/store/hooks.ts","../src/host/types/interfaces.ts","../src/lib/components/theme-icon/theme-icon.tsx","../src/host/pages/index.page.tsx","../node_modules/sonner/dist/index.mjs","../node_modules/@gilbarbara/deep-equal/dist/index.mjs","../node_modules/react-joyride/node_modules/is-lite/dist/index.mjs","../node_modules/tree-changes/node_modules/is-lite/dist/index.mjs","../node_modules/tree-changes/dist/index.mjs","../node_modules/scroll/index.js","../node_modules/scrollparent/scrollparent.js","../node_modules/deepmerge/dist/cjs.js","../node_modules/prop-types/factoryWithThrowingShims.js","../node_modules/prop-types/index.js","../node_modules/prop-types/lib/ReactPropTypesSecret.js","../node_modules/popper.js/dist/esm/popper.js","../node_modules/is-lite/esm/index.js","../node_modules/react-floater/node_modules/@gilbarbara/deep-equal/esm/helpers.js","../node_modules/react-floater/node_modules/@gilbarbara/deep-equal/esm/index.js","../node_modules/react-floater/node_modules/tree-changes/esm/helpers.js","../node_modules/react-floater/es/index.js","../node_modules/react-floater/node_modules/tree-changes/esm/index.js","../node_modules/react-innertext/index.js","../node_modules/react-joyride/dist/index.mjs","../src/apps/path-finder/components/app-tour/tour-data.tsx","../src/apps/path-finder/components/app-tour/app-tour.tsx","../src/apps/path-finder/components/cell-info/cell-info.tsx","../src/apps/path-finder/components/navbar/navbar.tsx","../src/apps/path-finder/helpers/maze.helper.ts","../src/apps/path-finder/algorithms/maze-generator/prims.ts","../src/apps/path-finder/algorithms/maze-generator/recursive-division.ts","../src/apps/path-finder/algorithms/maze-generator/recursive-backtracking.ts","../src/apps/path-finder/algorithms/maze-generator/binary.ts","../src/apps/path-finder/algorithms/maze-generator/kruskal.ts","../src/apps/path-finder/algorithms/maze-generator/wilson.ts","../src/apps/path-finder/algorithms/path-finder/a-star.ts","../src/apps/path-finder/algorithms/path-finder/greedy.ts","../src/apps/path-finder/algorithms/maze-generator/labyrinth.ts","../src/apps/path-finder/algorithms/maze-generator/ellers.ts","../src/apps/path-finder/algorithms/index.ts","../src/apps/path-finder/algorithms/path-finder/bfs.ts","../src/apps/path-finder/algorithms/path-finder/dfs.ts","../src/apps/path-finder/algorithms/maze-generator/side-winder.ts","../src/apps/path-finder/algorithms/maze-generator/random.ts","../src/apps/path-finder/components/modal-icon/modal-content.tsx","../src/apps/path-finder/components/modal-icon/modals.tsx","../src/apps/path-finder/store/maze.thunk.ts","../src/apps/path-finder/components/controller/maze-controls.tsx","../node_modules/react-use/esm/misc/util.js","../node_modules/react-use/esm/useDebounce.js","../node_modules/react-use/esm/useTimeoutFn.js","../node_modules/react-use/esm/useEffectOnce.js","../node_modules/react-use/esm/useUnmount.js","../node_modules/react-use/esm/useWindowSize.js","../node_modules/react-use/esm/useRafState.js","../src/apps/path-finder/store/path.thunk.ts","../src/apps/path-finder/algorithms/path-finder/path-tracer.ts","../src/apps/path-finder/store/search.thunk.ts","../src/apps/path-finder/components/controller/path-controls.tsx","../src/apps/path-finder/components/controller/path-info.tsx","../src/apps/path-finder/hooks/use-timer.hook.ts","../src/apps/path-finder/components/controller/controller.tsx","../src/apps/path-finder/helpers/action.helper.ts","../src/apps/path-finder/hooks/use-mouse.hook.ts","../src/apps/path-finder/hooks/use-mouse-actions.hook.ts","../src/apps/path-finder/components/grid/grid.tsx","../src/apps/path-finder/hooks/use-touch.hook.ts","../src/apps/path-finder/layouts/main.layout.tsx","../src/apps/path-finder/pages/home.page.tsx","../src/apps/path-finder/routes.tsx","../src/apps/sorting-visualizer/helpers/array-helpers.ts","../src/apps/sorting-visualizer/components/controller/number-generator.tsx","../src/apps/sorting-visualizer/components/controller/array-input.tsx","../src/apps/sorting-visualizer/components/controller/execution.tsx","../node_modules/react-switch/dist/index.prod.mjs","../src/apps/sorting-visualizer/components/controller/type-switch.tsx","../src/apps/sorting-visualizer/components/controller/controller.tsx","../src/apps/sorting-visualizer/components/navbar/navbar.tsx","../src/apps/sorting-visualizer/layouts/main.layout.tsx","../src/apps/sorting-visualizer/components/visualizer/no-input.tsx","../src/apps/sorting-visualizer/components/visualizer/header.tsx","../src/apps/sorting-visualizer/components/bar/bar-ui.tsx","../src/apps/sorting-visualizer/components/cell/cell.tsx","../src/apps/sorting-visualizer/helpers/key-frames-helpers.ts","../src/apps/sorting-visualizer/components/cell/moving-cell.tsx","../src/apps/sorting-visualizer/components/cell/swapping-cell.tsx","../src/apps/sorting-visualizer/components/cell/cell-ui.tsx","../src/apps/sorting-visualizer/components/visualizer/visualizer-display.tsx","../src/apps/sorting-visualizer/hooks/use-algo.hook.tsx","../src/apps/sorting-visualizer/components/visualizer/visualizer.tsx","../src/apps/sorting-visualizer/hooks/use-completion.hook.ts","../src/apps/sorting-visualizer/layouts/single-algorithm.layout.tsx","../src/apps/sorting-visualizer/pages/algorithm.page.tsx","../src/apps/sorting-visualizer/components/controller/algo-selection.tsx","../src/apps/sorting-visualizer/layouts/all-algorithm.layout.tsx","../src/apps/sorting-visualizer/pages/all-algorithm.page.tsx","../src/apps/sorting-visualizer/routes.tsx","../src/host/routes.tsx","../src/host/app.tsx","../node_modules/redux-persist/es/integration/react.js","../node_modules/react-dom/client.js","../src/main.tsx"],"sourcesContent":["/**\n * @license React\n * react.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';var l=Symbol.for(\"react.element\"),n=Symbol.for(\"react.portal\"),p=Symbol.for(\"react.fragment\"),q=Symbol.for(\"react.strict_mode\"),r=Symbol.for(\"react.profiler\"),t=Symbol.for(\"react.provider\"),u=Symbol.for(\"react.context\"),v=Symbol.for(\"react.forward_ref\"),w=Symbol.for(\"react.suspense\"),x=Symbol.for(\"react.memo\"),y=Symbol.for(\"react.lazy\"),z=Symbol.iterator;function A(a){if(null===a||\"object\"!==typeof a)return null;a=z&&a[z]||a[\"@@iterator\"];return\"function\"===typeof a?a:null}\nvar B={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}E.prototype.isReactComponent={};\nE.prototype.setState=function(a,b){if(\"object\"!==typeof a&&\"function\"!==typeof a&&null!=a)throw Error(\"setState(...): takes an object of state variables to update or a function which returns an object of state variables.\");this.updater.enqueueSetState(this,a,b,\"setState\")};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,\"forceUpdate\")};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B}var H=G.prototype=new F;\nH.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};\nfunction M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=\"\"+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\nimport { FLUSH, PAUSE, PERSIST, PURGE, REHYDRATE, DEFAULT_VERSION } from './constants';\nimport autoMergeLevel1 from './stateReconciler/autoMergeLevel1';\nimport createPersistoid from './createPersistoid';\nimport defaultGetStoredState from './getStoredState';\nimport purgeStoredState from './purgeStoredState';\nvar DEFAULT_TIMEOUT = 5000;\n/*\n @TODO add validation / handling for:\n - persisting a reducer which has nested _persist\n - handling actions that fire before reydrate is called\n*/\n\nexport default function persistReducer(config, baseReducer) {\n if (process.env.NODE_ENV !== 'production') {\n if (!config) throw new Error('config is required for persistReducer');\n if (!config.key) throw new Error('key is required in persistor config');\n if (!config.storage) throw new Error(\"redux-persist: config.storage is required. Try using one of the provided storage engines `import storage from 'redux-persist/lib/storage'`\");\n }\n\n var version = config.version !== undefined ? config.version : DEFAULT_VERSION;\n var debug = config.debug || false;\n var stateReconciler = config.stateReconciler === undefined ? autoMergeLevel1 : config.stateReconciler;\n var getStoredState = config.getStoredState || defaultGetStoredState;\n var timeout = config.timeout !== undefined ? config.timeout : DEFAULT_TIMEOUT;\n var _persistoid = null;\n var _purge = false;\n var _paused = true;\n\n var conditionalUpdate = function conditionalUpdate(state) {\n // update the persistoid only if we are rehydrated and not paused\n state._persist.rehydrated && _persistoid && !_paused && _persistoid.update(state);\n return state;\n };\n\n return function (state, action) {\n var _ref = state || {},\n _persist = _ref._persist,\n rest = _objectWithoutProperties(_ref, [\"_persist\"]); // $FlowIgnore need to update State type\n\n\n var restState = rest;\n\n if (action.type === PERSIST) {\n var _sealed = false;\n\n var _rehydrate = function _rehydrate(payload, err) {\n // dev warning if we are already sealed\n if (process.env.NODE_ENV !== 'production' && _sealed) console.error(\"redux-persist: rehydrate for \\\"\".concat(config.key, \"\\\" called after timeout.\"), payload, err); // only rehydrate if we are not already sealed\n\n if (!_sealed) {\n action.rehydrate(config.key, payload, err);\n _sealed = true;\n }\n };\n\n timeout && setTimeout(function () {\n !_sealed && _rehydrate(undefined, new Error(\"redux-persist: persist timed out for persist key \\\"\".concat(config.key, \"\\\"\")));\n }, timeout); // @NOTE PERSIST resumes if paused.\n\n _paused = false; // @NOTE only ever create persistoid once, ensure we call it at least once, even if _persist has already been set\n\n if (!_persistoid) _persistoid = createPersistoid(config); // @NOTE PERSIST can be called multiple times, noop after the first\n\n if (_persist) {\n // We still need to call the base reducer because there might be nested\n // uses of persistReducer which need to be aware of the PERSIST action\n return _objectSpread({}, baseReducer(restState, action), {\n _persist: _persist\n });\n }\n\n if (typeof action.rehydrate !== 'function' || typeof action.register !== 'function') throw new Error('redux-persist: either rehydrate or register is not a function on the PERSIST action. This can happen if the action is being replayed. This is an unexplored use case, please open an issue and we will figure out a resolution.');\n action.register(config.key);\n getStoredState(config).then(function (restoredState) {\n var migrate = config.migrate || function (s, v) {\n return Promise.resolve(s);\n };\n\n migrate(restoredState, version).then(function (migratedState) {\n _rehydrate(migratedState);\n }, function (migrateErr) {\n if (process.env.NODE_ENV !== 'production' && migrateErr) console.error('redux-persist: migration error', migrateErr);\n\n _rehydrate(undefined, migrateErr);\n });\n }, function (err) {\n _rehydrate(undefined, err);\n });\n return _objectSpread({}, baseReducer(restState, action), {\n _persist: {\n version: version,\n rehydrated: false\n }\n });\n } else if (action.type === PURGE) {\n _purge = true;\n action.result(purgeStoredState(config));\n return _objectSpread({}, baseReducer(restState, action), {\n _persist: _persist\n });\n } else if (action.type === FLUSH) {\n action.result(_persistoid && _persistoid.flush());\n return _objectSpread({}, baseReducer(restState, action), {\n _persist: _persist\n });\n } else if (action.type === PAUSE) {\n _paused = true;\n } else if (action.type === REHYDRATE) {\n // noop on restState if purging\n if (_purge) return _objectSpread({}, restState, {\n _persist: _objectSpread({}, _persist, {\n rehydrated: true\n }) // @NOTE if key does not match, will continue to default else below\n\n });\n\n if (action.key === config.key) {\n var reducedState = baseReducer(restState, action);\n var inboundState = action.payload; // only reconcile state if stateReconciler and inboundState are both defined\n\n var reconciledRest = stateReconciler !== false && inboundState !== undefined ? stateReconciler(inboundState, state, reducedState, config) : reducedState;\n\n var _newState = _objectSpread({}, reconciledRest, {\n _persist: _objectSpread({}, _persist, {\n rehydrated: true\n })\n });\n\n return conditionalUpdate(_newState);\n }\n } // if we have not already handled PERSIST, straight passthrough\n\n\n if (!_persist) return baseReducer(state, action); // run base reducer:\n // is state modified ? return original : return updated\n\n var newState = baseReducer(restState, action);\n if (newState === restState) return state;\n return conditionalUpdate(_objectSpread({}, newState, {\n _persist: _persist\n }));\n };\n}","// src/utils/formatProdErrorMessage.ts\nfunction formatProdErrorMessage(code) {\n return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;\n}\n\n// src/utils/symbol-observable.ts\nvar $$observable = /* @__PURE__ */ (() => typeof Symbol === \"function\" && Symbol.observable || \"@@observable\")();\nvar symbol_observable_default = $$observable;\n\n// src/utils/actionTypes.ts\nvar randomString = () => Math.random().toString(36).substring(7).split(\"\").join(\".\");\nvar ActionTypes = {\n INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,\n REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,\n PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`\n};\nvar actionTypes_default = ActionTypes;\n\n// src/utils/isPlainObject.ts\nfunction isPlainObject(obj) {\n if (typeof obj !== \"object\" || obj === null)\n return false;\n let proto = obj;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;\n}\n\n// src/utils/kindOf.ts\nfunction miniKindOf(val) {\n if (val === void 0)\n return \"undefined\";\n if (val === null)\n return \"null\";\n const type = typeof val;\n switch (type) {\n case \"boolean\":\n case \"string\":\n case \"number\":\n case \"symbol\":\n case \"function\": {\n return type;\n }\n }\n if (Array.isArray(val))\n return \"array\";\n if (isDate(val))\n return \"date\";\n if (isError(val))\n return \"error\";\n const constructorName = ctorName(val);\n switch (constructorName) {\n case \"Symbol\":\n case \"Promise\":\n case \"WeakMap\":\n case \"WeakSet\":\n case \"Map\":\n case \"Set\":\n return constructorName;\n }\n return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\\s/g, \"\");\n}\nfunction ctorName(val) {\n return typeof val.constructor === \"function\" ? val.constructor.name : null;\n}\nfunction isError(val) {\n return val instanceof Error || typeof val.message === \"string\" && val.constructor && typeof val.constructor.stackTraceLimit === \"number\";\n}\nfunction isDate(val) {\n if (val instanceof Date)\n return true;\n return typeof val.toDateString === \"function\" && typeof val.getDate === \"function\" && typeof val.setDate === \"function\";\n}\nfunction kindOf(val) {\n let typeOfVal = typeof val;\n if (process.env.NODE_ENV !== \"production\") {\n typeOfVal = miniKindOf(val);\n }\n return typeOfVal;\n}\n\n// src/createStore.ts\nfunction createStore(reducer, preloadedState, enhancer) {\n if (typeof reducer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : `Expected the root reducer to be a function. Instead, received: '${kindOf(reducer)}'`);\n }\n if (typeof preloadedState === \"function\" && typeof enhancer === \"function\" || typeof enhancer === \"function\" && typeof arguments[3] === \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : \"It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.\");\n }\n if (typeof preloadedState === \"function\" && typeof enhancer === \"undefined\") {\n enhancer = preloadedState;\n preloadedState = void 0;\n }\n if (typeof enhancer !== \"undefined\") {\n if (typeof enhancer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : `Expected the enhancer to be a function. Instead, received: '${kindOf(enhancer)}'`);\n }\n return enhancer(createStore)(reducer, preloadedState);\n }\n let currentReducer = reducer;\n let currentState = preloadedState;\n let currentListeners = /* @__PURE__ */ new Map();\n let nextListeners = currentListeners;\n let listenerIdCounter = 0;\n let isDispatching = false;\n function ensureCanMutateNextListeners() {\n if (nextListeners === currentListeners) {\n nextListeners = /* @__PURE__ */ new Map();\n currentListeners.forEach((listener, key) => {\n nextListeners.set(key, listener);\n });\n }\n }\n function getState() {\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : \"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.\");\n }\n return currentState;\n }\n function subscribe(listener) {\n if (typeof listener !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : `Expected the listener to be a function. Instead, received: '${kindOf(listener)}'`);\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : \"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.\");\n }\n let isSubscribed = true;\n ensureCanMutateNextListeners();\n const listenerId = listenerIdCounter++;\n nextListeners.set(listenerId, listener);\n return function unsubscribe() {\n if (!isSubscribed) {\n return;\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : \"You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.\");\n }\n isSubscribed = false;\n ensureCanMutateNextListeners();\n nextListeners.delete(listenerId);\n currentListeners = null;\n };\n }\n function dispatch(action) {\n if (!isPlainObject(action)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : `Actions must be plain objects. Instead, the actual type was: '${kindOf(action)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);\n }\n if (typeof action.type === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : 'Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.');\n }\n if (typeof action.type !== \"string\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(17) : `Action \"type\" property must be a string. Instead, the actual type was: '${kindOf(action.type)}'. Value was: '${action.type}' (stringified)`);\n }\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : \"Reducers may not dispatch actions.\");\n }\n try {\n isDispatching = true;\n currentState = currentReducer(currentState, action);\n } finally {\n isDispatching = false;\n }\n const listeners = currentListeners = nextListeners;\n listeners.forEach((listener) => {\n listener();\n });\n return action;\n }\n function replaceReducer(nextReducer) {\n if (typeof nextReducer !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : `Expected the nextReducer to be a function. Instead, received: '${kindOf(nextReducer)}`);\n }\n currentReducer = nextReducer;\n dispatch({\n type: actionTypes_default.REPLACE\n });\n }\n function observable() {\n const outerSubscribe = subscribe;\n return {\n /**\n * The minimal observable subscription method.\n * @param observer Any object that can be used as an observer.\n * The observer object should have a `next` method.\n * @returns An object with an `unsubscribe` method that can\n * be used to unsubscribe the observable from the store, and prevent further\n * emission of values from the observable.\n */\n subscribe(observer) {\n if (typeof observer !== \"object\" || observer === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : `Expected the observer to be an object. Instead, received: '${kindOf(observer)}'`);\n }\n function observeState() {\n const observerAsObserver = observer;\n if (observerAsObserver.next) {\n observerAsObserver.next(getState());\n }\n }\n observeState();\n const unsubscribe = outerSubscribe(observeState);\n return {\n unsubscribe\n };\n },\n [symbol_observable_default]() {\n return this;\n }\n };\n }\n dispatch({\n type: actionTypes_default.INIT\n });\n const store = {\n dispatch,\n subscribe,\n getState,\n replaceReducer,\n [symbol_observable_default]: observable\n };\n return store;\n}\nfunction legacy_createStore(reducer, preloadedState, enhancer) {\n return createStore(reducer, preloadedState, enhancer);\n}\n\n// src/utils/warning.ts\nfunction warning(message) {\n if (typeof console !== \"undefined\" && typeof console.error === \"function\") {\n console.error(message);\n }\n try {\n throw new Error(message);\n } catch (e) {\n }\n}\n\n// src/combineReducers.ts\nfunction getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {\n const reducerKeys = Object.keys(reducers);\n const argumentName = action && action.type === actionTypes_default.INIT ? \"preloadedState argument passed to createStore\" : \"previous state received by the reducer\";\n if (reducerKeys.length === 0) {\n return \"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.\";\n }\n if (!isPlainObject(inputState)) {\n return `The ${argumentName} has unexpected type of \"${kindOf(inputState)}\". Expected argument to be an object with the following keys: \"${reducerKeys.join('\", \"')}\"`;\n }\n const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);\n unexpectedKeys.forEach((key) => {\n unexpectedKeyCache[key] = true;\n });\n if (action && action.type === actionTypes_default.REPLACE)\n return;\n if (unexpectedKeys.length > 0) {\n return `Unexpected ${unexpectedKeys.length > 1 ? \"keys\" : \"key\"} \"${unexpectedKeys.join('\", \"')}\" found in ${argumentName}. Expected to find one of the known reducer keys instead: \"${reducerKeys.join('\", \"')}\". Unexpected keys will be ignored.`;\n }\n}\nfunction assertReducerShape(reducers) {\n Object.keys(reducers).forEach((key) => {\n const reducer = reducers[key];\n const initialState = reducer(void 0, {\n type: actionTypes_default.INIT\n });\n if (typeof initialState === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : `The slice reducer for key \"${key}\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);\n }\n if (typeof reducer(void 0, {\n type: actionTypes_default.PROBE_UNKNOWN_ACTION()\n }) === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : `The slice reducer for key \"${key}\" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);\n }\n });\n}\nfunction combineReducers(reducers) {\n const reducerKeys = Object.keys(reducers);\n const finalReducers = {};\n for (let i = 0; i < reducerKeys.length; i++) {\n const key = reducerKeys[i];\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof reducers[key] === \"undefined\") {\n warning(`No reducer provided for key \"${key}\"`);\n }\n }\n if (typeof reducers[key] === \"function\") {\n finalReducers[key] = reducers[key];\n }\n }\n const finalReducerKeys = Object.keys(finalReducers);\n let unexpectedKeyCache;\n if (process.env.NODE_ENV !== \"production\") {\n unexpectedKeyCache = {};\n }\n let shapeAssertionError;\n try {\n assertReducerShape(finalReducers);\n } catch (e) {\n shapeAssertionError = e;\n }\n return function combination(state = {}, action) {\n if (shapeAssertionError) {\n throw shapeAssertionError;\n }\n if (process.env.NODE_ENV !== \"production\") {\n const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);\n if (warningMessage) {\n warning(warningMessage);\n }\n }\n let hasChanged = false;\n const nextState = {};\n for (let i = 0; i < finalReducerKeys.length; i++) {\n const key = finalReducerKeys[i];\n const reducer = finalReducers[key];\n const previousStateForKey = state[key];\n const nextStateForKey = reducer(previousStateForKey, action);\n if (typeof nextStateForKey === \"undefined\") {\n const actionType = action && action.type;\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `\"${String(actionType)}\"` : \"(unknown type)\"}, the slice reducer for key \"${key}\" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);\n }\n nextState[key] = nextStateForKey;\n hasChanged = hasChanged || nextStateForKey !== previousStateForKey;\n }\n hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;\n return hasChanged ? nextState : state;\n };\n}\n\n// src/bindActionCreators.ts\nfunction bindActionCreator(actionCreator, dispatch) {\n return function(...args) {\n return dispatch(actionCreator.apply(this, args));\n };\n}\nfunction bindActionCreators(actionCreators, dispatch) {\n if (typeof actionCreators === \"function\") {\n return bindActionCreator(actionCreators, dispatch);\n }\n if (typeof actionCreators !== \"object\" || actionCreators === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : `bindActionCreators expected an object or a function, but instead received: '${kindOf(actionCreators)}'. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?`);\n }\n const boundActionCreators = {};\n for (const key in actionCreators) {\n const actionCreator = actionCreators[key];\n if (typeof actionCreator === \"function\") {\n boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);\n }\n }\n return boundActionCreators;\n}\n\n// src/compose.ts\nfunction compose(...funcs) {\n if (funcs.length === 0) {\n return (arg) => arg;\n }\n if (funcs.length === 1) {\n return funcs[0];\n }\n return funcs.reduce((a, b) => (...args) => a(b(...args)));\n}\n\n// src/applyMiddleware.ts\nfunction applyMiddleware(...middlewares) {\n return (createStore2) => (reducer, preloadedState) => {\n const store = createStore2(reducer, preloadedState);\n let dispatch = () => {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : \"Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.\");\n };\n const middlewareAPI = {\n getState: store.getState,\n dispatch: (action, ...args) => dispatch(action, ...args)\n };\n const chain = middlewares.map((middleware) => middleware(middlewareAPI));\n dispatch = compose(...chain)(store.dispatch);\n return {\n ...store,\n dispatch\n };\n };\n}\n\n// src/utils/isAction.ts\nfunction isAction(action) {\n return isPlainObject(action) && \"type\" in action && typeof action.type === \"string\";\n}\nexport {\n actionTypes_default as __DO_NOT_USE__ActionTypes,\n applyMiddleware,\n bindActionCreators,\n combineReducers,\n compose,\n createStore,\n isAction,\n isPlainObject,\n legacy_createStore\n};\n//# sourceMappingURL=redux.mjs.map","function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nimport { createStore } from 'redux';\nimport { FLUSH, PAUSE, PERSIST, PURGE, REGISTER, REHYDRATE } from './constants';\nvar initialState = {\n registry: [],\n bootstrapped: false\n};\n\nvar persistorReducer = function persistorReducer() {\n var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;\n var action = arguments.length > 1 ? arguments[1] : undefined;\n\n switch (action.type) {\n case REGISTER:\n return _objectSpread({}, state, {\n registry: [].concat(_toConsumableArray(state.registry), [action.key])\n });\n\n case REHYDRATE:\n var firstIndex = state.registry.indexOf(action.key);\n\n var registry = _toConsumableArray(state.registry);\n\n registry.splice(firstIndex, 1);\n return _objectSpread({}, state, {\n registry: registry,\n bootstrapped: registry.length === 0\n });\n\n default:\n return state;\n }\n};\n\nexport default function persistStore(store, options, cb) {\n // help catch incorrect usage of passing PersistConfig in as PersistorOptions\n if (process.env.NODE_ENV !== 'production') {\n var optionsToTest = options || {};\n var bannedKeys = ['blacklist', 'whitelist', 'transforms', 'storage', 'keyPrefix', 'migrate'];\n bannedKeys.forEach(function (k) {\n if (!!optionsToTest[k]) console.error(\"redux-persist: invalid option passed to persistStore: \\\"\".concat(k, \"\\\". You may be incorrectly passing persistConfig into persistStore, whereas it should be passed into persistReducer.\"));\n });\n }\n\n var boostrappedCb = cb || false;\n\n var _pStore = createStore(persistorReducer, initialState, options && options.enhancer ? options.enhancer : undefined);\n\n var register = function register(key) {\n _pStore.dispatch({\n type: REGISTER,\n key: key\n });\n };\n\n var rehydrate = function rehydrate(key, payload, err) {\n var rehydrateAction = {\n type: REHYDRATE,\n payload: payload,\n err: err,\n key: key // dispatch to `store` to rehydrate and `persistor` to track result\n\n };\n store.dispatch(rehydrateAction);\n\n _pStore.dispatch(rehydrateAction);\n\n if (boostrappedCb && persistor.getState().bootstrapped) {\n boostrappedCb();\n boostrappedCb = false;\n }\n };\n\n var persistor = _objectSpread({}, _pStore, {\n purge: function purge() {\n var results = [];\n store.dispatch({\n type: PURGE,\n result: function result(purgeResult) {\n results.push(purgeResult);\n }\n });\n return Promise.all(results);\n },\n flush: function flush() {\n var results = [];\n store.dispatch({\n type: FLUSH,\n result: function result(flushResult) {\n results.push(flushResult);\n }\n });\n return Promise.all(results);\n },\n pause: function pause() {\n store.dispatch({\n type: PAUSE\n });\n },\n persist: function persist() {\n store.dispatch({\n type: PERSIST,\n register: register,\n rehydrate: rehydrate\n });\n }\n });\n\n if (!(options && options.manualPersist)) {\n persistor.persist();\n }\n\n return persistor;\n}","// src/utils/env.ts\nvar NOTHING = Symbol.for(\"immer-nothing\");\nvar DRAFTABLE = Symbol.for(\"immer-draftable\");\nvar DRAFT_STATE = Symbol.for(\"immer-state\");\n\n// src/utils/errors.ts\nvar errors = process.env.NODE_ENV !== \"production\" ? [\n // All error codes, starting by 0:\n function(plugin) {\n return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`;\n },\n function(thing) {\n return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;\n },\n \"This object has been frozen and should not be mutated\",\n function(data) {\n return \"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" + data;\n },\n \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n \"Immer forbids circular references\",\n \"The first or second argument to `produce` must be a function\",\n \"The third argument to `produce` must be a function or undefined\",\n \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n function(thing) {\n return `'current' expects a draft, got: ${thing}`;\n },\n \"Object.defineProperty() cannot be used on an Immer draft\",\n \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n \"Immer only supports deleting array indices\",\n \"Immer only supports setting array indices and the 'length' property\",\n function(thing) {\n return `'original' expects a draft, got: ${thing}`;\n }\n // Note: if more errors are added, the errorOffset in Patches.ts should be increased\n // See Patches.ts for additional errors\n] : [];\nfunction die(error, ...args) {\n if (process.env.NODE_ENV !== \"production\") {\n const e = errors[error];\n const msg = typeof e === \"function\" ? e.apply(null, args) : e;\n throw new Error(`[Immer] ${msg}`);\n }\n throw new Error(\n `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`\n );\n}\n\n// src/utils/common.ts\nvar getPrototypeOf = Object.getPrototypeOf;\nfunction isDraft(value) {\n return !!value && !!value[DRAFT_STATE];\n}\nfunction isDraftable(value) {\n if (!value)\n return false;\n return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);\n}\nvar objectCtorString = Object.prototype.constructor.toString();\nfunction isPlainObject(value) {\n if (!value || typeof value !== \"object\")\n return false;\n const proto = getPrototypeOf(value);\n if (proto === null) {\n return true;\n }\n const Ctor = Object.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n if (Ctor === Object)\n return true;\n return typeof Ctor == \"function\" && Function.toString.call(Ctor) === objectCtorString;\n}\nfunction original(value) {\n if (!isDraft(value))\n die(15, value);\n return value[DRAFT_STATE].base_;\n}\nfunction each(obj, iter) {\n if (getArchtype(obj) === 0 /* Object */) {\n Reflect.ownKeys(obj).forEach((key) => {\n iter(key, obj[key], obj);\n });\n } else {\n obj.forEach((entry, index) => iter(index, entry, obj));\n }\n}\nfunction getArchtype(thing) {\n const state = thing[DRAFT_STATE];\n return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;\n}\nfunction has(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);\n}\nfunction get(thing, prop) {\n return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];\n}\nfunction set(thing, propOrOldValue, value) {\n const t = getArchtype(thing);\n if (t === 2 /* Map */)\n thing.set(propOrOldValue, value);\n else if (t === 3 /* Set */) {\n thing.add(value);\n } else\n thing[propOrOldValue] = value;\n}\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || 1 / x === 1 / y;\n } else {\n return x !== x && y !== y;\n }\n}\nfunction isMap(target) {\n return target instanceof Map;\n}\nfunction isSet(target) {\n return target instanceof Set;\n}\nfunction latest(state) {\n return state.copy_ || state.base_;\n}\nfunction shallowCopy(base, strict) {\n if (isMap(base)) {\n return new Map(base);\n }\n if (isSet(base)) {\n return new Set(base);\n }\n if (Array.isArray(base))\n return Array.prototype.slice.call(base);\n const isPlain = isPlainObject(base);\n if (strict === true || strict === \"class_only\" && !isPlain) {\n const descriptors = Object.getOwnPropertyDescriptors(base);\n delete descriptors[DRAFT_STATE];\n let keys = Reflect.ownKeys(descriptors);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const desc = descriptors[key];\n if (desc.writable === false) {\n desc.writable = true;\n desc.configurable = true;\n }\n if (desc.get || desc.set)\n descriptors[key] = {\n configurable: true,\n writable: true,\n // could live with !!desc.set as well here...\n enumerable: desc.enumerable,\n value: base[key]\n };\n }\n return Object.create(getPrototypeOf(base), descriptors);\n } else {\n const proto = getPrototypeOf(base);\n if (proto !== null && isPlain) {\n return { ...base };\n }\n const obj = Object.create(proto);\n return Object.assign(obj, base);\n }\n}\nfunction freeze(obj, deep = false) {\n if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))\n return obj;\n if (getArchtype(obj) > 1) {\n obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;\n }\n Object.freeze(obj);\n if (deep)\n Object.entries(obj).forEach(([key, value]) => freeze(value, true));\n return obj;\n}\nfunction dontMutateFrozenCollections() {\n die(2);\n}\nfunction isFrozen(obj) {\n return Object.isFrozen(obj);\n}\n\n// src/utils/plugins.ts\nvar plugins = {};\nfunction getPlugin(pluginKey) {\n const plugin = plugins[pluginKey];\n if (!plugin) {\n die(0, pluginKey);\n }\n return plugin;\n}\nfunction loadPlugin(pluginKey, implementation) {\n if (!plugins[pluginKey])\n plugins[pluginKey] = implementation;\n}\n\n// src/core/scope.ts\nvar currentScope;\nfunction getCurrentScope() {\n return currentScope;\n}\nfunction createScope(parent_, immer_) {\n return {\n drafts_: [],\n parent_,\n immer_,\n // Whenever the modified draft contains a draft from another scope, we\n // need to prevent auto-freezing so the unowned draft can be finalized.\n canAutoFreeze_: true,\n unfinalizedDrafts_: 0\n };\n}\nfunction usePatchesInScope(scope, patchListener) {\n if (patchListener) {\n getPlugin(\"Patches\");\n scope.patches_ = [];\n scope.inversePatches_ = [];\n scope.patchListener_ = patchListener;\n }\n}\nfunction revokeScope(scope) {\n leaveScope(scope);\n scope.drafts_.forEach(revokeDraft);\n scope.drafts_ = null;\n}\nfunction leaveScope(scope) {\n if (scope === currentScope) {\n currentScope = scope.parent_;\n }\n}\nfunction enterScope(immer2) {\n return currentScope = createScope(currentScope, immer2);\n}\nfunction revokeDraft(draft) {\n const state = draft[DRAFT_STATE];\n if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)\n state.revoke_();\n else\n state.revoked_ = true;\n}\n\n// src/core/finalize.ts\nfunction processResult(result, scope) {\n scope.unfinalizedDrafts_ = scope.drafts_.length;\n const baseDraft = scope.drafts_[0];\n const isReplaced = result !== void 0 && result !== baseDraft;\n if (isReplaced) {\n if (baseDraft[DRAFT_STATE].modified_) {\n revokeScope(scope);\n die(4);\n }\n if (isDraftable(result)) {\n result = finalize(scope, result);\n if (!scope.parent_)\n maybeFreeze(scope, result);\n }\n if (scope.patches_) {\n getPlugin(\"Patches\").generateReplacementPatches_(\n baseDraft[DRAFT_STATE].base_,\n result,\n scope.patches_,\n scope.inversePatches_\n );\n }\n } else {\n result = finalize(scope, baseDraft, []);\n }\n revokeScope(scope);\n if (scope.patches_) {\n scope.patchListener_(scope.patches_, scope.inversePatches_);\n }\n return result !== NOTHING ? result : void 0;\n}\nfunction finalize(rootScope, value, path) {\n if (isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n if (!state) {\n each(\n value,\n (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)\n );\n return value;\n }\n if (state.scope_ !== rootScope)\n return value;\n if (!state.modified_) {\n maybeFreeze(rootScope, state.base_, true);\n return state.base_;\n }\n if (!state.finalized_) {\n state.finalized_ = true;\n state.scope_.unfinalizedDrafts_--;\n const result = state.copy_;\n let resultEach = result;\n let isSet2 = false;\n if (state.type_ === 3 /* Set */) {\n resultEach = new Set(result);\n result.clear();\n isSet2 = true;\n }\n each(\n resultEach,\n (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)\n );\n maybeFreeze(rootScope, result, false);\n if (path && rootScope.patches_) {\n getPlugin(\"Patches\").generatePatches_(\n state,\n path,\n rootScope.patches_,\n rootScope.inversePatches_\n );\n }\n }\n return state.copy_;\n}\nfunction finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {\n if (process.env.NODE_ENV !== \"production\" && childValue === targetObject)\n die(5);\n if (isDraft(childValue)) {\n const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.\n !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;\n const res = finalize(rootScope, childValue, path);\n set(targetObject, prop, res);\n if (isDraft(res)) {\n rootScope.canAutoFreeze_ = false;\n } else\n return;\n } else if (targetIsSet) {\n targetObject.add(childValue);\n }\n if (isDraftable(childValue) && !isFrozen(childValue)) {\n if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n return;\n }\n finalize(rootScope, childValue);\n if ((!parentState || !parentState.scope_.parent_) && typeof prop !== \"symbol\" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))\n maybeFreeze(rootScope, childValue);\n }\n}\nfunction maybeFreeze(scope, value, deep = false) {\n if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n freeze(value, deep);\n }\n}\n\n// src/core/proxy.ts\nfunction createProxyProxy(base, parent) {\n const isArray = Array.isArray(base);\n const state = {\n type_: isArray ? 1 /* Array */ : 0 /* Object */,\n // Track which produce call this is associated with.\n scope_: parent ? parent.scope_ : getCurrentScope(),\n // True for both shallow and deep changes.\n modified_: false,\n // Used during finalization.\n finalized_: false,\n // Track which properties have been assigned (true) or deleted (false).\n assigned_: {},\n // The parent draft state.\n parent_: parent,\n // The base state.\n base_: base,\n // The base proxy.\n draft_: null,\n // set below\n // The base copy with any updated values.\n copy_: null,\n // Called by the `produce` function.\n revoke_: null,\n isManual_: false\n };\n let target = state;\n let traps = objectTraps;\n if (isArray) {\n target = [state];\n traps = arrayTraps;\n }\n const { revoke, proxy } = Proxy.revocable(target, traps);\n state.draft_ = proxy;\n state.revoke_ = revoke;\n return proxy;\n}\nvar objectTraps = {\n get(state, prop) {\n if (prop === DRAFT_STATE)\n return state;\n const source = latest(state);\n if (!has(source, prop)) {\n return readPropFromProto(state, source, prop);\n }\n const value = source[prop];\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value === peek(state.base_, prop)) {\n prepareCopy(state);\n return state.copy_[prop] = createProxy(value, state);\n }\n return value;\n },\n has(state, prop) {\n return prop in latest(state);\n },\n ownKeys(state) {\n return Reflect.ownKeys(latest(state));\n },\n set(state, prop, value) {\n const desc = getDescriptorFromProto(latest(state), prop);\n if (desc?.set) {\n desc.set.call(state.draft_, value);\n return true;\n }\n if (!state.modified_) {\n const current2 = peek(latest(state), prop);\n const currentState = current2?.[DRAFT_STATE];\n if (currentState && currentState.base_ === value) {\n state.copy_[prop] = value;\n state.assigned_[prop] = false;\n return true;\n }\n if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))\n return true;\n prepareCopy(state);\n markChanged(state);\n }\n if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'\n (value !== void 0 || prop in state.copy_) || // special case: NaN\n Number.isNaN(value) && Number.isNaN(state.copy_[prop]))\n return true;\n state.copy_[prop] = value;\n state.assigned_[prop] = true;\n return true;\n },\n deleteProperty(state, prop) {\n if (peek(state.base_, prop) !== void 0 || prop in state.base_) {\n state.assigned_[prop] = false;\n prepareCopy(state);\n markChanged(state);\n } else {\n delete state.assigned_[prop];\n }\n if (state.copy_) {\n delete state.copy_[prop];\n }\n return true;\n },\n // Note: We never coerce `desc.value` into an Immer draft, because we can't make\n // the same guarantee in ES5 mode.\n getOwnPropertyDescriptor(state, prop) {\n const owner = latest(state);\n const desc = Reflect.getOwnPropertyDescriptor(owner, prop);\n if (!desc)\n return desc;\n return {\n writable: true,\n configurable: state.type_ !== 1 /* Array */ || prop !== \"length\",\n enumerable: desc.enumerable,\n value: owner[prop]\n };\n },\n defineProperty() {\n die(11);\n },\n getPrototypeOf(state) {\n return getPrototypeOf(state.base_);\n },\n setPrototypeOf() {\n die(12);\n }\n};\nvar arrayTraps = {};\neach(objectTraps, (key, fn) => {\n arrayTraps[key] = function() {\n arguments[0] = arguments[0][0];\n return fn.apply(this, arguments);\n };\n});\narrayTraps.deleteProperty = function(state, prop) {\n if (process.env.NODE_ENV !== \"production\" && isNaN(parseInt(prop)))\n die(13);\n return arrayTraps.set.call(this, state, prop, void 0);\n};\narrayTraps.set = function(state, prop, value) {\n if (process.env.NODE_ENV !== \"production\" && prop !== \"length\" && isNaN(parseInt(prop)))\n die(14);\n return objectTraps.set.call(this, state[0], prop, value, state[0]);\n};\nfunction peek(draft, prop) {\n const state = draft[DRAFT_STATE];\n const source = state ? latest(state) : draft;\n return source[prop];\n}\nfunction readPropFromProto(state, source, prop) {\n const desc = getDescriptorFromProto(source, prop);\n return desc ? `value` in desc ? desc.value : (\n // This is a very special case, if the prop is a getter defined by the\n // prototype, we should invoke it with the draft as context!\n desc.get?.call(state.draft_)\n ) : void 0;\n}\nfunction getDescriptorFromProto(source, prop) {\n if (!(prop in source))\n return void 0;\n let proto = getPrototypeOf(source);\n while (proto) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc)\n return desc;\n proto = getPrototypeOf(proto);\n }\n return void 0;\n}\nfunction markChanged(state) {\n if (!state.modified_) {\n state.modified_ = true;\n if (state.parent_) {\n markChanged(state.parent_);\n }\n }\n}\nfunction prepareCopy(state) {\n if (!state.copy_) {\n state.copy_ = shallowCopy(\n state.base_,\n state.scope_.immer_.useStrictShallowCopy_\n );\n }\n}\n\n// src/core/immerClass.ts\nvar Immer2 = class {\n constructor(config) {\n this.autoFreeze_ = true;\n this.useStrictShallowCopy_ = false;\n /**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\n this.produce = (base, recipe, patchListener) => {\n if (typeof base === \"function\" && typeof recipe !== \"function\") {\n const defaultBase = recipe;\n recipe = base;\n const self = this;\n return function curriedProduce(base2 = defaultBase, ...args) {\n return self.produce(base2, (draft) => recipe.call(this, draft, ...args));\n };\n }\n if (typeof recipe !== \"function\")\n die(6);\n if (patchListener !== void 0 && typeof patchListener !== \"function\")\n die(7);\n let result;\n if (isDraftable(base)) {\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n let hasError = true;\n try {\n result = recipe(proxy);\n hasError = false;\n } finally {\n if (hasError)\n revokeScope(scope);\n else\n leaveScope(scope);\n }\n usePatchesInScope(scope, patchListener);\n return processResult(result, scope);\n } else if (!base || typeof base !== \"object\") {\n result = recipe(base);\n if (result === void 0)\n result = base;\n if (result === NOTHING)\n result = void 0;\n if (this.autoFreeze_)\n freeze(result, true);\n if (patchListener) {\n const p = [];\n const ip = [];\n getPlugin(\"Patches\").generateReplacementPatches_(base, result, p, ip);\n patchListener(p, ip);\n }\n return result;\n } else\n die(1, base);\n };\n this.produceWithPatches = (base, recipe) => {\n if (typeof base === \"function\") {\n return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));\n }\n let patches, inversePatches;\n const result = this.produce(base, recipe, (p, ip) => {\n patches = p;\n inversePatches = ip;\n });\n return [result, patches, inversePatches];\n };\n if (typeof config?.autoFreeze === \"boolean\")\n this.setAutoFreeze(config.autoFreeze);\n if (typeof config?.useStrictShallowCopy === \"boolean\")\n this.setUseStrictShallowCopy(config.useStrictShallowCopy);\n }\n createDraft(base) {\n if (!isDraftable(base))\n die(8);\n if (isDraft(base))\n base = current(base);\n const scope = enterScope(this);\n const proxy = createProxy(base, void 0);\n proxy[DRAFT_STATE].isManual_ = true;\n leaveScope(scope);\n return proxy;\n }\n finishDraft(draft, patchListener) {\n const state = draft && draft[DRAFT_STATE];\n if (!state || !state.isManual_)\n die(9);\n const { scope_: scope } = state;\n usePatchesInScope(scope, patchListener);\n return processResult(void 0, scope);\n }\n /**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * By default, auto-freezing is enabled.\n */\n setAutoFreeze(value) {\n this.autoFreeze_ = value;\n }\n /**\n * Pass true to enable strict shallow copy.\n *\n * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.\n */\n setUseStrictShallowCopy(value) {\n this.useStrictShallowCopy_ = value;\n }\n applyPatches(base, patches) {\n let i;\n for (i = patches.length - 1; i >= 0; i--) {\n const patch = patches[i];\n if (patch.path.length === 0 && patch.op === \"replace\") {\n base = patch.value;\n break;\n }\n }\n if (i > -1) {\n patches = patches.slice(i + 1);\n }\n const applyPatchesImpl = getPlugin(\"Patches\").applyPatches_;\n if (isDraft(base)) {\n return applyPatchesImpl(base, patches);\n }\n return this.produce(\n base,\n (draft) => applyPatchesImpl(draft, patches)\n );\n }\n};\nfunction createProxy(value, parent) {\n const draft = isMap(value) ? getPlugin(\"MapSet\").proxyMap_(value, parent) : isSet(value) ? getPlugin(\"MapSet\").proxySet_(value, parent) : createProxyProxy(value, parent);\n const scope = parent ? parent.scope_ : getCurrentScope();\n scope.drafts_.push(draft);\n return draft;\n}\n\n// src/core/current.ts\nfunction current(value) {\n if (!isDraft(value))\n die(10, value);\n return currentImpl(value);\n}\nfunction currentImpl(value) {\n if (!isDraftable(value) || isFrozen(value))\n return value;\n const state = value[DRAFT_STATE];\n let copy;\n if (state) {\n if (!state.modified_)\n return state.base_;\n state.finalized_ = true;\n copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);\n } else {\n copy = shallowCopy(value, true);\n }\n each(copy, (key, childValue) => {\n set(copy, key, currentImpl(childValue));\n });\n if (state) {\n state.finalized_ = false;\n }\n return copy;\n}\n\n// src/plugins/patches.ts\nfunction enablePatches() {\n const errorOffset = 16;\n if (process.env.NODE_ENV !== \"production\") {\n errors.push(\n 'Sets cannot have \"replace\" patches.',\n function(op) {\n return \"Unsupported patch operation: \" + op;\n },\n function(path) {\n return \"Cannot apply patch, path doesn't resolve: \" + path;\n },\n \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n );\n }\n const REPLACE = \"replace\";\n const ADD = \"add\";\n const REMOVE = \"remove\";\n function generatePatches_(state, basePath, patches, inversePatches) {\n switch (state.type_) {\n case 0 /* Object */:\n case 2 /* Map */:\n return generatePatchesFromAssigned(\n state,\n basePath,\n patches,\n inversePatches\n );\n case 1 /* Array */:\n return generateArrayPatches(state, basePath, patches, inversePatches);\n case 3 /* Set */:\n return generateSetPatches(\n state,\n basePath,\n patches,\n inversePatches\n );\n }\n }\n function generateArrayPatches(state, basePath, patches, inversePatches) {\n let { base_, assigned_ } = state;\n let copy_ = state.copy_;\n if (copy_.length < base_.length) {\n ;\n [base_, copy_] = [copy_, base_];\n [patches, inversePatches] = [inversePatches, patches];\n }\n for (let i = 0; i < base_.length; i++) {\n if (assigned_[i] && copy_[i] !== base_[i]) {\n const path = basePath.concat([i]);\n patches.push({\n op: REPLACE,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n inversePatches.push({\n op: REPLACE,\n path,\n value: clonePatchValueIfNeeded(base_[i])\n });\n }\n }\n for (let i = base_.length; i < copy_.length; i++) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n // Need to maybe clone it, as it can in fact be the original value\n // due to the base/copy inversion at the start of this function\n value: clonePatchValueIfNeeded(copy_[i])\n });\n }\n for (let i = copy_.length - 1; base_.length <= i; --i) {\n const path = basePath.concat([i]);\n inversePatches.push({\n op: REMOVE,\n path\n });\n }\n }\n function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {\n const { base_, copy_ } = state;\n each(state.assigned_, (key, assignedValue) => {\n const origValue = get(base_, key);\n const value = get(copy_, key);\n const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;\n if (origValue === value && op === REPLACE)\n return;\n const path = basePath.concat(key);\n patches.push(op === REMOVE ? { op, path } : { op, path, value });\n inversePatches.push(\n op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }\n );\n });\n }\n function generateSetPatches(state, basePath, patches, inversePatches) {\n let { base_, copy_ } = state;\n let i = 0;\n base_.forEach((value) => {\n if (!copy_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: REMOVE,\n path,\n value\n });\n inversePatches.unshift({\n op: ADD,\n path,\n value\n });\n }\n i++;\n });\n i = 0;\n copy_.forEach((value) => {\n if (!base_.has(value)) {\n const path = basePath.concat([i]);\n patches.push({\n op: ADD,\n path,\n value\n });\n inversePatches.unshift({\n op: REMOVE,\n path,\n value\n });\n }\n i++;\n });\n }\n function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {\n patches.push({\n op: REPLACE,\n path: [],\n value: replacement === NOTHING ? void 0 : replacement\n });\n inversePatches.push({\n op: REPLACE,\n path: [],\n value: baseValue\n });\n }\n function applyPatches_(draft, patches) {\n patches.forEach((patch) => {\n const { path, op } = patch;\n let base = draft;\n for (let i = 0; i < path.length - 1; i++) {\n const parentType = getArchtype(base);\n let p = path[i];\n if (typeof p !== \"string\" && typeof p !== \"number\") {\n p = \"\" + p;\n }\n if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === \"__proto__\" || p === \"constructor\"))\n die(errorOffset + 3);\n if (typeof base === \"function\" && p === \"prototype\")\n die(errorOffset + 3);\n base = get(base, p);\n if (typeof base !== \"object\")\n die(errorOffset + 2, path.join(\"/\"));\n }\n const type = getArchtype(base);\n const value = deepClonePatchValue(patch.value);\n const key = path[path.length - 1];\n switch (op) {\n case REPLACE:\n switch (type) {\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n die(errorOffset);\n default:\n return base[key] = value;\n }\n case ADD:\n switch (type) {\n case 1 /* Array */:\n return key === \"-\" ? base.push(value) : base.splice(key, 0, value);\n case 2 /* Map */:\n return base.set(key, value);\n case 3 /* Set */:\n return base.add(value);\n default:\n return base[key] = value;\n }\n case REMOVE:\n switch (type) {\n case 1 /* Array */:\n return base.splice(key, 1);\n case 2 /* Map */:\n return base.delete(key);\n case 3 /* Set */:\n return base.delete(patch.value);\n default:\n return delete base[key];\n }\n default:\n die(errorOffset + 1, op);\n }\n });\n return draft;\n }\n function deepClonePatchValue(obj) {\n if (!isDraftable(obj))\n return obj;\n if (Array.isArray(obj))\n return obj.map(deepClonePatchValue);\n if (isMap(obj))\n return new Map(\n Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n );\n if (isSet(obj))\n return new Set(Array.from(obj).map(deepClonePatchValue));\n const cloned = Object.create(getPrototypeOf(obj));\n for (const key in obj)\n cloned[key] = deepClonePatchValue(obj[key]);\n if (has(obj, DRAFTABLE))\n cloned[DRAFTABLE] = obj[DRAFTABLE];\n return cloned;\n }\n function clonePatchValueIfNeeded(obj) {\n if (isDraft(obj)) {\n return deepClonePatchValue(obj);\n } else\n return obj;\n }\n loadPlugin(\"Patches\", {\n applyPatches_,\n generatePatches_,\n generateReplacementPatches_\n });\n}\n\n// src/plugins/mapset.ts\nfunction enableMapSet() {\n class DraftMap extends Map {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 2 /* Map */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n assigned_: void 0,\n base_: target,\n draft_: this,\n isManual_: false,\n revoked_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(key) {\n return latest(this[DRAFT_STATE]).has(key);\n }\n set(key, value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!latest(state).has(key) || latest(state).get(key) !== value) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_.set(key, true);\n state.copy_.set(key, value);\n state.assigned_.set(key, true);\n }\n return this;\n }\n delete(key) {\n if (!this.has(key)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareMapCopy(state);\n markChanged(state);\n if (state.base_.has(key)) {\n state.assigned_.set(key, false);\n } else {\n state.assigned_.delete(key);\n }\n state.copy_.delete(key);\n return true;\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareMapCopy(state);\n markChanged(state);\n state.assigned_ = /* @__PURE__ */ new Map();\n each(state.base_, (key) => {\n state.assigned_.set(key, false);\n });\n state.copy_.clear();\n }\n }\n forEach(cb, thisArg) {\n const state = this[DRAFT_STATE];\n latest(state).forEach((_value, key, _map) => {\n cb.call(thisArg, this.get(key), key, this);\n });\n }\n get(key) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n const value = latest(state).get(key);\n if (state.finalized_ || !isDraftable(value)) {\n return value;\n }\n if (value !== state.base_.get(key)) {\n return value;\n }\n const draft = createProxy(value, state);\n prepareMapCopy(state);\n state.copy_.set(key, draft);\n return draft;\n }\n keys() {\n return latest(this[DRAFT_STATE]).keys();\n }\n values() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.values(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value\n };\n }\n };\n }\n entries() {\n const iterator = this.keys();\n return {\n [Symbol.iterator]: () => this.entries(),\n next: () => {\n const r = iterator.next();\n if (r.done)\n return r;\n const value = this.get(r.value);\n return {\n done: false,\n value: [r.value, value]\n };\n }\n };\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.entries();\n }\n }\n function proxyMap_(target, parent) {\n return new DraftMap(target, parent);\n }\n function prepareMapCopy(state) {\n if (!state.copy_) {\n state.assigned_ = /* @__PURE__ */ new Map();\n state.copy_ = new Map(state.base_);\n }\n }\n class DraftSet extends Set {\n constructor(target, parent) {\n super();\n this[DRAFT_STATE] = {\n type_: 3 /* Set */,\n parent_: parent,\n scope_: parent ? parent.scope_ : getCurrentScope(),\n modified_: false,\n finalized_: false,\n copy_: void 0,\n base_: target,\n draft_: this,\n drafts_: /* @__PURE__ */ new Map(),\n revoked_: false,\n isManual_: false\n };\n }\n get size() {\n return latest(this[DRAFT_STATE]).size;\n }\n has(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!state.copy_) {\n return state.base_.has(value);\n }\n if (state.copy_.has(value))\n return true;\n if (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n return true;\n return false;\n }\n add(value) {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (!this.has(value)) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.add(value);\n }\n return this;\n }\n delete(value) {\n if (!this.has(value)) {\n return false;\n }\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n markChanged(state);\n return state.copy_.delete(value) || (state.drafts_.has(value) ? state.copy_.delete(state.drafts_.get(value)) : (\n /* istanbul ignore next */\n false\n ));\n }\n clear() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n if (latest(state).size) {\n prepareSetCopy(state);\n markChanged(state);\n state.copy_.clear();\n }\n }\n values() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.values();\n }\n entries() {\n const state = this[DRAFT_STATE];\n assertUnrevoked(state);\n prepareSetCopy(state);\n return state.copy_.entries();\n }\n keys() {\n return this.values();\n }\n [(DRAFT_STATE, Symbol.iterator)]() {\n return this.values();\n }\n forEach(cb, thisArg) {\n const iterator = this.values();\n let result = iterator.next();\n while (!result.done) {\n cb.call(thisArg, result.value, result.value, this);\n result = iterator.next();\n }\n }\n }\n function proxySet_(target, parent) {\n return new DraftSet(target, parent);\n }\n function prepareSetCopy(state) {\n if (!state.copy_) {\n state.copy_ = /* @__PURE__ */ new Set();\n state.base_.forEach((value) => {\n if (isDraftable(value)) {\n const draft = createProxy(value, state);\n state.drafts_.set(value, draft);\n state.copy_.add(draft);\n } else {\n state.copy_.add(value);\n }\n });\n }\n }\n function assertUnrevoked(state) {\n if (state.revoked_)\n die(3, JSON.stringify(latest(state)));\n }\n loadPlugin(\"MapSet\", { proxyMap_, proxySet_ });\n}\n\n// src/immer.ts\nvar immer = new Immer2();\nvar produce = immer.produce;\nvar produceWithPatches = immer.produceWithPatches.bind(\n immer\n);\nvar setAutoFreeze = immer.setAutoFreeze.bind(immer);\nvar setUseStrictShallowCopy = immer.setUseStrictShallowCopy.bind(immer);\nvar applyPatches = immer.applyPatches.bind(immer);\nvar createDraft = immer.createDraft.bind(immer);\nvar finishDraft = immer.finishDraft.bind(immer);\nfunction castDraft(value) {\n return value;\n}\nfunction castImmutable(value) {\n return value;\n}\nexport {\n Immer2 as Immer,\n applyPatches,\n castDraft,\n castImmutable,\n createDraft,\n current,\n enableMapSet,\n enablePatches,\n finishDraft,\n freeze,\n DRAFTABLE as immerable,\n isDraft,\n isDraftable,\n NOTHING as nothing,\n original,\n produce,\n produceWithPatches,\n setAutoFreeze,\n setUseStrictShallowCopy\n};\n//# sourceMappingURL=immer.mjs.map","// src/devModeChecks/identityFunctionCheck.ts\nvar runIdentityFunctionCheck = (resultFunc, inputSelectorsResults, outputSelectorResult) => {\n if (inputSelectorsResults.length === 1 && inputSelectorsResults[0] === outputSelectorResult) {\n let isInputSameAsOutput = false;\n try {\n const emptyObject = {};\n if (resultFunc(emptyObject) === emptyObject)\n isInputSameAsOutput = true;\n } catch {\n }\n if (isInputSameAsOutput) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"The result function returned its own inputs without modification. e.g\\n`createSelector([state => state.todos], todos => todos)`\\nThis could lead to inefficient memoization and unnecessary re-renders.\\nEnsure transformation logic is in the result function, and extraction logic is in the input selectors.\",\n { stack }\n );\n }\n }\n};\n\n// src/devModeChecks/inputStabilityCheck.ts\nvar runInputStabilityCheck = (inputSelectorResultsObject, options, inputSelectorArgs) => {\n const { memoize, memoizeOptions } = options;\n const { inputSelectorResults, inputSelectorResultsCopy } = inputSelectorResultsObject;\n const createAnEmptyObject = memoize(() => ({}), ...memoizeOptions);\n const areInputSelectorResultsEqual = createAnEmptyObject.apply(null, inputSelectorResults) === createAnEmptyObject.apply(null, inputSelectorResultsCopy);\n if (!areInputSelectorResultsEqual) {\n let stack = void 0;\n try {\n throw new Error();\n } catch (e) {\n ;\n ({ stack } = e);\n }\n console.warn(\n \"An input selector returned a different result when passed same arguments.\\nThis means your output selector will likely run more frequently than intended.\\nAvoid returning a new reference inside your input selector, e.g.\\n`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)`\",\n {\n arguments: inputSelectorArgs,\n firstInputs: inputSelectorResults,\n secondInputs: inputSelectorResultsCopy,\n stack\n }\n );\n }\n};\n\n// src/devModeChecks/setGlobalDevModeChecks.ts\nvar globalDevModeChecks = {\n inputStabilityCheck: \"once\",\n identityFunctionCheck: \"once\"\n};\nvar setGlobalDevModeChecks = (devModeChecks) => {\n Object.assign(globalDevModeChecks, devModeChecks);\n};\n\n// src/utils.ts\nvar NOT_FOUND = /* @__PURE__ */ Symbol(\"NOT_FOUND\");\nfunction assertIsFunction(func, errorMessage = `expected a function, instead received ${typeof func}`) {\n if (typeof func !== \"function\") {\n throw new TypeError(errorMessage);\n }\n}\nfunction assertIsObject(object, errorMessage = `expected an object, instead received ${typeof object}`) {\n if (typeof object !== \"object\") {\n throw new TypeError(errorMessage);\n }\n}\nfunction assertIsArrayOfFunctions(array, errorMessage = `expected all items to be functions, instead received the following types: `) {\n if (!array.every((item) => typeof item === \"function\")) {\n const itemTypes = array.map(\n (item) => typeof item === \"function\" ? `function ${item.name || \"unnamed\"}()` : typeof item\n ).join(\", \");\n throw new TypeError(`${errorMessage}[${itemTypes}]`);\n }\n}\nvar ensureIsArray = (item) => {\n return Array.isArray(item) ? item : [item];\n};\nfunction getDependencies(createSelectorArgs) {\n const dependencies = Array.isArray(createSelectorArgs[0]) ? createSelectorArgs[0] : createSelectorArgs;\n assertIsArrayOfFunctions(\n dependencies,\n `createSelector expects all input-selectors to be functions, but received the following types: `\n );\n return dependencies;\n}\nfunction collectInputSelectorResults(dependencies, inputSelectorArgs) {\n const inputSelectorResults = [];\n const { length } = dependencies;\n for (let i = 0; i < length; i++) {\n inputSelectorResults.push(dependencies[i].apply(null, inputSelectorArgs));\n }\n return inputSelectorResults;\n}\nvar getDevModeChecksExecutionInfo = (firstRun, devModeChecks) => {\n const { identityFunctionCheck, inputStabilityCheck } = {\n ...globalDevModeChecks,\n ...devModeChecks\n };\n return {\n identityFunctionCheck: {\n shouldRun: identityFunctionCheck === \"always\" || identityFunctionCheck === \"once\" && firstRun,\n run: runIdentityFunctionCheck\n },\n inputStabilityCheck: {\n shouldRun: inputStabilityCheck === \"always\" || inputStabilityCheck === \"once\" && firstRun,\n run: runInputStabilityCheck\n }\n };\n};\n\n// src/autotrackMemoize/autotracking.ts\nvar $REVISION = 0;\nvar CURRENT_TRACKER = null;\nvar Cell = class {\n revision = $REVISION;\n _value;\n _lastValue;\n _isEqual = tripleEq;\n constructor(initialValue, isEqual = tripleEq) {\n this._value = this._lastValue = initialValue;\n this._isEqual = isEqual;\n }\n // Whenever a storage value is read, it'll add itself to the current tracker if\n // one exists, entangling its state with that cache.\n get value() {\n CURRENT_TRACKER?.add(this);\n return this._value;\n }\n // Whenever a storage value is updated, we bump the global revision clock,\n // assign the revision for this storage to the new value, _and_ we schedule a\n // rerender. This is important, and it's what makes autotracking _pull_\n // based. We don't actively tell the caches which depend on the storage that\n // anything has happened. Instead, we recompute the caches when needed.\n set value(newValue) {\n if (this.value === newValue)\n return;\n this._value = newValue;\n this.revision = ++$REVISION;\n }\n};\nfunction tripleEq(a, b) {\n return a === b;\n}\nvar TrackingCache = class {\n _cachedValue;\n _cachedRevision = -1;\n _deps = [];\n hits = 0;\n fn;\n constructor(fn) {\n this.fn = fn;\n }\n clear() {\n this._cachedValue = void 0;\n this._cachedRevision = -1;\n this._deps = [];\n this.hits = 0;\n }\n get value() {\n if (this.revision > this._cachedRevision) {\n const { fn } = this;\n const currentTracker = /* @__PURE__ */ new Set();\n const prevTracker = CURRENT_TRACKER;\n CURRENT_TRACKER = currentTracker;\n this._cachedValue = fn();\n CURRENT_TRACKER = prevTracker;\n this.hits++;\n this._deps = Array.from(currentTracker);\n this._cachedRevision = this.revision;\n }\n CURRENT_TRACKER?.add(this);\n return this._cachedValue;\n }\n get revision() {\n return Math.max(...this._deps.map((d) => d.revision), 0);\n }\n};\nfunction getValue(cell) {\n if (!(cell instanceof Cell)) {\n console.warn(\"Not a valid cell! \", cell);\n }\n return cell.value;\n}\nfunction setValue(storage, value) {\n if (!(storage instanceof Cell)) {\n throw new TypeError(\n \"setValue must be passed a tracked store created with `createStorage`.\"\n );\n }\n storage.value = storage._lastValue = value;\n}\nfunction createCell(initialValue, isEqual = tripleEq) {\n return new Cell(initialValue, isEqual);\n}\nfunction createCache(fn) {\n assertIsFunction(\n fn,\n \"the first parameter to `createCache` must be a function\"\n );\n return new TrackingCache(fn);\n}\n\n// src/autotrackMemoize/tracking.ts\nvar neverEq = (a, b) => false;\nfunction createTag() {\n return createCell(null, neverEq);\n}\nfunction dirtyTag(tag, value) {\n setValue(tag, value);\n}\nvar consumeCollection = (node) => {\n let tag = node.collectionTag;\n if (tag === null) {\n tag = node.collectionTag = createTag();\n }\n getValue(tag);\n};\nvar dirtyCollection = (node) => {\n const tag = node.collectionTag;\n if (tag !== null) {\n dirtyTag(tag, null);\n }\n};\n\n// src/autotrackMemoize/proxy.ts\nvar REDUX_PROXY_LABEL = Symbol();\nvar nextId = 0;\nvar proto = Object.getPrototypeOf({});\nvar ObjectTreeNode = class {\n constructor(value) {\n this.value = value;\n this.value = value;\n this.tag.value = value;\n }\n proxy = new Proxy(this, objectProxyHandler);\n tag = createTag();\n tags = {};\n children = {};\n collectionTag = null;\n id = nextId++;\n};\nvar objectProxyHandler = {\n get(node, key) {\n function calculateResult() {\n const { value } = node;\n const childValue = Reflect.get(value, key);\n if (typeof key === \"symbol\") {\n return childValue;\n }\n if (key in proto) {\n return childValue;\n }\n if (typeof childValue === \"object\" && childValue !== null) {\n let childNode = node.children[key];\n if (childNode === void 0) {\n childNode = node.children[key] = createNode(childValue);\n }\n if (childNode.tag) {\n getValue(childNode.tag);\n }\n return childNode.proxy;\n } else {\n let tag = node.tags[key];\n if (tag === void 0) {\n tag = node.tags[key] = createTag();\n tag.value = childValue;\n }\n getValue(tag);\n return childValue;\n }\n }\n const res = calculateResult();\n return res;\n },\n ownKeys(node) {\n consumeCollection(node);\n return Reflect.ownKeys(node.value);\n },\n getOwnPropertyDescriptor(node, prop) {\n return Reflect.getOwnPropertyDescriptor(node.value, prop);\n },\n has(node, prop) {\n return Reflect.has(node.value, prop);\n }\n};\nvar ArrayTreeNode = class {\n constructor(value) {\n this.value = value;\n this.value = value;\n this.tag.value = value;\n }\n proxy = new Proxy([this], arrayProxyHandler);\n tag = createTag();\n tags = {};\n children = {};\n collectionTag = null;\n id = nextId++;\n};\nvar arrayProxyHandler = {\n get([node], key) {\n if (key === \"length\") {\n consumeCollection(node);\n }\n return objectProxyHandler.get(node, key);\n },\n ownKeys([node]) {\n return objectProxyHandler.ownKeys(node);\n },\n getOwnPropertyDescriptor([node], prop) {\n return objectProxyHandler.getOwnPropertyDescriptor(node, prop);\n },\n has([node], prop) {\n return objectProxyHandler.has(node, prop);\n }\n};\nfunction createNode(value) {\n if (Array.isArray(value)) {\n return new ArrayTreeNode(value);\n }\n return new ObjectTreeNode(value);\n}\nfunction updateNode(node, newValue) {\n const { value, tags, children } = node;\n node.value = newValue;\n if (Array.isArray(value) && Array.isArray(newValue) && value.length !== newValue.length) {\n dirtyCollection(node);\n } else {\n if (value !== newValue) {\n let oldKeysSize = 0;\n let newKeysSize = 0;\n let anyKeysAdded = false;\n for (const _key in value) {\n oldKeysSize++;\n }\n for (const key in newValue) {\n newKeysSize++;\n if (!(key in value)) {\n anyKeysAdded = true;\n break;\n }\n }\n const isDifferent = anyKeysAdded || oldKeysSize !== newKeysSize;\n if (isDifferent) {\n dirtyCollection(node);\n }\n }\n }\n for (const key in tags) {\n const childValue = value[key];\n const newChildValue = newValue[key];\n if (childValue !== newChildValue) {\n dirtyCollection(node);\n dirtyTag(tags[key], newChildValue);\n }\n if (typeof newChildValue === \"object\" && newChildValue !== null) {\n delete tags[key];\n }\n }\n for (const key in children) {\n const childNode = children[key];\n const newChildValue = newValue[key];\n const childValue = childNode.value;\n if (childValue === newChildValue) {\n continue;\n } else if (typeof newChildValue === \"object\" && newChildValue !== null) {\n updateNode(childNode, newChildValue);\n } else {\n deleteNode(childNode);\n delete children[key];\n }\n }\n}\nfunction deleteNode(node) {\n if (node.tag) {\n dirtyTag(node.tag, null);\n }\n dirtyCollection(node);\n for (const key in node.tags) {\n dirtyTag(node.tags[key], null);\n }\n for (const key in node.children) {\n deleteNode(node.children[key]);\n }\n}\n\n// src/lruMemoize.ts\nfunction createSingletonCache(equals) {\n let entry;\n return {\n get(key) {\n if (entry && equals(entry.key, key)) {\n return entry.value;\n }\n return NOT_FOUND;\n },\n put(key, value) {\n entry = { key, value };\n },\n getEntries() {\n return entry ? [entry] : [];\n },\n clear() {\n entry = void 0;\n }\n };\n}\nfunction createLruCache(maxSize, equals) {\n let entries = [];\n function get(key) {\n const cacheIndex = entries.findIndex((entry) => equals(key, entry.key));\n if (cacheIndex > -1) {\n const entry = entries[cacheIndex];\n if (cacheIndex > 0) {\n entries.splice(cacheIndex, 1);\n entries.unshift(entry);\n }\n return entry.value;\n }\n return NOT_FOUND;\n }\n function put(key, value) {\n if (get(key) === NOT_FOUND) {\n entries.unshift({ key, value });\n if (entries.length > maxSize) {\n entries.pop();\n }\n }\n }\n function getEntries() {\n return entries;\n }\n function clear() {\n entries = [];\n }\n return { get, put, getEntries, clear };\n}\nvar referenceEqualityCheck = (a, b) => a === b;\nfunction createCacheKeyComparator(equalityCheck) {\n return function areArgumentsShallowlyEqual(prev, next) {\n if (prev === null || next === null || prev.length !== next.length) {\n return false;\n }\n const { length } = prev;\n for (let i = 0; i < length; i++) {\n if (!equalityCheck(prev[i], next[i])) {\n return false;\n }\n }\n return true;\n };\n}\nfunction lruMemoize(func, equalityCheckOrOptions) {\n const providedOptions = typeof equalityCheckOrOptions === \"object\" ? equalityCheckOrOptions : { equalityCheck: equalityCheckOrOptions };\n const {\n equalityCheck = referenceEqualityCheck,\n maxSize = 1,\n resultEqualityCheck\n } = providedOptions;\n const comparator = createCacheKeyComparator(equalityCheck);\n let resultsCount = 0;\n const cache = maxSize <= 1 ? createSingletonCache(comparator) : createLruCache(maxSize, comparator);\n function memoized() {\n let value = cache.get(arguments);\n if (value === NOT_FOUND) {\n value = func.apply(null, arguments);\n resultsCount++;\n if (resultEqualityCheck) {\n const entries = cache.getEntries();\n const matchingEntry = entries.find(\n (entry) => resultEqualityCheck(entry.value, value)\n );\n if (matchingEntry) {\n value = matchingEntry.value;\n resultsCount !== 0 && resultsCount--;\n }\n }\n cache.put(arguments, value);\n }\n return value;\n }\n memoized.clearCache = () => {\n cache.clear();\n memoized.resetResultsCount();\n };\n memoized.resultsCount = () => resultsCount;\n memoized.resetResultsCount = () => {\n resultsCount = 0;\n };\n return memoized;\n}\n\n// src/autotrackMemoize/autotrackMemoize.ts\nfunction autotrackMemoize(func) {\n const node = createNode(\n []\n );\n let lastArgs = null;\n const shallowEqual = createCacheKeyComparator(referenceEqualityCheck);\n const cache = createCache(() => {\n const res = func.apply(null, node.proxy);\n return res;\n });\n function memoized() {\n if (!shallowEqual(lastArgs, arguments)) {\n updateNode(node, arguments);\n lastArgs = arguments;\n }\n return cache.value;\n }\n memoized.clearCache = () => {\n return cache.clear();\n };\n return memoized;\n}\n\n// src/weakMapMemoize.ts\nvar StrongRef = class {\n constructor(value) {\n this.value = value;\n }\n deref() {\n return this.value;\n }\n};\nvar Ref = typeof WeakRef !== \"undefined\" ? WeakRef : StrongRef;\nvar UNTERMINATED = 0;\nvar TERMINATED = 1;\nfunction createCacheNode() {\n return {\n s: UNTERMINATED,\n v: void 0,\n o: null,\n p: null\n };\n}\nfunction weakMapMemoize(func, options = {}) {\n let fnNode = createCacheNode();\n const { resultEqualityCheck } = options;\n let lastResult;\n let resultsCount = 0;\n function memoized() {\n let cacheNode = fnNode;\n const { length } = arguments;\n for (let i = 0, l = length; i < l; i++) {\n const arg = arguments[i];\n if (typeof arg === \"function\" || typeof arg === \"object\" && arg !== null) {\n let objectCache = cacheNode.o;\n if (objectCache === null) {\n cacheNode.o = objectCache = /* @__PURE__ */ new WeakMap();\n }\n const objectNode = objectCache.get(arg);\n if (objectNode === void 0) {\n cacheNode = createCacheNode();\n objectCache.set(arg, cacheNode);\n } else {\n cacheNode = objectNode;\n }\n } else {\n let primitiveCache = cacheNode.p;\n if (primitiveCache === null) {\n cacheNode.p = primitiveCache = /* @__PURE__ */ new Map();\n }\n const primitiveNode = primitiveCache.get(arg);\n if (primitiveNode === void 0) {\n cacheNode = createCacheNode();\n primitiveCache.set(arg, cacheNode);\n } else {\n cacheNode = primitiveNode;\n }\n }\n }\n const terminatedNode = cacheNode;\n let result;\n if (cacheNode.s === TERMINATED) {\n result = cacheNode.v;\n } else {\n result = func.apply(null, arguments);\n resultsCount++;\n if (resultEqualityCheck) {\n const lastResultValue = lastResult?.deref?.() ?? lastResult;\n if (lastResultValue != null && resultEqualityCheck(lastResultValue, result)) {\n result = lastResultValue;\n resultsCount !== 0 && resultsCount--;\n }\n const needsWeakRef = typeof result === \"object\" && result !== null || typeof result === \"function\";\n lastResult = needsWeakRef ? new Ref(result) : result;\n }\n }\n terminatedNode.s = TERMINATED;\n terminatedNode.v = result;\n return result;\n }\n memoized.clearCache = () => {\n fnNode = createCacheNode();\n memoized.resetResultsCount();\n };\n memoized.resultsCount = () => resultsCount;\n memoized.resetResultsCount = () => {\n resultsCount = 0;\n };\n return memoized;\n}\n\n// src/createSelectorCreator.ts\nfunction createSelectorCreator(memoizeOrOptions, ...memoizeOptionsFromArgs) {\n const createSelectorCreatorOptions = typeof memoizeOrOptions === \"function\" ? {\n memoize: memoizeOrOptions,\n memoizeOptions: memoizeOptionsFromArgs\n } : memoizeOrOptions;\n const createSelector2 = (...createSelectorArgs) => {\n let recomputations = 0;\n let dependencyRecomputations = 0;\n let lastResult;\n let directlyPassedOptions = {};\n let resultFunc = createSelectorArgs.pop();\n if (typeof resultFunc === \"object\") {\n directlyPassedOptions = resultFunc;\n resultFunc = createSelectorArgs.pop();\n }\n assertIsFunction(\n resultFunc,\n `createSelector expects an output function after the inputs, but received: [${typeof resultFunc}]`\n );\n const combinedOptions = {\n ...createSelectorCreatorOptions,\n ...directlyPassedOptions\n };\n const {\n memoize,\n memoizeOptions = [],\n argsMemoize = weakMapMemoize,\n argsMemoizeOptions = [],\n devModeChecks = {}\n } = combinedOptions;\n const finalMemoizeOptions = ensureIsArray(memoizeOptions);\n const finalArgsMemoizeOptions = ensureIsArray(argsMemoizeOptions);\n const dependencies = getDependencies(createSelectorArgs);\n const memoizedResultFunc = memoize(function recomputationWrapper() {\n recomputations++;\n return resultFunc.apply(\n null,\n arguments\n );\n }, ...finalMemoizeOptions);\n let firstRun = true;\n const selector = argsMemoize(function dependenciesChecker() {\n dependencyRecomputations++;\n const inputSelectorResults = collectInputSelectorResults(\n dependencies,\n arguments\n );\n lastResult = memoizedResultFunc.apply(null, inputSelectorResults);\n if (process.env.NODE_ENV !== \"production\") {\n const { identityFunctionCheck, inputStabilityCheck } = getDevModeChecksExecutionInfo(firstRun, devModeChecks);\n if (identityFunctionCheck.shouldRun) {\n identityFunctionCheck.run(\n resultFunc,\n inputSelectorResults,\n lastResult\n );\n }\n if (inputStabilityCheck.shouldRun) {\n const inputSelectorResultsCopy = collectInputSelectorResults(\n dependencies,\n arguments\n );\n inputStabilityCheck.run(\n { inputSelectorResults, inputSelectorResultsCopy },\n { memoize, memoizeOptions: finalMemoizeOptions },\n arguments\n );\n }\n if (firstRun)\n firstRun = false;\n }\n return lastResult;\n }, ...finalArgsMemoizeOptions);\n return Object.assign(selector, {\n resultFunc,\n memoizedResultFunc,\n dependencies,\n dependencyRecomputations: () => dependencyRecomputations,\n resetDependencyRecomputations: () => {\n dependencyRecomputations = 0;\n },\n lastResult: () => lastResult,\n recomputations: () => recomputations,\n resetRecomputations: () => {\n recomputations = 0;\n },\n memoize,\n argsMemoize\n });\n };\n Object.assign(createSelector2, {\n withTypes: () => createSelector2\n });\n return createSelector2;\n}\nvar createSelector = /* @__PURE__ */ createSelectorCreator(weakMapMemoize);\n\n// src/createStructuredSelector.ts\nvar createStructuredSelector = Object.assign(\n (inputSelectorsObject, selectorCreator = createSelector) => {\n assertIsObject(\n inputSelectorsObject,\n `createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof inputSelectorsObject}`\n );\n const inputSelectorKeys = Object.keys(inputSelectorsObject);\n const dependencies = inputSelectorKeys.map(\n (key) => inputSelectorsObject[key]\n );\n const structuredSelector = selectorCreator(\n dependencies,\n (...inputSelectorResults) => {\n return inputSelectorResults.reduce((composition, value, index) => {\n composition[inputSelectorKeys[index]] = value;\n return composition;\n }, {});\n }\n );\n return structuredSelector;\n },\n { withTypes: () => createStructuredSelector }\n);\nexport {\n createSelector,\n createSelectorCreator,\n createStructuredSelector,\n lruMemoize,\n referenceEqualityCheck,\n setGlobalDevModeChecks,\n autotrackMemoize as unstable_autotrackMemoize,\n weakMapMemoize\n};\n//# sourceMappingURL=reselect.mjs.map","// src/index.ts\nfunction createThunkMiddleware(extraArgument) {\n const middleware = ({ dispatch, getState }) => (next) => (action) => {\n if (typeof action === \"function\") {\n return action(dispatch, getState, extraArgument);\n }\n return next(action);\n };\n return middleware;\n}\nvar thunk = createThunkMiddleware();\nvar withExtraArgument = createThunkMiddleware;\nexport {\n thunk,\n withExtraArgument\n};\n","// src/index.ts\nexport * from \"redux\";\nimport { produce, current as current3, freeze, original as original2, isDraft as isDraft5 } from \"immer\";\nimport { createSelector, createSelectorCreator as createSelectorCreator2, lruMemoize, weakMapMemoize as weakMapMemoize2 } from \"reselect\";\n\n// src/createDraftSafeSelector.ts\nimport { current, isDraft } from \"immer\";\nimport { createSelectorCreator, weakMapMemoize } from \"reselect\";\nvar createDraftSafeSelectorCreator = (...args) => {\n const createSelector2 = createSelectorCreator(...args);\n const createDraftSafeSelector2 = Object.assign((...args2) => {\n const selector = createSelector2(...args2);\n const wrappedSelector = (value, ...rest) => selector(isDraft(value) ? current(value) : value, ...rest);\n Object.assign(wrappedSelector, selector);\n return wrappedSelector;\n }, {\n withTypes: () => createDraftSafeSelector2\n });\n return createDraftSafeSelector2;\n};\nvar createDraftSafeSelector = createDraftSafeSelectorCreator(weakMapMemoize);\n\n// src/configureStore.ts\nimport { applyMiddleware, createStore, compose as compose2, combineReducers, isPlainObject as isPlainObject2 } from \"redux\";\n\n// src/devtoolsExtension.ts\nimport { compose } from \"redux\";\nvar composeWithDevTools = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ : function() {\n if (arguments.length === 0)\n return void 0;\n if (typeof arguments[0] === \"object\")\n return compose;\n return compose.apply(null, arguments);\n};\nvar devToolsEnhancer = typeof window !== \"undefined\" && window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__ : function() {\n return function(noop3) {\n return noop3;\n };\n};\n\n// src/getDefaultMiddleware.ts\nimport { thunk as thunkMiddleware, withExtraArgument } from \"redux-thunk\";\n\n// src/createAction.ts\nimport { isAction } from \"redux\";\n\n// src/tsHelpers.ts\nvar hasMatchFunction = (v) => {\n return v && typeof v.match === \"function\";\n};\n\n// src/createAction.ts\nfunction createAction(type, prepareAction) {\n function actionCreator(...args) {\n if (prepareAction) {\n let prepared = prepareAction(...args);\n if (!prepared) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : \"prepareAction did not return an object\");\n }\n return {\n type,\n payload: prepared.payload,\n ...\"meta\" in prepared && {\n meta: prepared.meta\n },\n ...\"error\" in prepared && {\n error: prepared.error\n }\n };\n }\n return {\n type,\n payload: args[0]\n };\n }\n actionCreator.toString = () => `${type}`;\n actionCreator.type = type;\n actionCreator.match = (action) => isAction(action) && action.type === type;\n return actionCreator;\n}\nfunction isActionCreator(action) {\n return typeof action === \"function\" && \"type\" in action && // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n hasMatchFunction(action);\n}\nfunction isFSA(action) {\n return isAction(action) && Object.keys(action).every(isValidKey);\n}\nfunction isValidKey(key) {\n return [\"type\", \"payload\", \"error\", \"meta\"].indexOf(key) > -1;\n}\n\n// src/actionCreatorInvariantMiddleware.ts\nfunction getMessage(type) {\n const splitType = type ? `${type}`.split(\"/\") : [];\n const actionName = splitType[splitType.length - 1] || \"actionCreator\";\n return `Detected an action creator with type \"${type || \"unknown\"}\" being dispatched. \nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`;\n}\nfunction createActionCreatorInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n }\n const {\n isActionCreator: isActionCreator2 = isActionCreator\n } = options;\n return () => (next) => (action) => {\n if (isActionCreator2(action)) {\n console.warn(getMessage(action.type));\n }\n return next(action);\n };\n}\n\n// src/utils.ts\nimport { produce as createNextState, isDraftable } from \"immer\";\nfunction getTimeMeasureUtils(maxDelay, fnName) {\n let elapsed = 0;\n return {\n measureTime(fn) {\n const started = Date.now();\n try {\n return fn();\n } finally {\n const finished = Date.now();\n elapsed += finished - started;\n }\n },\n warnIfExceeded() {\n if (elapsed > maxDelay) {\n console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`);\n }\n }\n };\n}\nfunction find(iterable, comparator) {\n for (const entry of iterable) {\n if (comparator(entry)) {\n return entry;\n }\n }\n return void 0;\n}\nvar Tuple = class _Tuple extends Array {\n constructor(...items) {\n super(...items);\n Object.setPrototypeOf(this, _Tuple.prototype);\n }\n static get [Symbol.species]() {\n return _Tuple;\n }\n concat(...arr) {\n return super.concat.apply(this, arr);\n }\n prepend(...arr) {\n if (arr.length === 1 && Array.isArray(arr[0])) {\n return new _Tuple(...arr[0].concat(this));\n }\n return new _Tuple(...arr.concat(this));\n }\n};\nfunction freezeDraftable(val) {\n return isDraftable(val) ? createNextState(val, () => {\n }) : val;\n}\nfunction emplace(map, key, handler) {\n if (map.has(key)) {\n let value = map.get(key);\n if (handler.update) {\n value = handler.update(value, key, map);\n map.set(key, value);\n }\n return value;\n }\n if (!handler.insert)\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : \"No insert provided for key not already in map\");\n const inserted = handler.insert(key, map);\n map.set(key, inserted);\n return inserted;\n}\n\n// src/immutableStateInvariantMiddleware.ts\nfunction isImmutableDefault(value) {\n return typeof value !== \"object\" || value == null || Object.isFrozen(value);\n}\nfunction trackForMutations(isImmutable, ignorePaths, obj) {\n const trackedProperties = trackProperties(isImmutable, ignorePaths, obj);\n return {\n detectMutations() {\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj);\n }\n };\n}\nfunction trackProperties(isImmutable, ignorePaths = [], obj, path = \"\", checkedObjects = /* @__PURE__ */ new Set()) {\n const tracked = {\n value: obj\n };\n if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n checkedObjects.add(obj);\n tracked.children = {};\n for (const key in obj) {\n const childPath = path ? path + \".\" + key : key;\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\n continue;\n }\n tracked.children[key] = trackProperties(isImmutable, ignorePaths, obj[key], childPath);\n }\n }\n return tracked;\n}\nfunction detectMutations(isImmutable, ignoredPaths = [], trackedProperty, obj, sameParentRef = false, path = \"\") {\n const prevObj = trackedProperty ? trackedProperty.value : void 0;\n const sameRef = prevObj === obj;\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n return {\n wasMutated: true,\n path\n };\n }\n if (isImmutable(prevObj) || isImmutable(obj)) {\n return {\n wasMutated: false\n };\n }\n const keysToDetect = {};\n for (let key in trackedProperty.children) {\n keysToDetect[key] = true;\n }\n for (let key in obj) {\n keysToDetect[key] = true;\n }\n const hasIgnoredPaths = ignoredPaths.length > 0;\n for (let key in keysToDetect) {\n const nestedPath = path ? path + \".\" + key : key;\n if (hasIgnoredPaths) {\n const hasMatches = ignoredPaths.some((ignored) => {\n if (ignored instanceof RegExp) {\n return ignored.test(nestedPath);\n }\n return nestedPath === ignored;\n });\n if (hasMatches) {\n continue;\n }\n }\n const result = detectMutations(isImmutable, ignoredPaths, trackedProperty.children[key], obj[key], sameRef, nestedPath);\n if (result.wasMutated) {\n return result;\n }\n }\n return {\n wasMutated: false\n };\n}\nfunction createImmutableStateInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n } else {\n let stringify2 = function(obj, serializer, indent, decycler) {\n return JSON.stringify(obj, getSerialize2(serializer, decycler), indent);\n }, getSerialize2 = function(serializer, decycler) {\n let stack = [], keys = [];\n if (!decycler)\n decycler = function(_, value) {\n if (stack[0] === value)\n return \"[Circular ~]\";\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\";\n };\n return function(key, value) {\n if (stack.length > 0) {\n var thisPos = stack.indexOf(this);\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this);\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);\n if (~stack.indexOf(value))\n value = decycler.call(this, key, value);\n } else\n stack.push(value);\n return serializer == null ? value : serializer.call(this, key, value);\n };\n };\n var stringify = stringify2, getSerialize = getSerialize2;\n let {\n isImmutable = isImmutableDefault,\n ignoredPaths,\n warnAfter = 32\n } = options;\n const track = trackForMutations.bind(null, isImmutable, ignoredPaths);\n return ({\n getState\n }) => {\n let state = getState();\n let tracker = track(state);\n let result;\n return (next) => (action) => {\n const measureUtils = getTimeMeasureUtils(warnAfter, \"ImmutableStateInvariantMiddleware\");\n measureUtils.measureTime(() => {\n state = getState();\n result = tracker.detectMutations();\n tracker = track(state);\n if (result.wasMutated) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(19) : `A state mutation was detected between dispatches, in the path '${result.path || \"\"}'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n }\n });\n const dispatchedAction = next(action);\n measureUtils.measureTime(() => {\n state = getState();\n result = tracker.detectMutations();\n tracker = track(state);\n if (result.wasMutated) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(20) : `A state mutation was detected inside a dispatch, in the path: ${result.path || \"\"}. Take a look at the reducer(s) handling the action ${stringify2(action)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`);\n }\n });\n measureUtils.warnIfExceeded();\n return dispatchedAction;\n };\n };\n }\n}\n\n// src/serializableStateInvariantMiddleware.ts\nimport { isAction as isAction2, isPlainObject } from \"redux\";\nfunction isPlain(val) {\n const type = typeof val;\n return val == null || type === \"string\" || type === \"boolean\" || type === \"number\" || Array.isArray(val) || isPlainObject(val);\n}\nfunction findNonSerializableValue(value, path = \"\", isSerializable = isPlain, getEntries, ignoredPaths = [], cache) {\n let foundNestedSerializable;\n if (!isSerializable(value)) {\n return {\n keyPath: path || \"\",\n value\n };\n }\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n if (cache?.has(value))\n return false;\n const entries = getEntries != null ? getEntries(value) : Object.entries(value);\n const hasIgnoredPaths = ignoredPaths.length > 0;\n for (const [key, nestedValue] of entries) {\n const nestedPath = path ? path + \".\" + key : key;\n if (hasIgnoredPaths) {\n const hasMatches = ignoredPaths.some((ignored) => {\n if (ignored instanceof RegExp) {\n return ignored.test(nestedPath);\n }\n return nestedPath === ignored;\n });\n if (hasMatches) {\n continue;\n }\n }\n if (!isSerializable(nestedValue)) {\n return {\n keyPath: nestedPath,\n value: nestedValue\n };\n }\n if (typeof nestedValue === \"object\") {\n foundNestedSerializable = findNonSerializableValue(nestedValue, nestedPath, isSerializable, getEntries, ignoredPaths, cache);\n if (foundNestedSerializable) {\n return foundNestedSerializable;\n }\n }\n }\n if (cache && isNestedFrozen(value))\n cache.add(value);\n return false;\n}\nfunction isNestedFrozen(value) {\n if (!Object.isFrozen(value))\n return false;\n for (const nestedValue of Object.values(value)) {\n if (typeof nestedValue !== \"object\" || nestedValue === null)\n continue;\n if (!isNestedFrozen(nestedValue))\n return false;\n }\n return true;\n}\nfunction createSerializableStateInvariantMiddleware(options = {}) {\n if (process.env.NODE_ENV === \"production\") {\n return () => (next) => (action) => next(action);\n } else {\n const {\n isSerializable = isPlain,\n getEntries,\n ignoredActions = [],\n ignoredActionPaths = [\"meta.arg\", \"meta.baseQueryMeta\"],\n ignoredPaths = [],\n warnAfter = 32,\n ignoreState = false,\n ignoreActions = false,\n disableCache = false\n } = options;\n const cache = !disableCache && WeakSet ? /* @__PURE__ */ new WeakSet() : void 0;\n return (storeAPI) => (next) => (action) => {\n if (!isAction2(action)) {\n return next(action);\n }\n const result = next(action);\n const measureUtils = getTimeMeasureUtils(warnAfter, \"SerializableStateInvariantMiddleware\");\n if (!ignoreActions && !(ignoredActions.length && ignoredActions.indexOf(action.type) !== -1)) {\n measureUtils.measureTime(() => {\n const foundActionNonSerializableValue = findNonSerializableValue(action, \"\", isSerializable, getEntries, ignoredActionPaths, cache);\n if (foundActionNonSerializableValue) {\n const {\n keyPath,\n value\n } = foundActionNonSerializableValue;\n console.error(`A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`, value, \"\\nTake a look at the logic that dispatched this action: \", action, \"\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)\", \"\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)\");\n }\n });\n }\n if (!ignoreState) {\n measureUtils.measureTime(() => {\n const state = storeAPI.getState();\n const foundStateNonSerializableValue = findNonSerializableValue(state, \"\", isSerializable, getEntries, ignoredPaths, cache);\n if (foundStateNonSerializableValue) {\n const {\n keyPath,\n value\n } = foundStateNonSerializableValue;\n console.error(`A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`, value, `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`);\n }\n });\n measureUtils.warnIfExceeded();\n }\n return result;\n };\n }\n}\n\n// src/getDefaultMiddleware.ts\nfunction isBoolean(x) {\n return typeof x === \"boolean\";\n}\nvar buildGetDefaultMiddleware = () => function getDefaultMiddleware(options) {\n const {\n thunk = true,\n immutableCheck = true,\n serializableCheck = true,\n actionCreatorCheck = true\n } = options ?? {};\n let middlewareArray = new Tuple();\n if (thunk) {\n if (isBoolean(thunk)) {\n middlewareArray.push(thunkMiddleware);\n } else {\n middlewareArray.push(withExtraArgument(thunk.extraArgument));\n }\n }\n if (process.env.NODE_ENV !== \"production\") {\n if (immutableCheck) {\n let immutableOptions = {};\n if (!isBoolean(immutableCheck)) {\n immutableOptions = immutableCheck;\n }\n middlewareArray.unshift(createImmutableStateInvariantMiddleware(immutableOptions));\n }\n if (serializableCheck) {\n let serializableOptions = {};\n if (!isBoolean(serializableCheck)) {\n serializableOptions = serializableCheck;\n }\n middlewareArray.push(createSerializableStateInvariantMiddleware(serializableOptions));\n }\n if (actionCreatorCheck) {\n let actionCreatorOptions = {};\n if (!isBoolean(actionCreatorCheck)) {\n actionCreatorOptions = actionCreatorCheck;\n }\n middlewareArray.unshift(createActionCreatorInvariantMiddleware(actionCreatorOptions));\n }\n }\n return middlewareArray;\n};\n\n// src/autoBatchEnhancer.ts\nvar SHOULD_AUTOBATCH = \"RTK_autoBatch\";\nvar prepareAutoBatched = () => (payload) => ({\n payload,\n meta: {\n [SHOULD_AUTOBATCH]: true\n }\n});\nvar createQueueWithTimer = (timeout) => {\n return (notify) => {\n setTimeout(notify, timeout);\n };\n};\nvar rAF = typeof window !== \"undefined\" && window.requestAnimationFrame ? window.requestAnimationFrame : createQueueWithTimer(10);\nvar autoBatchEnhancer = (options = {\n type: \"raf\"\n}) => (next) => (...args) => {\n const store = next(...args);\n let notifying = true;\n let shouldNotifyAtEndOfTick = false;\n let notificationQueued = false;\n const listeners = /* @__PURE__ */ new Set();\n const queueCallback = options.type === \"tick\" ? queueMicrotask : options.type === \"raf\" ? rAF : options.type === \"callback\" ? options.queueNotification : createQueueWithTimer(options.timeout);\n const notifyListeners = () => {\n notificationQueued = false;\n if (shouldNotifyAtEndOfTick) {\n shouldNotifyAtEndOfTick = false;\n listeners.forEach((l) => l());\n }\n };\n return Object.assign({}, store, {\n // Override the base `store.subscribe` method to keep original listeners\n // from running if we're delaying notifications\n subscribe(listener2) {\n const wrappedListener = () => notifying && listener2();\n const unsubscribe = store.subscribe(wrappedListener);\n listeners.add(listener2);\n return () => {\n unsubscribe();\n listeners.delete(listener2);\n };\n },\n // Override the base `store.dispatch` method so that we can check actions\n // for the `shouldAutoBatch` flag and determine if batching is active\n dispatch(action) {\n try {\n notifying = !action?.meta?.[SHOULD_AUTOBATCH];\n shouldNotifyAtEndOfTick = !notifying;\n if (shouldNotifyAtEndOfTick) {\n if (!notificationQueued) {\n notificationQueued = true;\n queueCallback(notifyListeners);\n }\n }\n return store.dispatch(action);\n } finally {\n notifying = true;\n }\n }\n });\n};\n\n// src/getDefaultEnhancers.ts\nvar buildGetDefaultEnhancers = (middlewareEnhancer) => function getDefaultEnhancers(options) {\n const {\n autoBatch = true\n } = options ?? {};\n let enhancerArray = new Tuple(middlewareEnhancer);\n if (autoBatch) {\n enhancerArray.push(autoBatchEnhancer(typeof autoBatch === \"object\" ? autoBatch : void 0));\n }\n return enhancerArray;\n};\n\n// src/configureStore.ts\nvar IS_PRODUCTION = process.env.NODE_ENV === \"production\";\nfunction configureStore(options) {\n const getDefaultMiddleware = buildGetDefaultMiddleware();\n const {\n reducer = void 0,\n middleware,\n devTools = true,\n preloadedState = void 0,\n enhancers = void 0\n } = options || {};\n let rootReducer;\n if (typeof reducer === \"function\") {\n rootReducer = reducer;\n } else if (isPlainObject2(reducer)) {\n rootReducer = combineReducers(reducer);\n } else {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : \"`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers\");\n }\n if (!IS_PRODUCTION && middleware && typeof middleware !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : \"`middleware` field must be a callback\");\n }\n let finalMiddleware;\n if (typeof middleware === \"function\") {\n finalMiddleware = middleware(getDefaultMiddleware);\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : \"when using a middleware builder function, an array of middleware must be returned\");\n }\n } else {\n finalMiddleware = getDefaultMiddleware();\n }\n if (!IS_PRODUCTION && finalMiddleware.some((item) => typeof item !== \"function\")) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : \"each middleware provided to configureStore must be a function\");\n }\n let finalCompose = compose2;\n if (devTools) {\n finalCompose = composeWithDevTools({\n // Enable capture of stack traces for dispatched Redux actions\n trace: !IS_PRODUCTION,\n ...typeof devTools === \"object\" && devTools\n });\n }\n const middlewareEnhancer = applyMiddleware(...finalMiddleware);\n const getDefaultEnhancers = buildGetDefaultEnhancers(middlewareEnhancer);\n if (!IS_PRODUCTION && enhancers && typeof enhancers !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : \"`enhancers` field must be a callback\");\n }\n let storeEnhancers = typeof enhancers === \"function\" ? enhancers(getDefaultEnhancers) : getDefaultEnhancers();\n if (!IS_PRODUCTION && !Array.isArray(storeEnhancers)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : \"`enhancers` callback must return an array\");\n }\n if (!IS_PRODUCTION && storeEnhancers.some((item) => typeof item !== \"function\")) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : \"each enhancer provided to configureStore must be a function\");\n }\n if (!IS_PRODUCTION && finalMiddleware.length && !storeEnhancers.includes(middlewareEnhancer)) {\n console.error(\"middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`\");\n }\n const composedEnhancer = finalCompose(...storeEnhancers);\n return createStore(rootReducer, preloadedState, composedEnhancer);\n}\n\n// src/createReducer.ts\nimport { produce as createNextState2, isDraft as isDraft2, isDraftable as isDraftable2 } from \"immer\";\n\n// src/mapBuilders.ts\nfunction executeReducerBuilderCallback(builderCallback) {\n const actionsMap = {};\n const actionMatchers = [];\n let defaultCaseReducer;\n const builder = {\n addCase(typeOrActionCreator, reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (actionMatchers.length > 0) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(26) : \"`builder.addCase` should only be called before calling `builder.addMatcher`\");\n }\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(27) : \"`builder.addCase` should only be called before calling `builder.addDefaultCase`\");\n }\n }\n const type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\n if (!type) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(28) : \"`builder.addCase` cannot be called with an empty action type\");\n }\n if (type in actionsMap) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(29) : `\\`builder.addCase\\` cannot be called with two reducers for the same action type '${type}'`);\n }\n actionsMap[type] = reducer;\n return builder;\n },\n addMatcher(matcher, reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(30) : \"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\");\n }\n }\n actionMatchers.push({\n matcher,\n reducer\n });\n return builder;\n },\n addDefaultCase(reducer) {\n if (process.env.NODE_ENV !== \"production\") {\n if (defaultCaseReducer) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(31) : \"`builder.addDefaultCase` can only be called once\");\n }\n }\n defaultCaseReducer = reducer;\n return builder;\n }\n };\n builderCallback(builder);\n return [actionsMap, actionMatchers, defaultCaseReducer];\n}\n\n// src/createReducer.ts\nfunction isStateFunction(x) {\n return typeof x === \"function\";\n}\nfunction createReducer(initialState, mapOrBuilderCallback) {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof mapOrBuilderCallback === \"object\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\");\n }\n }\n let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] = executeReducerBuilderCallback(mapOrBuilderCallback);\n let getInitialState;\n if (isStateFunction(initialState)) {\n getInitialState = () => freezeDraftable(initialState());\n } else {\n const frozenInitialState = freezeDraftable(initialState);\n getInitialState = () => frozenInitialState;\n }\n function reducer(state = getInitialState(), action) {\n let caseReducers = [actionsMap[action.type], ...finalActionMatchers.filter(({\n matcher\n }) => matcher(action)).map(({\n reducer: reducer2\n }) => reducer2)];\n if (caseReducers.filter((cr) => !!cr).length === 0) {\n caseReducers = [finalDefaultCaseReducer];\n }\n return caseReducers.reduce((previousState, caseReducer) => {\n if (caseReducer) {\n if (isDraft2(previousState)) {\n const draft = previousState;\n const result = caseReducer(draft, action);\n if (result === void 0) {\n return previousState;\n }\n return result;\n } else if (!isDraftable2(previousState)) {\n const result = caseReducer(previousState, action);\n if (result === void 0) {\n if (previousState === null) {\n return previousState;\n }\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : \"A case reducer on a non-draftable value must not return undefined\");\n }\n return result;\n } else {\n return createNextState2(previousState, (draft) => {\n return caseReducer(draft, action);\n });\n }\n }\n return previousState;\n }, state);\n }\n reducer.getInitialState = getInitialState;\n return reducer;\n}\n\n// src/nanoid.ts\nvar urlAlphabet = \"ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW\";\nvar nanoid = (size = 21) => {\n let id = \"\";\n let i = size;\n while (i--) {\n id += urlAlphabet[Math.random() * 64 | 0];\n }\n return id;\n};\n\n// src/matchers.ts\nvar matches = (matcher, action) => {\n if (hasMatchFunction(matcher)) {\n return matcher.match(action);\n } else {\n return matcher(action);\n }\n};\nfunction isAnyOf(...matchers) {\n return (action) => {\n return matchers.some((matcher) => matches(matcher, action));\n };\n}\nfunction isAllOf(...matchers) {\n return (action) => {\n return matchers.every((matcher) => matches(matcher, action));\n };\n}\nfunction hasExpectedRequestMetadata(action, validStatus) {\n if (!action || !action.meta)\n return false;\n const hasValidRequestId = typeof action.meta.requestId === \"string\";\n const hasValidRequestStatus = validStatus.indexOf(action.meta.requestStatus) > -1;\n return hasValidRequestId && hasValidRequestStatus;\n}\nfunction isAsyncThunkArray(a) {\n return typeof a[0] === \"function\" && \"pending\" in a[0] && \"fulfilled\" in a[0] && \"rejected\" in a[0];\n}\nfunction isPending(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"pending\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isPending()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending));\n}\nfunction isRejected(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"rejected\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isRejected()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected));\n}\nfunction isRejectedWithValue(...asyncThunks) {\n const hasFlag = (action) => {\n return action && action.meta && action.meta.rejectedWithValue;\n };\n if (asyncThunks.length === 0) {\n return isAllOf(isRejected(...asyncThunks), hasFlag);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isRejectedWithValue()(asyncThunks[0]);\n }\n return isAllOf(isRejected(...asyncThunks), hasFlag);\n}\nfunction isFulfilled(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"fulfilled\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isFulfilled()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled));\n}\nfunction isAsyncThunkAction(...asyncThunks) {\n if (asyncThunks.length === 0) {\n return (action) => hasExpectedRequestMetadata(action, [\"pending\", \"fulfilled\", \"rejected\"]);\n }\n if (!isAsyncThunkArray(asyncThunks)) {\n return isAsyncThunkAction()(asyncThunks[0]);\n }\n return isAnyOf(...asyncThunks.flatMap((asyncThunk) => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]));\n}\n\n// src/createAsyncThunk.ts\nvar commonProperties = [\"name\", \"message\", \"stack\", \"code\"];\nvar RejectWithValue = class {\n constructor(payload, meta) {\n this.payload = payload;\n this.meta = meta;\n }\n /*\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\n does not exist at runtime\n */\n _type;\n};\nvar FulfillWithMeta = class {\n constructor(payload, meta) {\n this.payload = payload;\n this.meta = meta;\n }\n /*\n type-only property to distinguish between RejectWithValue and FulfillWithMeta\n does not exist at runtime\n */\n _type;\n};\nvar miniSerializeError = (value) => {\n if (typeof value === \"object\" && value !== null) {\n const simpleError = {};\n for (const property of commonProperties) {\n if (typeof value[property] === \"string\") {\n simpleError[property] = value[property];\n }\n }\n return simpleError;\n }\n return {\n message: String(value)\n };\n};\nvar createAsyncThunk = /* @__PURE__ */ (() => {\n function createAsyncThunk2(typePrefix, payloadCreator, options) {\n const fulfilled = createAction(typePrefix + \"/fulfilled\", (payload, requestId, arg, meta) => ({\n payload,\n meta: {\n ...meta || {},\n arg,\n requestId,\n requestStatus: \"fulfilled\"\n }\n }));\n const pending = createAction(typePrefix + \"/pending\", (requestId, arg, meta) => ({\n payload: void 0,\n meta: {\n ...meta || {},\n arg,\n requestId,\n requestStatus: \"pending\"\n }\n }));\n const rejected = createAction(typePrefix + \"/rejected\", (error, requestId, arg, payload, meta) => ({\n payload,\n error: (options && options.serializeError || miniSerializeError)(error || \"Rejected\"),\n meta: {\n ...meta || {},\n arg,\n requestId,\n rejectedWithValue: !!payload,\n requestStatus: \"rejected\",\n aborted: error?.name === \"AbortError\",\n condition: error?.name === \"ConditionError\"\n }\n }));\n function actionCreator(arg) {\n return (dispatch, getState, extra) => {\n const requestId = options?.idGenerator ? options.idGenerator(arg) : nanoid();\n const abortController = new AbortController();\n let abortHandler;\n let abortReason;\n function abort(reason) {\n abortReason = reason;\n abortController.abort();\n }\n const promise = async function() {\n let finalAction;\n try {\n let conditionResult = options?.condition?.(arg, {\n getState,\n extra\n });\n if (isThenable(conditionResult)) {\n conditionResult = await conditionResult;\n }\n if (conditionResult === false || abortController.signal.aborted) {\n throw {\n name: \"ConditionError\",\n message: \"Aborted due to condition callback returning false.\"\n };\n }\n const abortedPromise = new Promise((_, reject) => {\n abortHandler = () => {\n reject({\n name: \"AbortError\",\n message: abortReason || \"Aborted\"\n });\n };\n abortController.signal.addEventListener(\"abort\", abortHandler);\n });\n dispatch(pending(requestId, arg, options?.getPendingMeta?.({\n requestId,\n arg\n }, {\n getState,\n extra\n })));\n finalAction = await Promise.race([abortedPromise, Promise.resolve(payloadCreator(arg, {\n dispatch,\n getState,\n extra,\n requestId,\n signal: abortController.signal,\n abort,\n rejectWithValue: (value, meta) => {\n return new RejectWithValue(value, meta);\n },\n fulfillWithValue: (value, meta) => {\n return new FulfillWithMeta(value, meta);\n }\n })).then((result) => {\n if (result instanceof RejectWithValue) {\n throw result;\n }\n if (result instanceof FulfillWithMeta) {\n return fulfilled(result.payload, requestId, arg, result.meta);\n }\n return fulfilled(result, requestId, arg);\n })]);\n } catch (err) {\n finalAction = err instanceof RejectWithValue ? rejected(null, requestId, arg, err.payload, err.meta) : rejected(err, requestId, arg);\n } finally {\n if (abortHandler) {\n abortController.signal.removeEventListener(\"abort\", abortHandler);\n }\n }\n const skipDispatch = options && !options.dispatchConditionRejection && rejected.match(finalAction) && finalAction.meta.condition;\n if (!skipDispatch) {\n dispatch(finalAction);\n }\n return finalAction;\n }();\n return Object.assign(promise, {\n abort,\n requestId,\n arg,\n unwrap() {\n return promise.then(unwrapResult);\n }\n });\n };\n }\n return Object.assign(actionCreator, {\n pending,\n rejected,\n fulfilled,\n settled: isAnyOf(rejected, fulfilled),\n typePrefix\n });\n }\n createAsyncThunk2.withTypes = () => createAsyncThunk2;\n return createAsyncThunk2;\n})();\nfunction unwrapResult(action) {\n if (action.meta && action.meta.rejectedWithValue) {\n throw action.payload;\n }\n if (action.error) {\n throw action.error;\n }\n return action.payload;\n}\nfunction isThenable(value) {\n return value !== null && typeof value === \"object\" && typeof value.then === \"function\";\n}\n\n// src/createSlice.ts\nvar asyncThunkSymbol = /* @__PURE__ */ Symbol.for(\"rtk-slice-createasyncthunk\");\nvar asyncThunkCreator = {\n [asyncThunkSymbol]: createAsyncThunk\n};\nvar ReducerType = /* @__PURE__ */ ((ReducerType2) => {\n ReducerType2[\"reducer\"] = \"reducer\";\n ReducerType2[\"reducerWithPrepare\"] = \"reducerWithPrepare\";\n ReducerType2[\"asyncThunk\"] = \"asyncThunk\";\n return ReducerType2;\n})(ReducerType || {});\nfunction getType(slice, actionKey) {\n return `${slice}/${actionKey}`;\n}\nfunction buildCreateSlice({\n creators\n} = {}) {\n const cAT = creators?.asyncThunk?.[asyncThunkSymbol];\n return function createSlice2(options) {\n const {\n name,\n reducerPath = name\n } = options;\n if (!name) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : \"`name` is a required option for createSlice\");\n }\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\n if (options.initialState === void 0) {\n console.error(\"You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`\");\n }\n }\n const reducers = (typeof options.reducers === \"function\" ? options.reducers(buildReducerCreators()) : options.reducers) || {};\n const reducerNames = Object.keys(reducers);\n const context = {\n sliceCaseReducersByName: {},\n sliceCaseReducersByType: {},\n actionCreators: {},\n sliceMatchers: []\n };\n const contextMethods = {\n addCase(typeOrActionCreator, reducer2) {\n const type = typeof typeOrActionCreator === \"string\" ? typeOrActionCreator : typeOrActionCreator.type;\n if (!type) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : \"`context.addCase` cannot be called with an empty action type\");\n }\n if (type in context.sliceCaseReducersByType) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : \"`context.addCase` cannot be called with two reducers for the same action type: \" + type);\n }\n context.sliceCaseReducersByType[type] = reducer2;\n return contextMethods;\n },\n addMatcher(matcher, reducer2) {\n context.sliceMatchers.push({\n matcher,\n reducer: reducer2\n });\n return contextMethods;\n },\n exposeAction(name2, actionCreator) {\n context.actionCreators[name2] = actionCreator;\n return contextMethods;\n },\n exposeCaseReducer(name2, reducer2) {\n context.sliceCaseReducersByName[name2] = reducer2;\n return contextMethods;\n }\n };\n reducerNames.forEach((reducerName) => {\n const reducerDefinition = reducers[reducerName];\n const reducerDetails = {\n reducerName,\n type: getType(name, reducerName),\n createNotation: typeof options.reducers === \"function\"\n };\n if (isAsyncThunkSliceReducerDefinition(reducerDefinition)) {\n handleThunkCaseReducerDefinition(reducerDetails, reducerDefinition, contextMethods, cAT);\n } else {\n handleNormalReducerDefinition(reducerDetails, reducerDefinition, contextMethods);\n }\n });\n function buildReducer() {\n if (process.env.NODE_ENV !== \"production\") {\n if (typeof options.extraReducers === \"object\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\");\n }\n }\n const [extraReducers = {}, actionMatchers = [], defaultCaseReducer = void 0] = typeof options.extraReducers === \"function\" ? executeReducerBuilderCallback(options.extraReducers) : [options.extraReducers];\n const finalCaseReducers = {\n ...extraReducers,\n ...context.sliceCaseReducersByType\n };\n return createReducer(options.initialState, (builder) => {\n for (let key in finalCaseReducers) {\n builder.addCase(key, finalCaseReducers[key]);\n }\n for (let sM of context.sliceMatchers) {\n builder.addMatcher(sM.matcher, sM.reducer);\n }\n for (let m of actionMatchers) {\n builder.addMatcher(m.matcher, m.reducer);\n }\n if (defaultCaseReducer) {\n builder.addDefaultCase(defaultCaseReducer);\n }\n });\n }\n const selectSelf = (state) => state;\n const injectedSelectorCache = /* @__PURE__ */ new Map();\n let _reducer;\n function reducer(state, action) {\n if (!_reducer)\n _reducer = buildReducer();\n return _reducer(state, action);\n }\n function getInitialState() {\n if (!_reducer)\n _reducer = buildReducer();\n return _reducer.getInitialState();\n }\n function makeSelectorProps(reducerPath2, injected = false) {\n function selectSlice(state) {\n let sliceState = state[reducerPath2];\n if (typeof sliceState === \"undefined\") {\n if (injected) {\n sliceState = getInitialState();\n } else if (process.env.NODE_ENV !== \"production\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : \"selectSlice returned undefined for an uninjected slice reducer\");\n }\n }\n return sliceState;\n }\n function getSelectors(selectState = selectSelf) {\n const selectorCache = emplace(injectedSelectorCache, injected, {\n insert: () => /* @__PURE__ */ new WeakMap()\n });\n return emplace(selectorCache, selectState, {\n insert: () => {\n const map = {};\n for (const [name2, selector] of Object.entries(options.selectors ?? {})) {\n map[name2] = wrapSelector(selector, selectState, getInitialState, injected);\n }\n return map;\n }\n });\n }\n return {\n reducerPath: reducerPath2,\n getSelectors,\n get selectors() {\n return getSelectors(selectSlice);\n },\n selectSlice\n };\n }\n const slice = {\n name,\n reducer,\n actions: context.actionCreators,\n caseReducers: context.sliceCaseReducersByName,\n getInitialState,\n ...makeSelectorProps(reducerPath),\n injectInto(injectable, {\n reducerPath: pathOpt,\n ...config\n } = {}) {\n const newReducerPath = pathOpt ?? reducerPath;\n injectable.inject({\n reducerPath: newReducerPath,\n reducer\n }, config);\n return {\n ...slice,\n ...makeSelectorProps(newReducerPath, true)\n };\n }\n };\n return slice;\n };\n}\nfunction wrapSelector(selector, selectState, getInitialState, injected) {\n function wrapper(rootState, ...args) {\n let sliceState = selectState(rootState);\n if (typeof sliceState === \"undefined\") {\n if (injected) {\n sliceState = getInitialState();\n } else if (process.env.NODE_ENV !== \"production\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : \"selectState returned undefined for an uninjected slice reducer\");\n }\n }\n return selector(sliceState, ...args);\n }\n wrapper.unwrapped = selector;\n return wrapper;\n}\nvar createSlice = /* @__PURE__ */ buildCreateSlice();\nfunction buildReducerCreators() {\n function asyncThunk(payloadCreator, config) {\n return {\n _reducerDefinitionType: \"asyncThunk\" /* asyncThunk */,\n payloadCreator,\n ...config\n };\n }\n asyncThunk.withTypes = () => asyncThunk;\n return {\n reducer(caseReducer) {\n return Object.assign({\n // hack so the wrapping function has the same name as the original\n // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n [caseReducer.name](...args) {\n return caseReducer(...args);\n }\n }[caseReducer.name], {\n _reducerDefinitionType: \"reducer\" /* reducer */\n });\n },\n preparedReducer(prepare, reducer) {\n return {\n _reducerDefinitionType: \"reducerWithPrepare\" /* reducerWithPrepare */,\n prepare,\n reducer\n };\n },\n asyncThunk\n };\n}\nfunction handleNormalReducerDefinition({\n type,\n reducerName,\n createNotation\n}, maybeReducerWithPrepare, context) {\n let caseReducer;\n let prepareCallback;\n if (\"reducer\" in maybeReducerWithPrepare) {\n if (createNotation && !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(17) : \"Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.\");\n }\n caseReducer = maybeReducerWithPrepare.reducer;\n prepareCallback = maybeReducerWithPrepare.prepare;\n } else {\n caseReducer = maybeReducerWithPrepare;\n }\n context.addCase(type, caseReducer).exposeCaseReducer(reducerName, caseReducer).exposeAction(reducerName, prepareCallback ? createAction(type, prepareCallback) : createAction(type));\n}\nfunction isAsyncThunkSliceReducerDefinition(reducerDefinition) {\n return reducerDefinition._reducerDefinitionType === \"asyncThunk\" /* asyncThunk */;\n}\nfunction isCaseReducerWithPrepareDefinition(reducerDefinition) {\n return reducerDefinition._reducerDefinitionType === \"reducerWithPrepare\" /* reducerWithPrepare */;\n}\nfunction handleThunkCaseReducerDefinition({\n type,\n reducerName\n}, reducerDefinition, context, cAT) {\n if (!cAT) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(18) : \"Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.\");\n }\n const {\n payloadCreator,\n fulfilled,\n pending,\n rejected,\n settled,\n options\n } = reducerDefinition;\n const thunk = cAT(type, payloadCreator, options);\n context.exposeAction(reducerName, thunk);\n if (fulfilled) {\n context.addCase(thunk.fulfilled, fulfilled);\n }\n if (pending) {\n context.addCase(thunk.pending, pending);\n }\n if (rejected) {\n context.addCase(thunk.rejected, rejected);\n }\n if (settled) {\n context.addMatcher(thunk.settled, settled);\n }\n context.exposeCaseReducer(reducerName, {\n fulfilled: fulfilled || noop,\n pending: pending || noop,\n rejected: rejected || noop,\n settled: settled || noop\n });\n}\nfunction noop() {\n}\n\n// src/entities/entity_state.ts\nfunction getInitialEntityState() {\n return {\n ids: [],\n entities: {}\n };\n}\nfunction createInitialStateFactory(stateAdapter) {\n function getInitialState(additionalState = {}, entities) {\n const state = Object.assign(getInitialEntityState(), additionalState);\n return entities ? stateAdapter.setAll(state, entities) : state;\n }\n return {\n getInitialState\n };\n}\n\n// src/entities/state_selectors.ts\nfunction createSelectorsFactory() {\n function getSelectors(selectState, options = {}) {\n const {\n createSelector: createSelector2 = createDraftSafeSelector\n } = options;\n const selectIds = (state) => state.ids;\n const selectEntities = (state) => state.entities;\n const selectAll = createSelector2(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));\n const selectId = (_, id) => id;\n const selectById = (entities, id) => entities[id];\n const selectTotal = createSelector2(selectIds, (ids) => ids.length);\n if (!selectState) {\n return {\n selectIds,\n selectEntities,\n selectAll,\n selectTotal,\n selectById: createSelector2(selectEntities, selectId, selectById)\n };\n }\n const selectGlobalizedEntities = createSelector2(selectState, selectEntities);\n return {\n selectIds: createSelector2(selectState, selectIds),\n selectEntities: selectGlobalizedEntities,\n selectAll: createSelector2(selectState, selectAll),\n selectTotal: createSelector2(selectState, selectTotal),\n selectById: createSelector2(selectGlobalizedEntities, selectId, selectById)\n };\n }\n return {\n getSelectors\n };\n}\n\n// src/entities/state_adapter.ts\nimport { produce as createNextState3, isDraft as isDraft3 } from \"immer\";\nvar isDraftTyped = isDraft3;\nfunction createSingleArgumentStateOperator(mutator) {\n const operator = createStateOperator((_, state) => mutator(state));\n return function operation(state) {\n return operator(state, void 0);\n };\n}\nfunction createStateOperator(mutator) {\n return function operation(state, arg) {\n function isPayloadActionArgument(arg2) {\n return isFSA(arg2);\n }\n const runMutator = (draft) => {\n if (isPayloadActionArgument(arg)) {\n mutator(arg.payload, draft);\n } else {\n mutator(arg, draft);\n }\n };\n if (isDraftTyped(state)) {\n runMutator(state);\n return state;\n }\n return createNextState3(state, runMutator);\n };\n}\n\n// src/entities/utils.ts\nimport { current as current2, isDraft as isDraft4 } from \"immer\";\nfunction selectIdValue(entity, selectId) {\n const key = selectId(entity);\n if (process.env.NODE_ENV !== \"production\" && key === void 0) {\n console.warn(\"The entity passed to the `selectId` implementation returned undefined.\", \"You should probably provide your own `selectId` implementation.\", \"The entity that was passed:\", entity, \"The `selectId` implementation:\", selectId.toString());\n }\n return key;\n}\nfunction ensureEntitiesArray(entities) {\n if (!Array.isArray(entities)) {\n entities = Object.values(entities);\n }\n return entities;\n}\nfunction getCurrent(value) {\n return isDraft4(value) ? current2(value) : value;\n}\nfunction splitAddedUpdatedEntities(newEntities, selectId, state) {\n newEntities = ensureEntitiesArray(newEntities);\n const existingIdsArray = getCurrent(state.ids);\n const existingIds = new Set(existingIdsArray);\n const added = [];\n const updated = [];\n for (const entity of newEntities) {\n const id = selectIdValue(entity, selectId);\n if (existingIds.has(id)) {\n updated.push({\n id,\n changes: entity\n });\n } else {\n added.push(entity);\n }\n }\n return [added, updated, existingIdsArray];\n}\n\n// src/entities/unsorted_state_adapter.ts\nfunction createUnsortedStateAdapter(selectId) {\n function addOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (key in state.entities) {\n return;\n }\n state.ids.push(key);\n state.entities[key] = entity;\n }\n function addManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n for (const entity of newEntities) {\n addOneMutably(entity, state);\n }\n }\n function setOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (!(key in state.entities)) {\n state.ids.push(key);\n }\n ;\n state.entities[key] = entity;\n }\n function setManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n for (const entity of newEntities) {\n setOneMutably(entity, state);\n }\n }\n function setAllMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n state.ids = [];\n state.entities = {};\n addManyMutably(newEntities, state);\n }\n function removeOneMutably(key, state) {\n return removeManyMutably([key], state);\n }\n function removeManyMutably(keys, state) {\n let didMutate = false;\n keys.forEach((key) => {\n if (key in state.entities) {\n delete state.entities[key];\n didMutate = true;\n }\n });\n if (didMutate) {\n state.ids = state.ids.filter((id) => id in state.entities);\n }\n }\n function removeAllMutably(state) {\n Object.assign(state, {\n ids: [],\n entities: {}\n });\n }\n function takeNewKey(keys, update, state) {\n const original3 = state.entities[update.id];\n if (original3 === void 0) {\n return false;\n }\n const updated = Object.assign({}, original3, update.changes);\n const newKey = selectIdValue(updated, selectId);\n const hasNewKey = newKey !== update.id;\n if (hasNewKey) {\n keys[update.id] = newKey;\n delete state.entities[update.id];\n }\n ;\n state.entities[newKey] = updated;\n return hasNewKey;\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function updateManyMutably(updates, state) {\n const newKeys = {};\n const updatesPerEntity = {};\n updates.forEach((update) => {\n if (update.id in state.entities) {\n updatesPerEntity[update.id] = {\n id: update.id,\n // Spreads ignore falsy values, so this works even if there isn't\n // an existing update already at this key\n changes: {\n ...updatesPerEntity[update.id]?.changes,\n ...update.changes\n }\n };\n }\n });\n updates = Object.values(updatesPerEntity);\n const didMutateEntities = updates.length > 0;\n if (didMutateEntities) {\n const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length > 0;\n if (didMutateIds) {\n state.ids = Object.values(state.entities).map((e) => selectIdValue(e, selectId));\n }\n }\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(newEntities, state) {\n const [added, updated] = splitAddedUpdatedEntities(newEntities, selectId, state);\n updateManyMutably(updated, state);\n addManyMutably(added, state);\n }\n return {\n removeAll: createSingleArgumentStateOperator(removeAllMutably),\n addOne: createStateOperator(addOneMutably),\n addMany: createStateOperator(addManyMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n setAll: createStateOperator(setAllMutably),\n updateOne: createStateOperator(updateOneMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n upsertMany: createStateOperator(upsertManyMutably),\n removeOne: createStateOperator(removeOneMutably),\n removeMany: createStateOperator(removeManyMutably)\n };\n}\n\n// src/entities/sorted_state_adapter.ts\nfunction findInsertIndex(sortedItems, item, comparisonFunction) {\n let lowIndex = 0;\n let highIndex = sortedItems.length;\n while (lowIndex < highIndex) {\n let middleIndex = lowIndex + highIndex >>> 1;\n const currentItem = sortedItems[middleIndex];\n const res = comparisonFunction(item, currentItem);\n if (res >= 0) {\n lowIndex = middleIndex + 1;\n } else {\n highIndex = middleIndex;\n }\n }\n return lowIndex;\n}\nfunction insert(sortedItems, item, comparisonFunction) {\n const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction);\n sortedItems.splice(insertAtIndex, 0, item);\n return sortedItems;\n}\nfunction createSortedStateAdapter(selectId, comparer) {\n const {\n removeOne,\n removeMany,\n removeAll\n } = createUnsortedStateAdapter(selectId);\n function addOneMutably(entity, state) {\n return addManyMutably([entity], state);\n }\n function addManyMutably(newEntities, state, existingIds) {\n newEntities = ensureEntitiesArray(newEntities);\n const existingKeys = new Set(existingIds ?? getCurrent(state.ids));\n const models = newEntities.filter((model) => !existingKeys.has(selectIdValue(model, selectId)));\n if (models.length !== 0) {\n mergeFunction(state, models);\n }\n }\n function setOneMutably(entity, state) {\n return setManyMutably([entity], state);\n }\n function setManyMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n if (newEntities.length !== 0) {\n for (const item of newEntities) {\n delete state.entities[selectId(item)];\n }\n mergeFunction(state, newEntities);\n }\n }\n function setAllMutably(newEntities, state) {\n newEntities = ensureEntitiesArray(newEntities);\n state.entities = {};\n state.ids = [];\n addManyMutably(newEntities, state, []);\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function updateManyMutably(updates, state) {\n let appliedUpdates = false;\n let replacedIds = false;\n for (let update of updates) {\n const entity = state.entities[update.id];\n if (!entity) {\n continue;\n }\n appliedUpdates = true;\n Object.assign(entity, update.changes);\n const newId = selectId(entity);\n if (update.id !== newId) {\n replacedIds = true;\n delete state.entities[update.id];\n const oldIndex = state.ids.indexOf(update.id);\n state.ids[oldIndex] = newId;\n state.entities[newId] = entity;\n }\n }\n if (appliedUpdates) {\n mergeFunction(state, [], appliedUpdates, replacedIds);\n }\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(newEntities, state) {\n const [added, updated, existingIdsArray] = splitAddedUpdatedEntities(newEntities, selectId, state);\n if (updated.length) {\n updateManyMutably(updated, state);\n }\n if (added.length) {\n addManyMutably(added, state, existingIdsArray);\n }\n }\n function areArraysEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] === b[i]) {\n continue;\n }\n return false;\n }\n return true;\n }\n const mergeFunction = (state, addedItems, appliedUpdates, replacedIds) => {\n const currentEntities = getCurrent(state.entities);\n const currentIds = getCurrent(state.ids);\n const stateEntities = state.entities;\n let ids = currentIds;\n if (replacedIds) {\n ids = new Set(currentIds);\n }\n let sortedEntities = [];\n for (const id of ids) {\n const entity = currentEntities[id];\n if (entity) {\n sortedEntities.push(entity);\n }\n }\n const wasPreviouslyEmpty = sortedEntities.length === 0;\n for (const item of addedItems) {\n stateEntities[selectId(item)] = item;\n if (!wasPreviouslyEmpty) {\n insert(sortedEntities, item, comparer);\n }\n }\n if (wasPreviouslyEmpty) {\n sortedEntities = addedItems.slice().sort(comparer);\n } else if (appliedUpdates) {\n sortedEntities.sort(comparer);\n }\n const newSortedIds = sortedEntities.map(selectId);\n if (!areArraysEqual(currentIds, newSortedIds)) {\n state.ids = newSortedIds;\n }\n };\n return {\n removeOne,\n removeMany,\n removeAll,\n addOne: createStateOperator(addOneMutably),\n updateOne: createStateOperator(updateOneMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n setAll: createStateOperator(setAllMutably),\n addMany: createStateOperator(addManyMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertMany: createStateOperator(upsertManyMutably)\n };\n}\n\n// src/entities/create_adapter.ts\nfunction createEntityAdapter(options = {}) {\n const {\n selectId,\n sortComparer\n } = {\n sortComparer: false,\n selectId: (instance) => instance.id,\n ...options\n };\n const stateAdapter = sortComparer ? createSortedStateAdapter(selectId, sortComparer) : createUnsortedStateAdapter(selectId);\n const stateFactory = createInitialStateFactory(stateAdapter);\n const selectorsFactory = createSelectorsFactory();\n return {\n selectId,\n sortComparer,\n ...stateFactory,\n ...selectorsFactory,\n ...stateAdapter\n };\n}\n\n// src/listenerMiddleware/index.ts\nimport { isAction as isAction3 } from \"redux\";\n\n// src/listenerMiddleware/exceptions.ts\nvar task = \"task\";\nvar listener = \"listener\";\nvar completed = \"completed\";\nvar cancelled = \"cancelled\";\nvar taskCancelled = `task-${cancelled}`;\nvar taskCompleted = `task-${completed}`;\nvar listenerCancelled = `${listener}-${cancelled}`;\nvar listenerCompleted = `${listener}-${completed}`;\nvar TaskAbortError = class {\n constructor(code) {\n this.code = code;\n this.message = `${task} ${cancelled} (reason: ${code})`;\n }\n name = \"TaskAbortError\";\n message;\n};\n\n// src/listenerMiddleware/utils.ts\nvar assertFunction = (func, expected) => {\n if (typeof func !== \"function\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(32) : `${expected} is not a function`);\n }\n};\nvar noop2 = () => {\n};\nvar catchRejection = (promise, onError = noop2) => {\n promise.catch(onError);\n return promise;\n};\nvar addAbortSignalListener = (abortSignal, callback) => {\n abortSignal.addEventListener(\"abort\", callback, {\n once: true\n });\n return () => abortSignal.removeEventListener(\"abort\", callback);\n};\nvar abortControllerWithReason = (abortController, reason) => {\n const signal = abortController.signal;\n if (signal.aborted) {\n return;\n }\n if (!(\"reason\" in signal)) {\n Object.defineProperty(signal, \"reason\", {\n enumerable: true,\n value: reason,\n configurable: true,\n writable: true\n });\n }\n ;\n abortController.abort(reason);\n};\n\n// src/listenerMiddleware/task.ts\nvar validateActive = (signal) => {\n if (signal.aborted) {\n const {\n reason\n } = signal;\n throw new TaskAbortError(reason);\n }\n};\nfunction raceWithSignal(signal, promise) {\n let cleanup = noop2;\n return new Promise((resolve, reject) => {\n const notifyRejection = () => reject(new TaskAbortError(signal.reason));\n if (signal.aborted) {\n notifyRejection();\n return;\n }\n cleanup = addAbortSignalListener(signal, notifyRejection);\n promise.finally(() => cleanup()).then(resolve, reject);\n }).finally(() => {\n cleanup = noop2;\n });\n}\nvar runTask = async (task2, cleanUp) => {\n try {\n await Promise.resolve();\n const value = await task2();\n return {\n status: \"ok\",\n value\n };\n } catch (error) {\n return {\n status: error instanceof TaskAbortError ? \"cancelled\" : \"rejected\",\n error\n };\n } finally {\n cleanUp?.();\n }\n};\nvar createPause = (signal) => {\n return (promise) => {\n return catchRejection(raceWithSignal(signal, promise).then((output) => {\n validateActive(signal);\n return output;\n }));\n };\n};\nvar createDelay = (signal) => {\n const pause = createPause(signal);\n return (timeoutMs) => {\n return pause(new Promise((resolve) => setTimeout(resolve, timeoutMs)));\n };\n};\n\n// src/listenerMiddleware/index.ts\nvar {\n assign\n} = Object;\nvar INTERNAL_NIL_TOKEN = {};\nvar alm = \"listenerMiddleware\";\nvar createFork = (parentAbortSignal, parentBlockingPromises) => {\n const linkControllers = (controller) => addAbortSignalListener(parentAbortSignal, () => abortControllerWithReason(controller, parentAbortSignal.reason));\n return (taskExecutor, opts) => {\n assertFunction(taskExecutor, \"taskExecutor\");\n const childAbortController = new AbortController();\n linkControllers(childAbortController);\n const result = runTask(async () => {\n validateActive(parentAbortSignal);\n validateActive(childAbortController.signal);\n const result2 = await taskExecutor({\n pause: createPause(childAbortController.signal),\n delay: createDelay(childAbortController.signal),\n signal: childAbortController.signal\n });\n validateActive(childAbortController.signal);\n return result2;\n }, () => abortControllerWithReason(childAbortController, taskCompleted));\n if (opts?.autoJoin) {\n parentBlockingPromises.push(result.catch(noop2));\n }\n return {\n result: createPause(parentAbortSignal)(result),\n cancel() {\n abortControllerWithReason(childAbortController, taskCancelled);\n }\n };\n };\n};\nvar createTakePattern = (startListening, signal) => {\n const take = async (predicate, timeout) => {\n validateActive(signal);\n let unsubscribe = () => {\n };\n const tuplePromise = new Promise((resolve, reject) => {\n let stopListening = startListening({\n predicate,\n effect: (action, listenerApi) => {\n listenerApi.unsubscribe();\n resolve([action, listenerApi.getState(), listenerApi.getOriginalState()]);\n }\n });\n unsubscribe = () => {\n stopListening();\n reject();\n };\n });\n const promises = [tuplePromise];\n if (timeout != null) {\n promises.push(new Promise((resolve) => setTimeout(resolve, timeout, null)));\n }\n try {\n const output = await raceWithSignal(signal, Promise.race(promises));\n validateActive(signal);\n return output;\n } finally {\n unsubscribe();\n }\n };\n return (predicate, timeout) => catchRejection(take(predicate, timeout));\n};\nvar getListenerEntryPropsFrom = (options) => {\n let {\n type,\n actionCreator,\n matcher,\n predicate,\n effect\n } = options;\n if (type) {\n predicate = createAction(type).match;\n } else if (actionCreator) {\n type = actionCreator.type;\n predicate = actionCreator.match;\n } else if (matcher) {\n predicate = matcher;\n } else if (predicate) {\n } else {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(21) : \"Creating or removing a listener requires one of the known fields for matching an action\");\n }\n assertFunction(effect, \"options.listener\");\n return {\n predicate,\n type,\n effect\n };\n};\nvar createListenerEntry = Object.assign((options) => {\n const {\n type,\n predicate,\n effect\n } = getListenerEntryPropsFrom(options);\n const id = nanoid();\n const entry = {\n id,\n effect,\n type,\n predicate,\n pending: /* @__PURE__ */ new Set(),\n unsubscribe: () => {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(22) : \"Unsubscribe not initialized\");\n }\n };\n return entry;\n}, {\n withTypes: () => createListenerEntry\n});\nvar cancelActiveListeners = (entry) => {\n entry.pending.forEach((controller) => {\n abortControllerWithReason(controller, listenerCancelled);\n });\n};\nvar createClearListenerMiddleware = (listenerMap) => {\n return () => {\n listenerMap.forEach(cancelActiveListeners);\n listenerMap.clear();\n };\n};\nvar safelyNotifyError = (errorHandler, errorToNotify, errorInfo) => {\n try {\n errorHandler(errorToNotify, errorInfo);\n } catch (errorHandlerError) {\n setTimeout(() => {\n throw errorHandlerError;\n }, 0);\n }\n};\nvar addListener = Object.assign(createAction(`${alm}/add`), {\n withTypes: () => addListener\n});\nvar clearAllListeners = createAction(`${alm}/removeAll`);\nvar removeListener = Object.assign(createAction(`${alm}/remove`), {\n withTypes: () => removeListener\n});\nvar defaultErrorHandler = (...args) => {\n console.error(`${alm}/error`, ...args);\n};\nvar createListenerMiddleware = (middlewareOptions = {}) => {\n const listenerMap = /* @__PURE__ */ new Map();\n const {\n extra,\n onError = defaultErrorHandler\n } = middlewareOptions;\n assertFunction(onError, \"onError\");\n const insertEntry = (entry) => {\n entry.unsubscribe = () => listenerMap.delete(entry.id);\n listenerMap.set(entry.id, entry);\n return (cancelOptions) => {\n entry.unsubscribe();\n if (cancelOptions?.cancelActive) {\n cancelActiveListeners(entry);\n }\n };\n };\n const startListening = (options) => {\n let entry = find(Array.from(listenerMap.values()), (existingEntry) => existingEntry.effect === options.effect);\n if (!entry) {\n entry = createListenerEntry(options);\n }\n return insertEntry(entry);\n };\n Object.assign(startListening, {\n withTypes: () => startListening\n });\n const stopListening = (options) => {\n const {\n type,\n effect,\n predicate\n } = getListenerEntryPropsFrom(options);\n const entry = find(Array.from(listenerMap.values()), (entry2) => {\n const matchPredicateOrType = typeof type === \"string\" ? entry2.type === type : entry2.predicate === predicate;\n return matchPredicateOrType && entry2.effect === effect;\n });\n if (entry) {\n entry.unsubscribe();\n if (options.cancelActive) {\n cancelActiveListeners(entry);\n }\n }\n return !!entry;\n };\n Object.assign(stopListening, {\n withTypes: () => stopListening\n });\n const notifyListener = async (entry, action, api, getOriginalState) => {\n const internalTaskController = new AbortController();\n const take = createTakePattern(startListening, internalTaskController.signal);\n const autoJoinPromises = [];\n try {\n entry.pending.add(internalTaskController);\n await Promise.resolve(entry.effect(\n action,\n // Use assign() rather than ... to avoid extra helper functions added to bundle\n assign({}, api, {\n getOriginalState,\n condition: (predicate, timeout) => take(predicate, timeout).then(Boolean),\n take,\n delay: createDelay(internalTaskController.signal),\n pause: createPause(internalTaskController.signal),\n extra,\n signal: internalTaskController.signal,\n fork: createFork(internalTaskController.signal, autoJoinPromises),\n unsubscribe: entry.unsubscribe,\n subscribe: () => {\n listenerMap.set(entry.id, entry);\n },\n cancelActiveListeners: () => {\n entry.pending.forEach((controller, _, set) => {\n if (controller !== internalTaskController) {\n abortControllerWithReason(controller, listenerCancelled);\n set.delete(controller);\n }\n });\n },\n cancel: () => {\n abortControllerWithReason(internalTaskController, listenerCancelled);\n entry.pending.delete(internalTaskController);\n },\n throwIfCancelled: () => {\n validateActive(internalTaskController.signal);\n }\n })\n ));\n } catch (listenerError) {\n if (!(listenerError instanceof TaskAbortError)) {\n safelyNotifyError(onError, listenerError, {\n raisedBy: \"effect\"\n });\n }\n } finally {\n await Promise.all(autoJoinPromises);\n abortControllerWithReason(internalTaskController, listenerCompleted);\n entry.pending.delete(internalTaskController);\n }\n };\n const clearListenerMiddleware = createClearListenerMiddleware(listenerMap);\n const middleware = (api) => (next) => (action) => {\n if (!isAction3(action)) {\n return next(action);\n }\n if (addListener.match(action)) {\n return startListening(action.payload);\n }\n if (clearAllListeners.match(action)) {\n clearListenerMiddleware();\n return;\n }\n if (removeListener.match(action)) {\n return stopListening(action.payload);\n }\n let originalState = api.getState();\n const getOriginalState = () => {\n if (originalState === INTERNAL_NIL_TOKEN) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(23) : `${alm}: getOriginalState can only be called synchronously`);\n }\n return originalState;\n };\n let result;\n try {\n result = next(action);\n if (listenerMap.size > 0) {\n const currentState = api.getState();\n const listenerEntries = Array.from(listenerMap.values());\n for (const entry of listenerEntries) {\n let runListener = false;\n try {\n runListener = entry.predicate(action, currentState, originalState);\n } catch (predicateError) {\n runListener = false;\n safelyNotifyError(onError, predicateError, {\n raisedBy: \"predicate\"\n });\n }\n if (!runListener) {\n continue;\n }\n notifyListener(entry, action, api, getOriginalState);\n }\n }\n } finally {\n originalState = INTERNAL_NIL_TOKEN;\n }\n return result;\n };\n return {\n middleware,\n startListening,\n stopListening,\n clearListeners: clearListenerMiddleware\n };\n};\n\n// src/dynamicMiddleware/index.ts\nimport { compose as compose3 } from \"redux\";\nvar createMiddlewareEntry = (middleware) => ({\n id: nanoid(),\n middleware,\n applied: /* @__PURE__ */ new Map()\n});\nvar matchInstance = (instanceId) => (action) => action?.meta?.instanceId === instanceId;\nvar createDynamicMiddleware = () => {\n const instanceId = nanoid();\n const middlewareMap = /* @__PURE__ */ new Map();\n const withMiddleware = Object.assign(createAction(\"dynamicMiddleware/add\", (...middlewares) => ({\n payload: middlewares,\n meta: {\n instanceId\n }\n })), {\n withTypes: () => withMiddleware\n });\n const addMiddleware = Object.assign(function addMiddleware2(...middlewares) {\n middlewares.forEach((middleware2) => {\n let entry = find(Array.from(middlewareMap.values()), (entry2) => entry2.middleware === middleware2);\n if (!entry) {\n entry = createMiddlewareEntry(middleware2);\n }\n middlewareMap.set(entry.id, entry);\n });\n }, {\n withTypes: () => addMiddleware\n });\n const getFinalMiddleware = (api) => {\n const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) => emplace(entry.applied, api, {\n insert: () => entry.middleware(api)\n }));\n return compose3(...appliedMiddleware);\n };\n const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId));\n const middleware = (api) => (next) => (action) => {\n if (isWithMiddleware(action)) {\n addMiddleware(...action.payload);\n return api.dispatch;\n }\n return getFinalMiddleware(api)(next)(action);\n };\n return {\n middleware,\n addMiddleware,\n withMiddleware,\n instanceId\n };\n};\n\n// src/combineSlices.ts\nimport { combineReducers as combineReducers2 } from \"redux\";\nvar isSliceLike = (maybeSliceLike) => \"reducerPath\" in maybeSliceLike && typeof maybeSliceLike.reducerPath === \"string\";\nvar getReducers = (slices) => slices.flatMap((sliceOrMap) => isSliceLike(sliceOrMap) ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]] : Object.entries(sliceOrMap));\nvar ORIGINAL_STATE = Symbol.for(\"rtk-state-proxy-original\");\nvar isStateProxy = (value) => !!value && !!value[ORIGINAL_STATE];\nvar stateProxyMap = /* @__PURE__ */ new WeakMap();\nvar createStateProxy = (state, reducerMap) => emplace(stateProxyMap, state, {\n insert: () => new Proxy(state, {\n get: (target, prop, receiver) => {\n if (prop === ORIGINAL_STATE)\n return target;\n const result = Reflect.get(target, prop, receiver);\n if (typeof result === \"undefined\") {\n const reducer = reducerMap[prop.toString()];\n if (reducer) {\n const reducerResult = reducer(void 0, {\n type: nanoid()\n });\n if (typeof reducerResult === \"undefined\") {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(24) : `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);\n }\n return reducerResult;\n }\n }\n return result;\n }\n })\n});\nvar original = (state) => {\n if (!isStateProxy(state)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(25) : \"original must be used on state Proxy\");\n }\n return state[ORIGINAL_STATE];\n};\nvar noopReducer = (state = {}) => state;\nfunction combineSlices(...slices) {\n const reducerMap = Object.fromEntries(getReducers(slices));\n const getReducer = () => Object.keys(reducerMap).length ? combineReducers2(reducerMap) : noopReducer;\n let reducer = getReducer();\n function combinedReducer(state, action) {\n return reducer(state, action);\n }\n combinedReducer.withLazyLoadedSlices = () => combinedReducer;\n const inject = (slice, config = {}) => {\n const {\n reducerPath,\n reducer: reducerToInject\n } = slice;\n const currentReducer = reducerMap[reducerPath];\n if (!config.overrideExisting && currentReducer && currentReducer !== reducerToInject) {\n if (typeof process !== \"undefined\" && process.env.NODE_ENV === \"development\") {\n console.error(`called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``);\n }\n return combinedReducer;\n }\n reducerMap[reducerPath] = reducerToInject;\n reducer = getReducer();\n return combinedReducer;\n };\n const selector = Object.assign(function makeSelector(selectorFn, selectState) {\n return function selector2(state, ...args) {\n return selectorFn(createStateProxy(selectState ? selectState(state, ...args) : state, reducerMap), ...args);\n };\n }, {\n original\n });\n return Object.assign(combinedReducer, {\n inject,\n selector\n });\n}\n\n// src/formatProdErrorMessage.ts\nfunction formatProdErrorMessage(code) {\n return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;\n}\nexport {\n ReducerType,\n SHOULD_AUTOBATCH,\n TaskAbortError,\n Tuple,\n addListener,\n asyncThunkCreator,\n autoBatchEnhancer,\n buildCreateSlice,\n clearAllListeners,\n combineSlices,\n configureStore,\n createAction,\n createActionCreatorInvariantMiddleware,\n createAsyncThunk,\n createDraftSafeSelector,\n createDraftSafeSelectorCreator,\n createDynamicMiddleware,\n createEntityAdapter,\n createImmutableStateInvariantMiddleware,\n createListenerMiddleware,\n produce as createNextState,\n createReducer,\n createSelector,\n createSelectorCreator2 as createSelectorCreator,\n createSerializableStateInvariantMiddleware,\n createSlice,\n current3 as current,\n findNonSerializableValue,\n formatProdErrorMessage,\n freeze,\n isActionCreator,\n isAllOf,\n isAnyOf,\n isAsyncThunkAction,\n isDraft5 as isDraft,\n isFSA as isFluxStandardAction,\n isFulfilled,\n isImmutableDefault,\n isPending,\n isPlain,\n isRejected,\n isRejectedWithValue,\n lruMemoize,\n miniSerializeError,\n nanoid,\n original2 as original,\n prepareAutoBatched,\n removeListener,\n unwrapResult,\n weakMapMemoize2 as weakMapMemoize\n};\n//# sourceMappingURL=redux-toolkit.modern.mjs.map","import { AppState, Theme } from '@/host/types/interfaces';\n\nimport type { PayloadAction } from '@reduxjs/toolkit';\nimport { createSlice } from '@reduxjs/toolkit';\n\nconst initialState: AppState = {\n theme: null,\n};\n\nexport const appSlice = createSlice({\n name: 'app',\n initialState,\n reducers: {\n setTheme: (state, action: PayloadAction) => {\n state.theme = action.payload;\n document.documentElement.setAttribute('data-theme', action.payload);\n },\n },\n});\n\nexport const { setTheme } = appSlice.actions;\nexport default appSlice.reducer;\n","export const enum CellType {\n clear,\n entry,\n exit,\n wall,\n visited,\n path,\n}\n\nexport enum Status {\n Generating,\n Ready,\n Searching,\n Complete,\n}\n\nexport enum Speed {\n Infinity = '∞',\n '4x' = '4x',\n '2x' = '2x',\n '1x' = '1x',\n '0.7x' = '0.7x',\n '0.5x' = '0.5x',\n '0.1x' = '0.1x',\n}\n","import { Speed } from '@pathFinder/models/enum';\n\nexport const cellSize = 25;\n\nexport const speeds: Map = new Map([\n [Speed.Infinity, 0],\n [Speed['4x'], 1],\n [Speed['2x'], 25],\n [Speed['1x'], 50],\n [Speed['0.7x'], 75],\n [Speed['0.5x'], 120],\n [Speed['0.1x'], 250],\n]);\n\nexport const defaultSpeeds = {\n mobile: Speed['1x'],\n desktop: Speed['4x'],\n};\n\nexport const cellColors = {\n clear: 'transparent',\n entry: 'deepskyblue',\n exit: 'lawngreen',\n wall: '#490e78', // purple\n visitedStart: 'blue',\n visitedMid: 'deepskyblue',\n visited: 'rgb(225 208 254)',\n path: 'blue',\n pathBorder: 'yellow',\n};\n\nconst root = document.querySelector(':root') as HTMLElement;\nroot.style.setProperty('--pf-cell-size', cellSize + 'px');\nroot.style.setProperty('--pf-cell-clear', cellColors.clear);\nroot.style.setProperty('--pf-cell-entry', cellColors.entry);\nroot.style.setProperty('--pf-cell-exit', cellColors.exit);\nroot.style.setProperty('--pf-cell-wall', cellColors.wall);\nroot.style.setProperty('--pf-cell-visited', cellColors.visited);\nroot.style.setProperty('--pf-cell-visited-start', cellColors.visitedStart);\nroot.style.setProperty('--pf-cell-visited-mid', cellColors.visitedMid);\nroot.style.setProperty('--pf-cell-path', cellColors.path);\nroot.style.setProperty('--pf-cell-path-border', cellColors.pathBorder);\n","import { cellSize } from '@pathFinder/config';\nimport { CellType } from '@pathFinder/models';\n\nfunction getRandom(max: number) {\n return Math.floor(Math.random() * max);\n}\n\nexport function generateGrid(\n rows: number,\n cols: number,\n value: T | null = null\n): T[][] {\n return Array.from(new Array(rows), () => new Array(cols).fill(value));\n}\n\nexport function initGrid(rows: number, cols: number) {\n const grid = generateGrid(rows, cols, 0);\n grid[0][0] = CellType.entry;\n grid[rows - 1][cols - 1] = CellType.exit;\n return grid;\n}\n\nexport function getEntryAndExit(\n grid: number[][],\n rows: number,\n cols: number,\n cellType: {\n clear: number;\n entry: number;\n exit: number;\n wall: number;\n }\n) {\n let entry = { row: -1, col: -1 };\n let exit = { row: -1, col: -1 };\n\n do {\n entry = { row: getRandom(rows), col: getRandom(cols) };\n } while (grid[entry.row][entry.col] !== cellType.clear);\n\n do {\n exit = { row: getRandom(rows), col: getRandom(cols) };\n } while (grid[exit.row][exit.col] !== cellType.clear);\n\n return { entry, exit };\n}\n\nexport function getDimensionsFromScreenSize() {\n let maxRows = Math.floor(\n (window.innerHeight - 120 - 2 * cellSize) / cellSize\n );\n let maxCols = Math.floor((window.innerWidth - 3 * cellSize) / cellSize);\n\n if (maxRows % 2 === 0) {\n maxRows -= 1;\n }\n\n if (maxCols % 2 === 0) {\n maxCols -= 1;\n }\n\n return {\n maxRows,\n maxCols,\n };\n}\n","import '@pathFinder/config';\nimport {\n AppState,\n Cell,\n CellElement,\n CellType,\n Status,\n} from '@pathFinder/models';\nimport {\n generateGrid,\n getDimensionsFromScreenSize,\n initGrid,\n} from '@pathFinder/helpers/grid.helper';\n\nimport type { PayloadAction } from '@reduxjs/toolkit';\nimport { createSlice } from '@reduxjs/toolkit';\n\nexport const { maxRows, maxCols } = getDimensionsFromScreenSize();\n\nconst initialState: AppState = {\n rows: maxRows,\n cols: maxCols,\n entry: { row: 0, col: 0 },\n exit: { row: maxRows - 1, col: maxCols - 1 },\n grid: initGrid(maxRows, maxCols),\n status: Status.Ready,\n visitedCellCount: 0,\n pathLength: 0,\n};\n\nexport const pathFinderSlice = createSlice({\n name: 'pathFinder',\n initialState,\n reducers: {\n setDimension: (\n state,\n action: PayloadAction<{ rows?: number; cols?: number }>\n ) => {\n state.rows = action.payload.rows ?? state.rows;\n state.cols = action.payload.cols ?? state.cols;\n },\n\n setGrid: (\n state,\n action: PayloadAction<{ grid: CellType[][]; clone?: boolean }>\n ) => {\n if (!action.payload.clone) {\n state.grid = action.payload.grid;\n return;\n }\n\n const gridClone = action.payload.grid.map((row) => row.slice());\n state.grid = gridClone;\n },\n\n setCell: (state, action: PayloadAction) => {\n const payload = action.payload;\n\n if (\n payload.cellType === CellType.entry ||\n payload.cellType === CellType.exit\n ) {\n const cellType = payload.cellType === CellType.entry ? 'entry' : 'exit';\n const { row, col } = state[cellType];\n state.grid[row][col] = CellType.clear;\n state[cellType] = {\n row: payload.row,\n col: payload.col,\n };\n }\n state.grid[payload.row][payload.col] = payload.cellType;\n },\n\n setCells: (\n state,\n action: PayloadAction<{ cells: Cell[]; cellType: CellType }>\n ) => {\n const { cells, cellType } = action.payload;\n\n const gridClone = state.grid.map((row) => row.slice());\n cells.forEach((cell) => {\n gridClone[cell.row][cell.col] = cellType;\n });\n\n state.grid = gridClone;\n },\n\n setStatus: (state, action: PayloadAction) => {\n state.status = action.payload;\n },\n\n clearGrid: (state) => {\n const gridClone = state.grid.map((row) => row.slice());\n for (let i = 0; i < state.rows; i++) {\n for (let j = 0; j < state.cols; j++) {\n if (\n gridClone[i][j] === CellType.visited ||\n gridClone[i][j] === CellType.path\n ) {\n gridClone[i][j] = CellType.clear;\n }\n }\n }\n state.grid = gridClone;\n state.status = Status.Ready;\n },\n\n resetGrid: (state) => {\n const grid = generateGrid(state.rows, state.cols, CellType.clear);\n if (state.entry.row >= state.rows) {\n state.entry.row = state.rows - 1;\n }\n if (state.entry.col >= state.cols) {\n state.entry.col = state.cols - 1;\n }\n if (state.exit.row >= state.rows) {\n state.exit.row = state.rows - 1;\n }\n if (state.exit.col >= state.cols) {\n state.exit.col = state.cols - 1;\n }\n grid[state.entry.row][state.entry.col] = CellType.entry;\n grid[state.exit.row][state.exit.col] = CellType.exit;\n\n state.grid = grid;\n state.status = Status.Ready;\n },\n\n setVisitedCellCount: (state, action: PayloadAction) => {\n state.visitedCellCount = action.payload;\n },\n\n setPathLength: (state, action: PayloadAction) => {\n state.pathLength = action.payload;\n },\n },\n});\n\nexport const {\n setDimension,\n setGrid,\n setCell,\n setCells,\n resetGrid,\n clearGrid,\n setStatus,\n setVisitedCellCount,\n setPathLength,\n} = pathFinderSlice.actions;\nexport default pathFinderSlice.reducer;\n","import { Simulator } from '@/lib/helpers/simulator';\n\nexport const maxInterval = 2000;\nexport let highlightInterval = 250;\nexport let swapInterval = 1000;\nexport const simulator = new Simulator();\n\nexport const setSwapInterval = (interval: number) => {\n swapInterval = interval;\n};\n\nexport const setHighlightInterval = (interval: number) => {\n highlightInterval = interval;\n};\n","export class Simulator {\n public isPlaying = false;\n public isPlayingPromise: Promise;\n private isPlayingResolver!: () => void;\n private onPlay: (() => void) | undefined;\n private onStop: (() => void) | undefined;\n\n constructor(onPlay?: () => void, onStop?: () => void) {\n this.onPlay = onPlay;\n this.onStop = onStop;\n this.isPlayingPromise = new Promise((r) => {\n this.isPlayingResolver = r;\n });\n }\n\n start() {\n if (this.isPlaying) {\n return;\n }\n\n this.isPlaying = true;\n this.isPlayingResolver();\n this.onPlay?.();\n }\n\n pause() {\n if (!this.isPlaying) {\n return;\n }\n\n this.isPlaying = false;\n this.isPlayingPromise = new Promise((r) => {\n this.isPlayingResolver = r;\n });\n this.onStop?.();\n }\n\n getStatus() {\n return this.isPlayingPromise;\n }\n}\n","export function delay(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","import {\n highlightInterval,\n simulator,\n swapInterval,\n} from '@sortViz/store/global.state';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\nimport { delay } from '@/lib/helpers/async';\n\nexport async function* swap(\n array: number[],\n i: number,\n j: number\n): SortAsyncGenerator {\n await simulator.isPlayingPromise;\n\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n\n yield { type: 'swap', positions: [i, j] };\n await delay(swapInterval);\n\n await simulator.isPlayingPromise;\n}\n\nexport async function* highlight(...positions: number[]): SortAsyncGenerator {\n yield { type: 'highlight', positions: [-1, -1] };\n await delay(highlightInterval);\n await simulator.isPlayingPromise;\n\n yield { type: 'highlight', positions };\n await delay(highlightInterval);\n\n await simulator.isPlayingPromise;\n}\n\nexport async function* showPivot(position: number): SortAsyncGenerator {\n yield { type: 'pivot', position };\n}\n\nexport async function* sort(position: number): SortAsyncGenerator {\n yield { type: 'sort', position: position };\n}\n\nexport async function* move(...positions: number[]): SortAsyncGenerator {\n await simulator.isPlayingPromise;\n yield { type: 'move', positions };\n await delay(swapInterval);\n}\n","import {\n highlight,\n showPivot,\n sort,\n swap,\n} from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nasync function* maxHeap(\n array: number[],\n i: number,\n length: number\n): SortAsyncGenerator {\n const left = 2 * i + 1;\n const right = 2 * i + 2;\n let max = i;\n\n const highlightArray = [];\n if (left < length) highlightArray.push(left);\n if (right < length) highlightArray.push(right);\n\n if (highlightArray.length > 0) {\n yield* showPivot(i);\n yield* highlight(...highlightArray);\n }\n\n if (left < length) {\n if (array[left] > array[max]) {\n max = left;\n }\n }\n\n if (right < length) {\n if (array[right] > array[max]) {\n max = right;\n }\n }\n\n if (max !== i) {\n yield* swap(array, i, max);\n yield* showPivot(-1);\n yield* maxHeap(array, max, length);\n }\n}\n\nexport async function* heapSort(array: number[]): SortAsyncGenerator {\n let length = array.length;\n for (let i = Math.floor(length / 2) - 1; i >= 0; i--) {\n yield* maxHeap(array, i, length);\n }\n\n for (let i = array.length - 1; i > 0; i--) {\n length--;\n yield* sort(length);\n yield* swap(array, 0, i);\n yield* maxHeap(array, 0, length);\n }\n\n yield* sort(0);\n}\n","import { highlight, move, sort } from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* mergeSort(\n array: number[],\n i = 0,\n j = array.length - 1,\n isFinal = true\n): SortAsyncGenerator {\n if (i === j) {\n if (isFinal && array.length === 1) {\n yield* sort(i);\n }\n\n return;\n }\n\n if (i < j) {\n const mid = Math.floor((i + j) / 2);\n yield* mergeSort(array, i, mid, false);\n yield* mergeSort(array, mid + 1, j, false);\n yield* merge(array, i, mid + 1, mid - i + 1, j - mid, isFinal);\n }\n}\n\nfunction shiftRight(array: number[], start: number, end: number) {\n for (let i = end; i > start; i--) {\n array[i] = array[i - 1];\n }\n}\n\nasync function* merge(\n array: number[],\n i: number,\n j: number,\n size1: number,\n size2: number,\n isFinal: boolean\n): SortAsyncGenerator {\n let iMove = 0;\n let jMove = 0;\n\n while (iMove < size1 && jMove < size2) {\n const left = i + iMove,\n right = j + jMove;\n\n yield* highlight(left, right);\n\n if (array[left] <= array[right]) {\n iMove++;\n\n if (isFinal) {\n yield* sort(left);\n }\n }\n\n if (array[left] > array[right]) {\n const value = array[right];\n shiftRight(array, left, right);\n array[left] = value;\n\n yield* move(left, right);\n\n i++;\n jMove++;\n\n if (isFinal) {\n yield* sort(left);\n }\n }\n }\n\n for (let k = i + iMove; k < i + size1; k++) {\n yield* highlight(k);\n\n if (isFinal) {\n yield* sort(k);\n }\n }\n\n for (let k = j + jMove; k < j + size2; k++) {\n yield* highlight(k);\n\n if (isFinal) {\n yield* sort(k);\n }\n }\n}\n","import { bubbleSort } from './bubble';\nimport { cocktailSort } from './cocktail';\nimport { heapSort } from './heap';\nimport { insertionSort } from './insertion';\nimport { mergeSort } from './merge';\nimport { quickSort } from './quick';\nimport { selectionSort } from './selection';\nimport { shellSort } from './shell';\n\nexport const algoList = [\n {\n name: 'bubble',\n fn: bubbleSort,\n },\n {\n name: 'selection',\n fn: selectionSort,\n },\n {\n name: 'insertion',\n fn: insertionSort,\n },\n {\n name: 'heap',\n fn: heapSort,\n },\n {\n name: 'merge',\n fn: mergeSort,\n },\n {\n name: 'quick',\n fn: quickSort,\n },\n {\n name: 'shell',\n fn: shellSort,\n },\n {\n name: 'cocktail',\n fn: cocktailSort,\n },\n];\n","import { highlight, sort, swap } from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* bubbleSort(array: number[]): SortAsyncGenerator {\n let i, j;\n\n for (i = 0; i < array.length; i++) {\n for (j = 0; j < array.length - i - 1; j++) {\n yield* highlight(j, j + 1);\n\n if (array[j] > array[j + 1]) {\n yield* swap(array, j, j + 1);\n }\n }\n\n yield* sort(j);\n }\n}\n","import {\n highlight,\n showPivot,\n sort,\n swap,\n} from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* selectionSort(array: number[]): SortAsyncGenerator {\n let i, j;\n\n for (i = 0; i < array.length; i++) {\n let maxIndex = 0;\n\n for (j = 1; j < array.length - i; j++) {\n yield* showPivot(maxIndex);\n yield* highlight(j);\n\n if (array[maxIndex] < array[j]) {\n maxIndex = j;\n }\n }\n\n j = j - 1;\n if (maxIndex !== j && array[maxIndex] !== array[j]) {\n yield* swap(array, maxIndex, j);\n }\n\n yield* sort(j);\n }\n}\n","import { highlight, sort, swap } from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* insertionSort(array: number[]): SortAsyncGenerator {\n let i, j;\n for (i = 0; i < array.length; i++) {\n let keyIndex = i;\n for (j = i - 1; j >= 0; j--) {\n yield* highlight(keyIndex, j);\n\n if (array[j] > array[keyIndex]) {\n yield* swap(array, j, keyIndex);\n keyIndex = j;\n } else {\n break;\n }\n }\n\n yield* sort(i);\n }\n}\n","import {\n highlight,\n showPivot,\n sort,\n swap,\n} from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nasync function* partition(\n array: number[],\n low: number,\n high: number\n): SortAsyncGenerator {\n const pivot = low;\n let i = low;\n let j = high + 1;\n\n yield* showPivot(pivot);\n\n while (i < j) {\n while (--j > low) {\n yield* highlight(j);\n if (array[j] < array[pivot]) {\n break;\n }\n }\n\n while (i <= high && i < j) {\n i++;\n yield* highlight(i);\n if (array[i] > array[pivot]) {\n break;\n }\n }\n\n if (i < j) {\n yield* swap(array, i, j);\n }\n }\n\n if (pivot !== j) {\n yield* swap(array, pivot, j);\n }\n\n yield* sort(j);\n return j;\n}\n\nexport async function* quickSort(\n array: number[],\n low = 0,\n high = array.length - 1\n): SortAsyncGenerator {\n if (low <= high) {\n const pivot = yield* partition(array, low, high);\n if (typeof pivot === 'number') {\n yield* quickSort(array, low, pivot - 1);\n yield* quickSort(array, pivot + 1, high);\n }\n }\n}\n","import { highlight, sort, swap } from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* shellSort(array: number[]): SortAsyncGenerator {\n if (array.length === 1) {\n yield* sort(0);\n return;\n }\n\n let gap = 1;\n\n while (gap * 3 + 1 < array.length) {\n gap = gap * 3 + 1;\n }\n\n while (gap > 0) {\n for (let i = gap; i < array.length; i++) {\n let j = i;\n const temp = array[i];\n yield* highlight(j, j - gap);\n while (j > 0 && array[j] <= array[j - gap]) {\n yield* highlight(j, j - gap);\n yield* swap(array, j - gap, j);\n j -= gap;\n }\n array[j] = temp;\n if (gap === 1) {\n yield* sort(0);\n yield* sort(i);\n }\n }\n gap = Math.floor((gap - 1) / 3);\n }\n}\n","import { highlight, sort, swap } from '@sortViz/helpers/algorithm-helpers';\n\nimport { SortAsyncGenerator } from '@sortViz/models/types';\n\nexport async function* cocktailSort(array: number[]): SortAsyncGenerator {\n for (let i = 0; i < array.length; i++) {\n let j = i;\n let sorted = 1;\n\n for (; j < array.length - 1 - i; j++) {\n yield* highlight(j, j + 1);\n\n if (array[j] > array[j + 1]) {\n yield* swap(array, j, j + 1);\n sorted = 0;\n }\n }\n\n if (sorted === 1) {\n for (let index = 0; index < array.length; index++) {\n yield* sort(index);\n }\n\n return;\n }\n\n yield* sort(array.length - 1 - i);\n\n sorted = 1;\n\n for (let k = j - 1; k > array.length - j - 1; k--) {\n yield* highlight(k - 1, k);\n\n if (array[k] < array[k - 1]) {\n yield* swap(array, k - 1, k);\n sorted = 0;\n }\n }\n\n if (sorted === 1) {\n for (let index = 0; index < array.length; index++) {\n yield* sort(index);\n }\n return;\n }\n\n yield* sort(i);\n }\n}\n","import { algoList } from './sorting-algorithms/algo-list';\n\nexport const menuItems = algoList.map((item) => item.name).concat('all');\nexport const initialArray = [6, 8, 3, 5, 1, 9, 2, 7, 4];\nexport const numberGenerator = { min: 10, max: 40 };\nexport const sortCompletionMessage = 'Sorting is complete';\n\nexport const cellCSS = {\n size: 50,\n margin: 4,\n};\n\nexport const barCSS = {\n size: 30,\n minSize: 10,\n maxHeight: 250,\n margin: 2,\n};\n\nexport const colors = {\n sort: '#8cf12b',\n highlight: 'yellow',\n pivot: 'orange',\n bar: 'lightgrey',\n};\n\nexport const selectedAlgosStatus = algoList.map(() => true);\n\nconst root = document.querySelector(':root') as HTMLElement;\nroot.style.setProperty('--cell-size', `${cellCSS.size}px`);\nroot.style.setProperty('--cell-margin', `${cellCSS.margin}px`);\nroot.style.setProperty('--bar-size', `${barCSS.size}px`);\nroot.style.setProperty('--bar-min-size', `${barCSS.minSize}px`);\nroot.style.setProperty('--bar-max-height', `${barCSS.maxHeight}px`);\nroot.style.setProperty('--bar-margin', `${barCSS.margin}px`);\nroot.style.setProperty('--color-sort', colors.sort);\nroot.style.setProperty('--color-highlight', colors.highlight);\nroot.style.setProperty('--color-pivot', colors.pivot);\nroot.style.setProperty('--color-bar', colors.bar);\n","import { initialArray, selectedAlgosStatus } from '@sortViz/config';\nimport {\n maxInterval,\n simulator,\n setHighlightInterval,\n setSwapInterval,\n} from './global.state';\n\nimport { AppDispatch } from '@/host/store/store';\nimport { AppState } from '@sortViz/models/interfaces';\nimport type { PayloadAction } from '@reduxjs/toolkit';\nimport { createSlice } from '@reduxjs/toolkit';\n\nconst initialState: AppState = {\n array: initialArray,\n visualizerType: 'cell',\n isPlaying: false,\n reset: false,\n time: 0,\n speed: 5,\n timeIntervalId: null,\n selectedAlgosStatus,\n};\n\nfunction setIntervals(state: AppState) {\n if (state.visualizerType === 'cell') {\n setSwapInterval(maxInterval / state.speed);\n } else {\n setSwapInterval(maxInterval / (state.speed * 4));\n }\n setHighlightInterval(maxInterval / (state.speed * 4));\n}\n\nexport const sortingVisualizerSlice = createSlice({\n name: 'sortViz',\n initialState,\n reducers: {\n setArray: (state, action: PayloadAction) => {\n state.array = action.payload;\n },\n\n setIsPlaying: (state, action: PayloadAction) => {\n state.isPlaying = action.payload;\n action.payload ? simulator.start() : simulator.pause();\n\n if (!state.isPlaying && state.timeIntervalId) {\n clearInterval(state.timeIntervalId);\n state.timeIntervalId = null;\n }\n },\n\n setIntervalId: (state, action: PayloadAction) => {\n state.timeIntervalId = action.payload;\n },\n\n incrementTime: (state) => {\n state.time++;\n },\n\n setReset: (state) => {\n state.reset = !state.reset;\n simulator.pause();\n state.time = 0;\n },\n\n modifyAlgoSelection: (state, action: PayloadAction) => {\n state.selectedAlgosStatus[action.payload] =\n !state.selectedAlgosStatus[action.payload];\n },\n\n setSpeed: (state, action: PayloadAction) => {\n state.speed = action.payload;\n setIntervals(state);\n },\n\n toggleVisualizerType: (state) => {\n state.visualizerType = state.visualizerType === 'cell' ? 'bar' : 'cell';\n setIntervals(state);\n },\n },\n});\n\nexport const {\n setArray,\n setIsPlaying,\n setReset,\n setSpeed,\n setIntervalId,\n incrementTime,\n modifyAlgoSelection,\n toggleVisualizerType,\n} = sortingVisualizerSlice.actions;\nexport default sortingVisualizerSlice.reducer;\n\nexport const startTimer = () => (dispatch: AppDispatch) => {\n const intervalId = setInterval(() => {\n dispatch(incrementTime());\n }, 100);\n dispatch(setIntervalId(intervalId));\n};\n","\"use strict\";\n\nexports.__esModule = true;\nexports.default = getStorage;\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction noop() {}\n\nvar noopStorage = {\n getItem: noop,\n setItem: noop,\n removeItem: noop\n};\n\nfunction hasStorage(storageType) {\n if ((typeof self === \"undefined\" ? \"undefined\" : _typeof(self)) !== 'object' || !(storageType in self)) {\n return false;\n }\n\n try {\n var storage = self[storageType];\n var testKey = \"redux-persist \".concat(storageType, \" test\");\n storage.setItem(testKey, 'test');\n storage.getItem(testKey);\n storage.removeItem(testKey);\n } catch (e) {\n if (process.env.NODE_ENV !== 'production') console.warn(\"redux-persist \".concat(storageType, \" test failed, persistence will be disabled.\"));\n return false;\n }\n\n return true;\n}\n\nfunction getStorage(type) {\n var storageType = \"\".concat(type, \"Storage\");\n if (hasStorage(storageType)) return self[storageType];else {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\"redux-persist failed to create sync storage. falling back to noop storage.\");\n }\n\n return noopStorage;\n }\n}","\"use strict\";\n\nexports.__esModule = true;\nexports.default = createWebStorage;\n\nvar _getStorage = _interopRequireDefault(require(\"./getStorage\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction createWebStorage(type) {\n var storage = (0, _getStorage.default)(type);\n return {\n getItem: function getItem(key) {\n return new Promise(function (resolve, reject) {\n resolve(storage.getItem(key));\n });\n },\n setItem: function setItem(key, item) {\n return new Promise(function (resolve, reject) {\n resolve(storage.setItem(key, item));\n });\n },\n removeItem: function removeItem(key) {\n return new Promise(function (resolve, reject) {\n resolve(storage.removeItem(key));\n });\n }\n };\n}","\"use strict\";\n\nexports.__esModule = true;\nexports.default = void 0;\n\nvar _createWebStorage = _interopRequireDefault(require(\"./createWebStorage\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nvar _default = (0, _createWebStorage.default)('local');\n\nexports.default = _default;","import {\n FLUSH,\n PAUSE,\n PERSIST,\n PURGE,\n REGISTER,\n REHYDRATE,\n persistReducer,\n persistStore,\n} from 'redux-persist';\n\nimport appReducer from './app.slice';\nimport { configureStore } from '@reduxjs/toolkit';\nimport pathFinderReducer from '@pathFinder/store/path-finder.slice';\nimport sortingVisualizerReducer from '@/apps/sorting-visualizer/store/sorting-visualizer.slice';\nimport storage from 'redux-persist/lib/storage';\n\nexport const store = configureStore({\n reducer: {\n app: persistReducer>(\n {\n key: 'app',\n storage,\n },\n appReducer\n ),\n sortViz: persistReducer>(\n {\n key: 'sorting-viz',\n storage,\n },\n sortingVisualizerReducer\n ),\n pathFinder: pathFinderReducer,\n },\n middleware: (getDefaultMiddleware) =>\n getDefaultMiddleware({\n serializableCheck: {\n ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],\n },\n }),\n});\n\nexport type RootState = ReturnType;\nexport type AppDispatch = typeof store.dispatch;\nexport const persistor = persistStore(store);\n","/**\n * @license React\n * scheduler.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n'use strict';function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.production.min.js\n *\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 createMemoryLocation(entry, typeof entry === \"string\" ? null : entry.state, index === 0 ? \"default\" : undefined));\n let index = clampIndex(initialIndex == null ? entries.length - 1 : initialIndex);\n let action = Action.Pop;\n let listener = null;\n function clampIndex(n) {\n return Math.min(Math.max(n, 0), entries.length - 1);\n }\n function getCurrentLocation() {\n return entries[index];\n }\n function createMemoryLocation(to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = createLocation(entries ? getCurrentLocation().pathname : \"/\", to, state, key);\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in memory history: \" + JSON.stringify(to));\n return location;\n }\n function createHref(to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n let history = {\n get index() {\n return index;\n },\n get action() {\n return action;\n },\n get location() {\n return getCurrentLocation();\n },\n createHref,\n createURL(to) {\n return new URL(createHref(to), \"http://localhost\");\n },\n encodeLocation(to) {\n let path = typeof to === \"string\" ? parsePath(to) : to;\n return {\n pathname: path.pathname || \"\",\n search: path.search || \"\",\n hash: path.hash || \"\"\n };\n },\n push(to, state) {\n action = Action.Push;\n let nextLocation = createMemoryLocation(to, state);\n index += 1;\n entries.splice(index, entries.length, nextLocation);\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 1\n });\n }\n },\n replace(to, state) {\n action = Action.Replace;\n let nextLocation = createMemoryLocation(to, state);\n entries[index] = nextLocation;\n if (v5Compat && listener) {\n listener({\n action,\n location: nextLocation,\n delta: 0\n });\n }\n },\n go(delta) {\n action = Action.Pop;\n let nextIndex = clampIndex(index + delta);\n let nextLocation = entries[nextIndex];\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: nextLocation,\n delta\n });\n }\n },\n listen(fn) {\n listener = fn;\n return () => {\n listener = null;\n };\n }\n };\n return history;\n}\n/**\n * Browser history stores the location in regular URLs. This is the standard for\n * most web apps, but it requires some configuration on the server to ensure you\n * serve the same app at multiple URLs.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createbrowserhistory\n */\nfunction createBrowserHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createBrowserLocation(window, globalHistory) {\n let {\n pathname,\n search,\n hash\n } = window.location;\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createBrowserHref(window, to) {\n return typeof to === \"string\" ? to : createPath(to);\n }\n return getUrlBasedHistory(createBrowserLocation, createBrowserHref, null, options);\n}\n/**\n * Hash history stores the location in window.location.hash. This makes it ideal\n * for situations where you don't want to send the location to the server for\n * some reason, either because you do cannot configure it or the URL space is\n * reserved for something else.\n *\n * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#createhashhistory\n */\nfunction createHashHistory(options) {\n if (options === void 0) {\n options = {};\n }\n function createHashLocation(window, globalHistory) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = parsePath(window.location.hash.substr(1));\n // Hash URL should always have a leading / just like window.location.pathname\n // does, so if an app ends up at a route like /#something then we add a\n // leading slash so all of our path-matching behaves the same as if it would\n // in a browser router. This is particularly important when there exists a\n // root splat route () since that matches internally against\n // \"/*\" and we'd expect /#something to 404 in a hash router app.\n if (!pathname.startsWith(\"/\") && !pathname.startsWith(\".\")) {\n pathname = \"/\" + pathname;\n }\n return createLocation(\"\", {\n pathname,\n search,\n hash\n },\n // state defaults to `null` because `window.history.state` does\n globalHistory.state && globalHistory.state.usr || null, globalHistory.state && globalHistory.state.key || \"default\");\n }\n function createHashHref(window, to) {\n let base = window.document.querySelector(\"base\");\n let href = \"\";\n if (base && base.getAttribute(\"href\")) {\n let url = window.location.href;\n let hashIndex = url.indexOf(\"#\");\n href = hashIndex === -1 ? url : url.slice(0, hashIndex);\n }\n return href + \"#\" + (typeof to === \"string\" ? to : createPath(to));\n }\n function validateHashLocation(location, to) {\n warning(location.pathname.charAt(0) === \"/\", \"relative pathnames are not supported in hash history.push(\" + JSON.stringify(to) + \")\");\n }\n return getUrlBasedHistory(createHashLocation, createHashHref, validateHashLocation, options);\n}\nfunction invariant(value, message) {\n if (value === false || value === null || typeof value === \"undefined\") {\n throw new Error(message);\n }\n}\nfunction warning(cond, message) {\n if (!cond) {\n // eslint-disable-next-line no-console\n if (typeof console !== \"undefined\") console.warn(message);\n try {\n // Welcome to debugging history!\n //\n // This error is thrown as a convenience, so you can more easily\n // find the source for a warning that appears in the console by\n // enabling \"pause on exceptions\" in your JavaScript debugger.\n throw new Error(message);\n // eslint-disable-next-line no-empty\n } catch (e) {}\n }\n}\nfunction createKey() {\n return Math.random().toString(36).substr(2, 8);\n}\n/**\n * For browser-based histories, we combine the state and key into an object\n */\nfunction getHistoryState(location, index) {\n return {\n usr: location.state,\n key: location.key,\n idx: index\n };\n}\n/**\n * Creates a Location object with a unique key from the given Path\n */\nfunction createLocation(current, to, state, key) {\n if (state === void 0) {\n state = null;\n }\n let location = _extends({\n pathname: typeof current === \"string\" ? current : current.pathname,\n search: \"\",\n hash: \"\"\n }, typeof to === \"string\" ? parsePath(to) : to, {\n state,\n // TODO: This could be cleaned up. push/replace should probably just take\n // full Locations now and avoid the need to run through this flow at all\n // But that's a pretty big refactor to the current test suite so going to\n // keep as is for the time being and just let any incoming keys take precedence\n key: to && to.key || key || createKey()\n });\n return location;\n}\n/**\n * Creates a string URL path from the given pathname, search, and hash components.\n */\nfunction createPath(_ref) {\n let {\n pathname = \"/\",\n search = \"\",\n hash = \"\"\n } = _ref;\n if (search && search !== \"?\") pathname += search.charAt(0) === \"?\" ? search : \"?\" + search;\n if (hash && hash !== \"#\") pathname += hash.charAt(0) === \"#\" ? hash : \"#\" + hash;\n return pathname;\n}\n/**\n * Parses a string URL path into its separate pathname, search, and hash components.\n */\nfunction parsePath(path) {\n let parsedPath = {};\n if (path) {\n let hashIndex = path.indexOf(\"#\");\n if (hashIndex >= 0) {\n parsedPath.hash = path.substr(hashIndex);\n path = path.substr(0, hashIndex);\n }\n let searchIndex = path.indexOf(\"?\");\n if (searchIndex >= 0) {\n parsedPath.search = path.substr(searchIndex);\n path = path.substr(0, searchIndex);\n }\n if (path) {\n parsedPath.pathname = path;\n }\n }\n return parsedPath;\n}\nfunction getUrlBasedHistory(getLocation, createHref, validateLocation, options) {\n if (options === void 0) {\n options = {};\n }\n let {\n window = document.defaultView,\n v5Compat = false\n } = options;\n let globalHistory = window.history;\n let action = Action.Pop;\n let listener = null;\n let index = getIndex();\n // Index should only be null when we initialize. If not, it's because the\n // user called history.pushState or history.replaceState directly, in which\n // case we should log a warning as it will result in bugs.\n if (index == null) {\n index = 0;\n globalHistory.replaceState(_extends({}, globalHistory.state, {\n idx: index\n }), \"\");\n }\n function getIndex() {\n let state = globalHistory.state || {\n idx: null\n };\n return state.idx;\n }\n function handlePop() {\n action = Action.Pop;\n let nextIndex = getIndex();\n let delta = nextIndex == null ? null : nextIndex - index;\n index = nextIndex;\n if (listener) {\n listener({\n action,\n location: history.location,\n delta\n });\n }\n }\n function push(to, state) {\n action = Action.Push;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex() + 1;\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n // try...catch because iOS limits us to 100 pushState calls :/\n try {\n globalHistory.pushState(historyState, \"\", url);\n } catch (error) {\n // If the exception is because `state` can't be serialized, let that throw\n // outwards just like a replace call would so the dev knows the cause\n // https://html.spec.whatwg.org/multipage/nav-history-apis.html#shared-history-push/replace-state-steps\n // https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal\n if (error instanceof DOMException && error.name === \"DataCloneError\") {\n throw error;\n }\n // They are going to lose state here, but there is no real\n // way to warn them about it since the page will refresh...\n window.location.assign(url);\n }\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 1\n });\n }\n }\n function replace(to, state) {\n action = Action.Replace;\n let location = createLocation(history.location, to, state);\n if (validateLocation) validateLocation(location, to);\n index = getIndex();\n let historyState = getHistoryState(location, index);\n let url = history.createHref(location);\n globalHistory.replaceState(historyState, \"\", url);\n if (v5Compat && listener) {\n listener({\n action,\n location: history.location,\n delta: 0\n });\n }\n }\n function createURL(to) {\n // window.location.origin is \"null\" (the literal string value) in Firefox\n // under certain conditions, notably when serving from a local HTML file\n // See https://bugzilla.mozilla.org/show_bug.cgi?id=878297\n let base = window.location.origin !== \"null\" ? window.location.origin : window.location.href;\n let href = typeof to === \"string\" ? to : createPath(to);\n // Treating this as a full URL will strip any trailing spaces so we need to\n // pre-encode them since they might be part of a matching splat param from\n // an ancestor route\n href = href.replace(/ $/, \"%20\");\n invariant(base, \"No window.location.(origin|href) available to create URL for href: \" + href);\n return new URL(href, base);\n }\n let history = {\n get action() {\n return action;\n },\n get location() {\n return getLocation(window, globalHistory);\n },\n listen(fn) {\n if (listener) {\n throw new Error(\"A history only accepts one active listener\");\n }\n window.addEventListener(PopStateEventType, handlePop);\n listener = fn;\n return () => {\n window.removeEventListener(PopStateEventType, handlePop);\n listener = null;\n };\n },\n createHref(to) {\n return createHref(window, to);\n },\n createURL,\n encodeLocation(to) {\n // Encode a Location the same way window.location would\n let url = createURL(to);\n return {\n pathname: url.pathname,\n search: url.search,\n hash: url.hash\n };\n },\n push,\n replace,\n go(n) {\n return globalHistory.go(n);\n }\n };\n return history;\n}\n//#endregion\n\nvar ResultType;\n(function (ResultType) {\n ResultType[\"data\"] = \"data\";\n ResultType[\"deferred\"] = \"deferred\";\n ResultType[\"redirect\"] = \"redirect\";\n ResultType[\"error\"] = \"error\";\n})(ResultType || (ResultType = {}));\nconst immutableRouteKeys = new Set([\"lazy\", \"caseSensitive\", \"path\", \"id\", \"index\", \"children\"]);\nfunction isIndexRoute(route) {\n return route.index === true;\n}\n// Walk the route tree generating unique IDs where necessary, so we are working\n// solely with AgnosticDataRouteObject's within the Router\nfunction convertRoutesToDataRoutes(routes, mapRouteProperties, parentPath, manifest) {\n if (parentPath === void 0) {\n parentPath = [];\n }\n if (manifest === void 0) {\n manifest = {};\n }\n return routes.map((route, index) => {\n let treePath = [...parentPath, String(index)];\n let id = typeof route.id === \"string\" ? route.id : treePath.join(\"-\");\n invariant(route.index !== true || !route.children, \"Cannot specify children on an index route\");\n invariant(!manifest[id], \"Found a route id collision on id \\\"\" + id + \"\\\". Route \" + \"id's must be globally unique within Data Router usages\");\n if (isIndexRoute(route)) {\n let indexRoute = _extends({}, route, mapRouteProperties(route), {\n id\n });\n manifest[id] = indexRoute;\n return indexRoute;\n } else {\n let pathOrLayoutRoute = _extends({}, route, mapRouteProperties(route), {\n id,\n children: undefined\n });\n manifest[id] = pathOrLayoutRoute;\n if (route.children) {\n pathOrLayoutRoute.children = convertRoutesToDataRoutes(route.children, mapRouteProperties, treePath, manifest);\n }\n return pathOrLayoutRoute;\n }\n });\n}\n/**\n * Matches the given routes to a location and returns the match data.\n *\n * @see https://reactrouter.com/utils/match-routes\n */\nfunction matchRoutes(routes, locationArg, basename) {\n if (basename === void 0) {\n basename = \"/\";\n }\n return matchRoutesImpl(routes, locationArg, basename, false);\n}\nfunction matchRoutesImpl(routes, locationArg, basename, allowPartial) {\n let location = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n let pathname = stripBasename(location.pathname || \"/\", basename);\n if (pathname == null) {\n return null;\n }\n let branches = flattenRoutes(routes);\n rankRouteBranches(branches);\n let matches = null;\n for (let i = 0; matches == null && i < branches.length; ++i) {\n // Incoming pathnames are generally encoded from either window.location\n // or from router.navigate, but we want to match against the unencoded\n // paths in the route definitions. Memory router locations won't be\n // encoded here but there also shouldn't be anything to decode so this\n // should be a safe operation. This avoids needing matchRoutes to be\n // history-aware.\n let decoded = decodePath(pathname);\n matches = matchRouteBranch(branches[i], decoded, allowPartial);\n }\n return matches;\n}\nfunction convertRouteMatchToUiMatch(match, loaderData) {\n let {\n route,\n pathname,\n params\n } = match;\n return {\n id: route.id,\n pathname,\n params,\n data: loaderData[route.id],\n handle: route.handle\n };\n}\nfunction flattenRoutes(routes, branches, parentsMeta, parentPath) {\n if (branches === void 0) {\n branches = [];\n }\n if (parentsMeta === void 0) {\n parentsMeta = [];\n }\n if (parentPath === void 0) {\n parentPath = \"\";\n }\n let flattenRoute = (route, index, relativePath) => {\n let meta = {\n relativePath: relativePath === undefined ? route.path || \"\" : relativePath,\n caseSensitive: route.caseSensitive === true,\n childrenIndex: index,\n route\n };\n if (meta.relativePath.startsWith(\"/\")) {\n invariant(meta.relativePath.startsWith(parentPath), \"Absolute route path \\\"\" + meta.relativePath + \"\\\" nested under path \" + (\"\\\"\" + parentPath + \"\\\" is not valid. An absolute child route path \") + \"must start with the combined path of all its parent routes.\");\n meta.relativePath = meta.relativePath.slice(parentPath.length);\n }\n let path = joinPaths([parentPath, meta.relativePath]);\n let routesMeta = parentsMeta.concat(meta);\n // Add the children before adding this route to the array, so we traverse the\n // route tree depth-first and child routes appear before their parents in\n // the \"flattened\" version.\n if (route.children && route.children.length > 0) {\n invariant(\n // Our types know better, but runtime JS may not!\n // @ts-expect-error\n route.index !== true, \"Index routes must not have child routes. Please remove \" + (\"all child routes from route path \\\"\" + path + \"\\\".\"));\n flattenRoutes(route.children, branches, routesMeta, path);\n }\n // Routes without a path shouldn't ever match by themselves unless they are\n // index routes, so don't add them to the list of possible branches.\n if (route.path == null && !route.index) {\n return;\n }\n branches.push({\n path,\n score: computeScore(path, route.index),\n routesMeta\n });\n };\n routes.forEach((route, index) => {\n var _route$path;\n // coarse-grain check for optional params\n if (route.path === \"\" || !((_route$path = route.path) != null && _route$path.includes(\"?\"))) {\n flattenRoute(route, index);\n } else {\n for (let exploded of explodeOptionalSegments(route.path)) {\n flattenRoute(route, index, exploded);\n }\n }\n });\n return branches;\n}\n/**\n * Computes all combinations of optional path segments for a given path,\n * excluding combinations that are ambiguous and of lower priority.\n *\n * For example, `/one/:two?/three/:four?/:five?` explodes to:\n * - `/one/three`\n * - `/one/:two/three`\n * - `/one/three/:four`\n * - `/one/three/:five`\n * - `/one/:two/three/:four`\n * - `/one/:two/three/:five`\n * - `/one/three/:four/:five`\n * - `/one/:two/three/:four/:five`\n */\nfunction explodeOptionalSegments(path) {\n let segments = path.split(\"/\");\n if (segments.length === 0) return [];\n let [first, ...rest] = segments;\n // Optional path segments are denoted by a trailing `?`\n let isOptional = first.endsWith(\"?\");\n // Compute the corresponding required segment: `foo?` -> `foo`\n let required = first.replace(/\\?$/, \"\");\n if (rest.length === 0) {\n // Intepret empty string as omitting an optional segment\n // `[\"one\", \"\", \"three\"]` corresponds to omitting `:two` from `/one/:two?/three` -> `/one/three`\n return isOptional ? [required, \"\"] : [required];\n }\n let restExploded = explodeOptionalSegments(rest.join(\"/\"));\n let result = [];\n // All child paths with the prefix. Do this for all children before the\n // optional version for all children, so we get consistent ordering where the\n // parent optional aspect is preferred as required. Otherwise, we can get\n // child sections interspersed where deeper optional segments are higher than\n // parent optional segments, where for example, /:two would explode _earlier_\n // then /:one. By always including the parent as required _for all children_\n // first, we avoid this issue\n result.push(...restExploded.map(subpath => subpath === \"\" ? required : [required, subpath].join(\"/\")));\n // Then, if this is an optional value, add all child versions without\n if (isOptional) {\n result.push(...restExploded);\n }\n // for absolute paths, ensure `/` instead of empty segment\n return result.map(exploded => path.startsWith(\"/\") && exploded === \"\" ? \"/\" : exploded);\n}\nfunction rankRouteBranches(branches) {\n branches.sort((a, b) => a.score !== b.score ? b.score - a.score // Higher score first\n : compareIndexes(a.routesMeta.map(meta => meta.childrenIndex), b.routesMeta.map(meta => meta.childrenIndex)));\n}\nconst paramRe = /^:[\\w-]+$/;\nconst dynamicSegmentValue = 3;\nconst indexRouteValue = 2;\nconst emptySegmentValue = 1;\nconst staticSegmentValue = 10;\nconst splatPenalty = -2;\nconst isSplat = s => s === \"*\";\nfunction computeScore(path, index) {\n let segments = path.split(\"/\");\n let initialScore = segments.length;\n if (segments.some(isSplat)) {\n initialScore += splatPenalty;\n }\n if (index) {\n initialScore += indexRouteValue;\n }\n return segments.filter(s => !isSplat(s)).reduce((score, segment) => score + (paramRe.test(segment) ? dynamicSegmentValue : segment === \"\" ? emptySegmentValue : staticSegmentValue), initialScore);\n}\nfunction compareIndexes(a, b) {\n let siblings = a.length === b.length && a.slice(0, -1).every((n, i) => n === b[i]);\n return siblings ?\n // If two routes are siblings, we should try to match the earlier sibling\n // first. This allows people to have fine-grained control over the matching\n // behavior by simply putting routes with identical paths in the order they\n // want them tried.\n a[a.length - 1] - b[b.length - 1] :\n // Otherwise, it doesn't really make sense to rank non-siblings by index,\n // so they sort equally.\n 0;\n}\nfunction matchRouteBranch(branch, pathname, allowPartial) {\n if (allowPartial === void 0) {\n allowPartial = false;\n }\n let {\n routesMeta\n } = branch;\n let matchedParams = {};\n let matchedPathname = \"/\";\n let matches = [];\n for (let i = 0; i < routesMeta.length; ++i) {\n let meta = routesMeta[i];\n let end = i === routesMeta.length - 1;\n let remainingPathname = matchedPathname === \"/\" ? pathname : pathname.slice(matchedPathname.length) || \"/\";\n let match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end\n }, remainingPathname);\n let route = meta.route;\n if (!match && end && allowPartial && !routesMeta[routesMeta.length - 1].route.index) {\n match = matchPath({\n path: meta.relativePath,\n caseSensitive: meta.caseSensitive,\n end: false\n }, remainingPathname);\n }\n if (!match) {\n return null;\n }\n Object.assign(matchedParams, match.params);\n matches.push({\n // TODO: Can this as be avoided?\n params: matchedParams,\n pathname: joinPaths([matchedPathname, match.pathname]),\n pathnameBase: normalizePathname(joinPaths([matchedPathname, match.pathnameBase])),\n route\n });\n if (match.pathnameBase !== \"/\") {\n matchedPathname = joinPaths([matchedPathname, match.pathnameBase]);\n }\n }\n return matches;\n}\n/**\n * Returns a path with params interpolated.\n *\n * @see https://reactrouter.com/utils/generate-path\n */\nfunction generatePath(originalPath, params) {\n if (params === void 0) {\n params = {};\n }\n let path = originalPath;\n if (path.endsWith(\"*\") && path !== \"*\" && !path.endsWith(\"/*\")) {\n warning(false, \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n path = path.replace(/\\*$/, \"/*\");\n }\n // ensure `/` is added at the beginning if the path is absolute\n const prefix = path.startsWith(\"/\") ? \"/\" : \"\";\n const stringify = p => p == null ? \"\" : typeof p === \"string\" ? p : String(p);\n const segments = path.split(/\\/+/).map((segment, index, array) => {\n const isLastSegment = index === array.length - 1;\n // only apply the splat if it's the last segment\n if (isLastSegment && segment === \"*\") {\n const star = \"*\";\n // Apply the splat\n return stringify(params[star]);\n }\n const keyMatch = segment.match(/^:([\\w-]+)(\\??)$/);\n if (keyMatch) {\n const [, key, optional] = keyMatch;\n let param = params[key];\n invariant(optional === \"?\" || param != null, \"Missing \\\":\" + key + \"\\\" param\");\n return stringify(param);\n }\n // Remove any optional markers from optional static segments\n return segment.replace(/\\?$/g, \"\");\n })\n // Remove empty segments\n .filter(segment => !!segment);\n return prefix + segments.join(\"/\");\n}\n/**\n * Performs pattern matching on a URL pathname and returns information about\n * the match.\n *\n * @see https://reactrouter.com/utils/match-path\n */\nfunction matchPath(pattern, pathname) {\n if (typeof pattern === \"string\") {\n pattern = {\n path: pattern,\n caseSensitive: false,\n end: true\n };\n }\n let [matcher, compiledParams] = compilePath(pattern.path, pattern.caseSensitive, pattern.end);\n let match = pathname.match(matcher);\n if (!match) return null;\n let matchedPathname = match[0];\n let pathnameBase = matchedPathname.replace(/(.)\\/+$/, \"$1\");\n let captureGroups = match.slice(1);\n let params = compiledParams.reduce((memo, _ref, index) => {\n let {\n paramName,\n isOptional\n } = _ref;\n // We need to compute the pathnameBase here using the raw splat value\n // instead of using params[\"*\"] later because it will be decoded then\n if (paramName === \"*\") {\n let splatValue = captureGroups[index] || \"\";\n pathnameBase = matchedPathname.slice(0, matchedPathname.length - splatValue.length).replace(/(.)\\/+$/, \"$1\");\n }\n const value = captureGroups[index];\n if (isOptional && !value) {\n memo[paramName] = undefined;\n } else {\n memo[paramName] = (value || \"\").replace(/%2F/g, \"/\");\n }\n return memo;\n }, {});\n return {\n params,\n pathname: matchedPathname,\n pathnameBase,\n pattern\n };\n}\nfunction compilePath(path, caseSensitive, end) {\n if (caseSensitive === void 0) {\n caseSensitive = false;\n }\n if (end === void 0) {\n end = true;\n }\n warning(path === \"*\" || !path.endsWith(\"*\") || path.endsWith(\"/*\"), \"Route path \\\"\" + path + \"\\\" will be treated as if it were \" + (\"\\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\" because the `*` character must \") + \"always follow a `/` in the pattern. To get rid of this warning, \" + (\"please change the route path to \\\"\" + path.replace(/\\*$/, \"/*\") + \"\\\".\"));\n let params = [];\n let regexpSource = \"^\" + path.replace(/\\/*\\*?$/, \"\") // Ignore trailing / and /*, we'll handle it below\n .replace(/^\\/*/, \"/\") // Make sure it has a leading /\n .replace(/[\\\\.*+^${}|()[\\]]/g, \"\\\\$&\") // Escape special regex chars\n .replace(/\\/:([\\w-]+)(\\?)?/g, (_, paramName, isOptional) => {\n params.push({\n paramName,\n isOptional: isOptional != null\n });\n return isOptional ? \"/?([^\\\\/]+)?\" : \"/([^\\\\/]+)\";\n });\n if (path.endsWith(\"*\")) {\n params.push({\n paramName: \"*\"\n });\n regexpSource += path === \"*\" || path === \"/*\" ? \"(.*)$\" // Already matched the initial /, just match the rest\n : \"(?:\\\\/(.+)|\\\\/*)$\"; // Don't include the / in params[\"*\"]\n } else if (end) {\n // When matching to the end, ignore trailing slashes\n regexpSource += \"\\\\/*$\";\n } else if (path !== \"\" && path !== \"/\") {\n // If our path is non-empty and contains anything beyond an initial slash,\n // then we have _some_ form of path in our regex, so we should expect to\n // match only if we find the end of this path segment. Look for an optional\n // non-captured trailing slash (to match a portion of the URL) or the end\n // of the path (if we've matched to the end). We used to do this with a\n // word boundary but that gives false positives on routes like\n // /user-preferences since `-` counts as a word boundary.\n regexpSource += \"(?:(?=\\\\/|$))\";\n } else ;\n let matcher = new RegExp(regexpSource, caseSensitive ? undefined : \"i\");\n return [matcher, params];\n}\nfunction decodePath(value) {\n try {\n return value.split(\"/\").map(v => decodeURIComponent(v).replace(/\\//g, \"%2F\")).join(\"/\");\n } catch (error) {\n warning(false, \"The URL path \\\"\" + value + \"\\\" could not be decoded because it is is a \" + \"malformed URL segment. This is probably due to a bad percent \" + (\"encoding (\" + error + \").\"));\n return value;\n }\n}\n/**\n * @private\n */\nfunction stripBasename(pathname, basename) {\n if (basename === \"/\") return pathname;\n if (!pathname.toLowerCase().startsWith(basename.toLowerCase())) {\n return null;\n }\n // We want to leave trailing slash behavior in the user's control, so if they\n // specify a basename with a trailing slash, we should support it\n let startIndex = basename.endsWith(\"/\") ? basename.length - 1 : basename.length;\n let nextChar = pathname.charAt(startIndex);\n if (nextChar && nextChar !== \"/\") {\n // pathname does not start with basename/\n return null;\n }\n return pathname.slice(startIndex) || \"/\";\n}\n/**\n * Returns a resolved path object relative to the given pathname.\n *\n * @see https://reactrouter.com/utils/resolve-path\n */\nfunction resolvePath(to, fromPathname) {\n if (fromPathname === void 0) {\n fromPathname = \"/\";\n }\n let {\n pathname: toPathname,\n search = \"\",\n hash = \"\"\n } = typeof to === \"string\" ? parsePath(to) : to;\n let pathname = toPathname ? toPathname.startsWith(\"/\") ? toPathname : resolvePathname(toPathname, fromPathname) : fromPathname;\n return {\n pathname,\n search: normalizeSearch(search),\n hash: normalizeHash(hash)\n };\n}\nfunction resolvePathname(relativePath, fromPathname) {\n let segments = fromPathname.replace(/\\/+$/, \"\").split(\"/\");\n let relativeSegments = relativePath.split(\"/\");\n relativeSegments.forEach(segment => {\n if (segment === \"..\") {\n // Keep the root \"\" segment so the pathname starts at /\n if (segments.length > 1) segments.pop();\n } else if (segment !== \".\") {\n segments.push(segment);\n }\n });\n return segments.length > 1 ? segments.join(\"/\") : \"/\";\n}\nfunction getInvalidPathError(char, field, dest, path) {\n return \"Cannot include a '\" + char + \"' character in a manually specified \" + (\"`to.\" + field + \"` field [\" + JSON.stringify(path) + \"]. Please separate it out to the \") + (\"`to.\" + dest + \"` field. Alternatively you may provide the full path as \") + \"a string in and the router will parse it for you.\";\n}\n/**\n * @private\n *\n * When processing relative navigation we want to ignore ancestor routes that\n * do not contribute to the path, such that index/pathless layout routes don't\n * interfere.\n *\n * For example, when moving a route element into an index route and/or a\n * pathless layout route, relative link behavior contained within should stay\n * the same. Both of the following examples should link back to the root:\n *\n * \n * \n * \n *\n * \n * \n * }> // <-- Does not contribute\n * // <-- Does not contribute\n * \n * \n */\nfunction getPathContributingMatches(matches) {\n return matches.filter((match, index) => index === 0 || match.route.path && match.route.path.length > 0);\n}\n// Return the array of pathnames for the current route matches - used to\n// generate the routePathnames input for resolveTo()\nfunction getResolveToMatches(matches, v7_relativeSplatPath) {\n let pathMatches = getPathContributingMatches(matches);\n // When v7_relativeSplatPath is enabled, use the full pathname for the leaf\n // match so we include splat values for \".\" links. See:\n // https://github.com/remix-run/react-router/issues/11052#issuecomment-1836589329\n if (v7_relativeSplatPath) {\n return pathMatches.map((match, idx) => idx === pathMatches.length - 1 ? match.pathname : match.pathnameBase);\n }\n return pathMatches.map(match => match.pathnameBase);\n}\n/**\n * @private\n */\nfunction resolveTo(toArg, routePathnames, locationPathname, isPathRelative) {\n if (isPathRelative === void 0) {\n isPathRelative = false;\n }\n let to;\n if (typeof toArg === \"string\") {\n to = parsePath(toArg);\n } else {\n to = _extends({}, toArg);\n invariant(!to.pathname || !to.pathname.includes(\"?\"), getInvalidPathError(\"?\", \"pathname\", \"search\", to));\n invariant(!to.pathname || !to.pathname.includes(\"#\"), getInvalidPathError(\"#\", \"pathname\", \"hash\", to));\n invariant(!to.search || !to.search.includes(\"#\"), getInvalidPathError(\"#\", \"search\", \"hash\", to));\n }\n let isEmptyPath = toArg === \"\" || to.pathname === \"\";\n let toPathname = isEmptyPath ? \"/\" : to.pathname;\n let from;\n // Routing is relative to the current pathname if explicitly requested.\n //\n // If a pathname is explicitly provided in `to`, it should be relative to the\n // route context. This is explained in `Note on `` values` in our\n // migration guide from v5 as a means of disambiguation between `to` values\n // that begin with `/` and those that do not. However, this is problematic for\n // `to` values that do not provide a pathname. `to` can simply be a search or\n // hash string, in which case we should assume that the navigation is relative\n // to the current location's pathname and *not* the route pathname.\n if (toPathname == null) {\n from = locationPathname;\n } else {\n let routePathnameIndex = routePathnames.length - 1;\n // With relative=\"route\" (the default), each leading .. segment means\n // \"go up one route\" instead of \"go up one URL segment\". This is a key\n // difference from how works and a major reason we call this a\n // \"to\" value instead of a \"href\".\n if (!isPathRelative && toPathname.startsWith(\"..\")) {\n let toSegments = toPathname.split(\"/\");\n while (toSegments[0] === \"..\") {\n toSegments.shift();\n routePathnameIndex -= 1;\n }\n to.pathname = toSegments.join(\"/\");\n }\n from = routePathnameIndex >= 0 ? routePathnames[routePathnameIndex] : \"/\";\n }\n let path = resolvePath(to, from);\n // Ensure the pathname has a trailing slash if the original \"to\" had one\n let hasExplicitTrailingSlash = toPathname && toPathname !== \"/\" && toPathname.endsWith(\"/\");\n // Or if this was a link to the current path which has a trailing slash\n let hasCurrentTrailingSlash = (isEmptyPath || toPathname === \".\") && locationPathname.endsWith(\"/\");\n if (!path.pathname.endsWith(\"/\") && (hasExplicitTrailingSlash || hasCurrentTrailingSlash)) {\n path.pathname += \"/\";\n }\n return path;\n}\n/**\n * @private\n */\nfunction getToPathname(to) {\n // Empty strings should be treated the same as / paths\n return to === \"\" || to.pathname === \"\" ? \"/\" : typeof to === \"string\" ? parsePath(to).pathname : to.pathname;\n}\n/**\n * @private\n */\nconst joinPaths = paths => paths.join(\"/\").replace(/\\/\\/+/g, \"/\");\n/**\n * @private\n */\nconst normalizePathname = pathname => pathname.replace(/\\/+$/, \"\").replace(/^\\/*/, \"/\");\n/**\n * @private\n */\nconst normalizeSearch = search => !search || search === \"?\" ? \"\" : search.startsWith(\"?\") ? search : \"?\" + search;\n/**\n * @private\n */\nconst normalizeHash = hash => !hash || hash === \"#\" ? \"\" : hash.startsWith(\"#\") ? hash : \"#\" + hash;\n/**\n * This is a shortcut for creating `application/json` responses. Converts `data`\n * to JSON and sets the `Content-Type` header.\n */\nconst json = function json(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n let headers = new Headers(responseInit.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n return new Response(JSON.stringify(data), _extends({}, responseInit, {\n headers\n }));\n};\nclass AbortedDeferredError extends Error {}\nclass DeferredData {\n constructor(data, responseInit) {\n this.pendingKeysSet = new Set();\n this.subscribers = new Set();\n this.deferredKeys = [];\n invariant(data && typeof data === \"object\" && !Array.isArray(data), \"defer() only accepts plain objects\");\n // Set up an AbortController + Promise we can race against to exit early\n // cancellation\n let reject;\n this.abortPromise = new Promise((_, r) => reject = r);\n this.controller = new AbortController();\n let onAbort = () => reject(new AbortedDeferredError(\"Deferred data aborted\"));\n this.unlistenAbortSignal = () => this.controller.signal.removeEventListener(\"abort\", onAbort);\n this.controller.signal.addEventListener(\"abort\", onAbort);\n this.data = Object.entries(data).reduce((acc, _ref2) => {\n let [key, value] = _ref2;\n return Object.assign(acc, {\n [key]: this.trackPromise(key, value)\n });\n }, {});\n if (this.done) {\n // All incoming values were resolved\n this.unlistenAbortSignal();\n }\n this.init = responseInit;\n }\n trackPromise(key, value) {\n if (!(value instanceof Promise)) {\n return value;\n }\n this.deferredKeys.push(key);\n this.pendingKeysSet.add(key);\n // We store a little wrapper promise that will be extended with\n // _data/_error props upon resolve/reject\n let promise = Promise.race([value, this.abortPromise]).then(data => this.onSettle(promise, key, undefined, data), error => this.onSettle(promise, key, error));\n // Register rejection listeners to avoid uncaught promise rejections on\n // errors or aborted deferred values\n promise.catch(() => {});\n Object.defineProperty(promise, \"_tracked\", {\n get: () => true\n });\n return promise;\n }\n onSettle(promise, key, error, data) {\n if (this.controller.signal.aborted && error instanceof AbortedDeferredError) {\n this.unlistenAbortSignal();\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n return Promise.reject(error);\n }\n this.pendingKeysSet.delete(key);\n if (this.done) {\n // Nothing left to abort!\n this.unlistenAbortSignal();\n }\n // If the promise was resolved/rejected with undefined, we'll throw an error as you\n // should always resolve with a value or null\n if (error === undefined && data === undefined) {\n let undefinedError = new Error(\"Deferred data for key \\\"\" + key + \"\\\" resolved/rejected with `undefined`, \" + \"you must resolve/reject with a value or `null`.\");\n Object.defineProperty(promise, \"_error\", {\n get: () => undefinedError\n });\n this.emit(false, key);\n return Promise.reject(undefinedError);\n }\n if (data === undefined) {\n Object.defineProperty(promise, \"_error\", {\n get: () => error\n });\n this.emit(false, key);\n return Promise.reject(error);\n }\n Object.defineProperty(promise, \"_data\", {\n get: () => data\n });\n this.emit(false, key);\n return data;\n }\n emit(aborted, settledKey) {\n this.subscribers.forEach(subscriber => subscriber(aborted, settledKey));\n }\n subscribe(fn) {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n cancel() {\n this.controller.abort();\n this.pendingKeysSet.forEach((v, k) => this.pendingKeysSet.delete(k));\n this.emit(true);\n }\n async resolveData(signal) {\n let aborted = false;\n if (!this.done) {\n let onAbort = () => this.cancel();\n signal.addEventListener(\"abort\", onAbort);\n aborted = await new Promise(resolve => {\n this.subscribe(aborted => {\n signal.removeEventListener(\"abort\", onAbort);\n if (aborted || this.done) {\n resolve(aborted);\n }\n });\n });\n }\n return aborted;\n }\n get done() {\n return this.pendingKeysSet.size === 0;\n }\n get unwrappedData() {\n invariant(this.data !== null && this.done, \"Can only unwrap data on initialized and settled deferreds\");\n return Object.entries(this.data).reduce((acc, _ref3) => {\n let [key, value] = _ref3;\n return Object.assign(acc, {\n [key]: unwrapTrackedPromise(value)\n });\n }, {});\n }\n get pendingKeys() {\n return Array.from(this.pendingKeysSet);\n }\n}\nfunction isTrackedPromise(value) {\n return value instanceof Promise && value._tracked === true;\n}\nfunction unwrapTrackedPromise(value) {\n if (!isTrackedPromise(value)) {\n return value;\n }\n if (value._error) {\n throw value._error;\n }\n return value._data;\n}\nconst defer = function defer(data, init) {\n if (init === void 0) {\n init = {};\n }\n let responseInit = typeof init === \"number\" ? {\n status: init\n } : init;\n return new DeferredData(data, responseInit);\n};\n/**\n * A redirect response. Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirect = function redirect(url, init) {\n if (init === void 0) {\n init = 302;\n }\n let responseInit = init;\n if (typeof responseInit === \"number\") {\n responseInit = {\n status: responseInit\n };\n } else if (typeof responseInit.status === \"undefined\") {\n responseInit.status = 302;\n }\n let headers = new Headers(responseInit.headers);\n headers.set(\"Location\", url);\n return new Response(null, _extends({}, responseInit, {\n headers\n }));\n};\n/**\n * A redirect response that will force a document reload to the new location.\n * Sets the status code and the `Location` header.\n * Defaults to \"302 Found\".\n */\nconst redirectDocument = (url, init) => {\n let response = redirect(url, init);\n response.headers.set(\"X-Remix-Reload-Document\", \"true\");\n return response;\n};\n/**\n * @private\n * Utility class we use to hold auto-unwrapped 4xx/5xx Response bodies\n *\n * We don't export the class for public use since it's an implementation\n * detail, but we export the interface above so folks can build their own\n * abstractions around instances via isRouteErrorResponse()\n */\nclass ErrorResponseImpl {\n constructor(status, statusText, data, internal) {\n if (internal === void 0) {\n internal = false;\n }\n this.status = status;\n this.statusText = statusText || \"\";\n this.internal = internal;\n if (data instanceof Error) {\n this.data = data.toString();\n this.error = data;\n } else {\n this.data = data;\n }\n }\n}\n/**\n * Check if the given error is an ErrorResponse generated from a 4xx/5xx\n * Response thrown from an action/loader\n */\nfunction isRouteErrorResponse(error) {\n return error != null && typeof error.status === \"number\" && typeof error.statusText === \"string\" && typeof error.internal === \"boolean\" && \"data\" in error;\n}\n\nconst validMutationMethodsArr = [\"post\", \"put\", \"patch\", \"delete\"];\nconst validMutationMethods = new Set(validMutationMethodsArr);\nconst validRequestMethodsArr = [\"get\", ...validMutationMethodsArr];\nconst validRequestMethods = new Set(validRequestMethodsArr);\nconst redirectStatusCodes = new Set([301, 302, 303, 307, 308]);\nconst redirectPreserveMethodStatusCodes = new Set([307, 308]);\nconst IDLE_NAVIGATION = {\n state: \"idle\",\n location: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_FETCHER = {\n state: \"idle\",\n data: undefined,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n};\nconst IDLE_BLOCKER = {\n state: \"unblocked\",\n proceed: undefined,\n reset: undefined,\n location: undefined\n};\nconst ABSOLUTE_URL_REGEX = /^(?:[a-z][a-z0-9+.-]*:|\\/\\/)/i;\nconst defaultMapRouteProperties = route => ({\n hasErrorBoundary: Boolean(route.hasErrorBoundary)\n});\nconst TRANSITIONS_STORAGE_KEY = \"remix-router-transitions\";\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createRouter\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Create a router and listen to history POP navigations\n */\nfunction createRouter(init) {\n const routerWindow = init.window ? init.window : typeof window !== \"undefined\" ? window : undefined;\n const isBrowser = typeof routerWindow !== \"undefined\" && typeof routerWindow.document !== \"undefined\" && typeof routerWindow.document.createElement !== \"undefined\";\n const isServer = !isBrowser;\n invariant(init.routes.length > 0, \"You must provide a non-empty routes array to createRouter\");\n let mapRouteProperties;\n if (init.mapRouteProperties) {\n mapRouteProperties = init.mapRouteProperties;\n } else if (init.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = init.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Routes keyed by ID\n let manifest = {};\n // Routes in tree format for matching\n let dataRoutes = convertRoutesToDataRoutes(init.routes, mapRouteProperties, undefined, manifest);\n let inFlightDataRoutes;\n let basename = init.basename || \"/\";\n let dataStrategyImpl = init.unstable_dataStrategy || defaultDataStrategy;\n let patchRoutesOnMissImpl = init.unstable_patchRoutesOnMiss;\n // Config driven behavior flags\n let future = _extends({\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_prependBasename: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false\n }, init.future);\n // Cleanup function for history\n let unlistenHistory = null;\n // Externally-provided functions to call on all state changes\n let subscribers = new Set();\n // Externally-provided object to hold scroll restoration locations during routing\n let savedScrollPositions = null;\n // Externally-provided function to get scroll restoration keys\n let getScrollRestorationKey = null;\n // Externally-provided function to get current scroll position\n let getScrollPosition = null;\n // One-time flag to control the initial hydration scroll restoration. Because\n // we don't get the saved positions from until _after_\n // the initial render, we need to manually trigger a separate updateState to\n // send along the restoreScrollPosition\n // Set to true if we have `hydrationData` since we assume we were SSR'd and that\n // SSR did the initial scroll restoration.\n let initialScrollRestored = init.hydrationData != null;\n let initialMatches = matchRoutes(dataRoutes, init.history.location, basename);\n let initialErrors = null;\n if (initialMatches == null && !patchRoutesOnMissImpl) {\n // If we do not match a user-provided-route, fall back to the root\n // to allow the error boundary to take over\n let error = getInternalRouterError(404, {\n pathname: init.history.location.pathname\n });\n let {\n matches,\n route\n } = getShortCircuitMatches(dataRoutes);\n initialMatches = matches;\n initialErrors = {\n [route.id]: error\n };\n }\n // In SPA apps, if the user provided a patchRoutesOnMiss implementation and\n // our initial match is a splat route, clear them out so we run through lazy\n // discovery on hydration in case there's a more accurate lazy route match.\n // In SSR apps (with `hydrationData`), we expect that the server will send\n // up the proper matched routes so we don't want to run lazy discovery on\n // initial hydration and want to hydrate into the splat route.\n if (initialMatches && patchRoutesOnMissImpl && !init.hydrationData) {\n let fogOfWar = checkFogOfWar(initialMatches, dataRoutes, init.history.location.pathname);\n if (fogOfWar.active) {\n initialMatches = null;\n }\n }\n let initialized;\n if (!initialMatches) {\n // We need to run patchRoutesOnMiss in initialize()\n initialized = false;\n initialMatches = [];\n } else if (initialMatches.some(m => m.route.lazy)) {\n // All initialMatches need to be loaded before we're ready. If we have lazy\n // functions around still then we'll need to run them in initialize()\n initialized = false;\n } else if (!initialMatches.some(m => m.route.loader)) {\n // If we've got no loaders to run, then we're good to go\n initialized = true;\n } else if (future.v7_partialHydration) {\n // If partial hydration is enabled, we're initialized so long as we were\n // provided with hydrationData for every route with a loader, and no loaders\n // were marked for explicit hydration\n let loaderData = init.hydrationData ? init.hydrationData.loaderData : null;\n let errors = init.hydrationData ? init.hydrationData.errors : null;\n let isRouteInitialized = m => {\n // No loader, nothing to initialize\n if (!m.route.loader) {\n return true;\n }\n // Explicitly opting-in to running on hydration\n if (typeof m.route.loader === \"function\" && m.route.loader.hydrate === true) {\n return false;\n }\n // Otherwise, initialized if hydrated with data or an error\n return loaderData && loaderData[m.route.id] !== undefined || errors && errors[m.route.id] !== undefined;\n };\n // If errors exist, don't consider routes below the boundary\n if (errors) {\n let idx = initialMatches.findIndex(m => errors[m.route.id] !== undefined);\n initialized = initialMatches.slice(0, idx + 1).every(isRouteInitialized);\n } else {\n initialized = initialMatches.every(isRouteInitialized);\n }\n } else {\n // Without partial hydration - we're initialized if we were provided any\n // hydrationData - which is expected to be complete\n initialized = init.hydrationData != null;\n }\n let router;\n let state = {\n historyAction: init.history.action,\n location: init.history.location,\n matches: initialMatches,\n initialized,\n navigation: IDLE_NAVIGATION,\n // Don't restore on initial updateState() if we were SSR'd\n restoreScrollPosition: init.hydrationData != null ? false : null,\n preventScrollReset: false,\n revalidation: \"idle\",\n loaderData: init.hydrationData && init.hydrationData.loaderData || {},\n actionData: init.hydrationData && init.hydrationData.actionData || null,\n errors: init.hydrationData && init.hydrationData.errors || initialErrors,\n fetchers: new Map(),\n blockers: new Map()\n };\n // -- Stateful internal variables to manage navigations --\n // Current navigation in progress (to be committed in completeNavigation)\n let pendingAction = Action.Pop;\n // Should the current navigation prevent the scroll reset if scroll cannot\n // be restored?\n let pendingPreventScrollReset = false;\n // AbortController for the active navigation\n let pendingNavigationController;\n // Should the current navigation enable document.startViewTransition?\n let pendingViewTransitionEnabled = false;\n // Store applied view transitions so we can apply them on POP\n let appliedViewTransitions = new Map();\n // Cleanup function for persisting applied transitions to sessionStorage\n let removePageHideEventListener = null;\n // We use this to avoid touching history in completeNavigation if a\n // revalidation is entirely uninterrupted\n let isUninterruptedRevalidation = false;\n // Use this internal flag to force revalidation of all loaders:\n // - submissions (completed or interrupted)\n // - useRevalidator()\n // - X-Remix-Revalidate (from redirect)\n let isRevalidationRequired = false;\n // Use this internal array to capture routes that require revalidation due\n // to a cancelled deferred on action submission\n let cancelledDeferredRoutes = [];\n // Use this internal array to capture fetcher loads that were cancelled by an\n // action navigation and require revalidation\n let cancelledFetcherLoads = [];\n // AbortControllers for any in-flight fetchers\n let fetchControllers = new Map();\n // Track loads based on the order in which they started\n let incrementingLoadId = 0;\n // Track the outstanding pending navigation data load to be compared against\n // the globally incrementing load when a fetcher load lands after a completed\n // navigation\n let pendingNavigationLoadId = -1;\n // Fetchers that triggered data reloads as a result of their actions\n let fetchReloadIds = new Map();\n // Fetchers that triggered redirect navigations\n let fetchRedirectIds = new Set();\n // Most recent href/match for fetcher.load calls for fetchers\n let fetchLoadMatches = new Map();\n // Ref-count mounted fetchers so we know when it's ok to clean them up\n let activeFetchers = new Map();\n // Fetchers that have requested a delete when using v7_fetcherPersist,\n // they'll be officially removed after they return to idle\n let deletedFetchers = new Set();\n // Store DeferredData instances for active route matches. When a\n // route loader returns defer() we stick one in here. Then, when a nested\n // promise resolves we update loaderData. If a new navigation starts we\n // cancel active deferreds for eliminated routes.\n let activeDeferreds = new Map();\n // Store blocker functions in a separate Map outside of router state since\n // we don't need to update UI state if they change\n let blockerFunctions = new Map();\n // Map of pending patchRoutesOnMiss() promises (keyed by path/matches) so\n // that we only kick them off once for a given combo\n let pendingPatchRoutes = new Map();\n // Flag to ignore the next history update, so we can revert the URL change on\n // a POP navigation that was blocked by the user without touching router state\n let ignoreNextHistoryUpdate = false;\n // Initialize the router, all side effects should be kicked off from here.\n // Implemented as a Fluent API for ease of:\n // let router = createRouter(init).initialize();\n function initialize() {\n // If history informs us of a POP navigation, start the navigation but do not update\n // state. We'll update our own state once the navigation completes\n unlistenHistory = init.history.listen(_ref => {\n let {\n action: historyAction,\n location,\n delta\n } = _ref;\n // Ignore this event if it was just us resetting the URL from a\n // blocked POP navigation\n if (ignoreNextHistoryUpdate) {\n ignoreNextHistoryUpdate = false;\n return;\n }\n warning(blockerFunctions.size === 0 || delta != null, \"You are trying to use a blocker on a POP navigation to a location \" + \"that was not created by @remix-run/router. This will fail silently in \" + \"production. This can happen if you are navigating outside the router \" + \"via `window.history.pushState`/`window.location.hash` instead of using \" + \"router navigation APIs. This can also happen if you are using \" + \"createHashRouter and the user manually changes the URL.\");\n let blockerKey = shouldBlockNavigation({\n currentLocation: state.location,\n nextLocation: location,\n historyAction\n });\n if (blockerKey && delta != null) {\n // Restore the URL to match the current UI, but don't update router state\n ignoreNextHistoryUpdate = true;\n init.history.go(delta * -1);\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location\n });\n // Re-do the same POP navigation we just blocked\n init.history.go(delta);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return startNavigation(historyAction, location);\n });\n if (isBrowser) {\n // FIXME: This feels gross. How can we cleanup the lines between\n // scrollRestoration/appliedTransitions persistance?\n restoreAppliedTransitions(routerWindow, appliedViewTransitions);\n let _saveAppliedTransitions = () => persistAppliedTransitions(routerWindow, appliedViewTransitions);\n routerWindow.addEventListener(\"pagehide\", _saveAppliedTransitions);\n removePageHideEventListener = () => routerWindow.removeEventListener(\"pagehide\", _saveAppliedTransitions);\n }\n // Kick off initial data load if needed. Use Pop to avoid modifying history\n // Note we don't do any handling of lazy here. For SPA's it'll get handled\n // in the normal navigation flow. For SSR it's expected that lazy modules are\n // resolved prior to router creation since we can't go into a fallbackElement\n // UI for SSR'd apps\n if (!state.initialized) {\n startNavigation(Action.Pop, state.location, {\n initialHydration: true\n });\n }\n return router;\n }\n // Clean up a router and it's side effects\n function dispose() {\n if (unlistenHistory) {\n unlistenHistory();\n }\n if (removePageHideEventListener) {\n removePageHideEventListener();\n }\n subscribers.clear();\n pendingNavigationController && pendingNavigationController.abort();\n state.fetchers.forEach((_, key) => deleteFetcher(key));\n state.blockers.forEach((_, key) => deleteBlocker(key));\n }\n // Subscribe to state updates for the router\n function subscribe(fn) {\n subscribers.add(fn);\n return () => subscribers.delete(fn);\n }\n // Update our state and notify the calling context of the change\n function updateState(newState, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state = _extends({}, state, newState);\n // Prep fetcher cleanup so we can tell the UI which fetcher data entries\n // can be removed\n let completedFetchers = [];\n let deletedFetchersKeys = [];\n if (future.v7_fetcherPersist) {\n state.fetchers.forEach((fetcher, key) => {\n if (fetcher.state === \"idle\") {\n if (deletedFetchers.has(key)) {\n // Unmounted from the UI and can be totally removed\n deletedFetchersKeys.push(key);\n } else {\n // Returned to idle but still mounted in the UI, so semi-remains for\n // revalidations and such\n completedFetchers.push(key);\n }\n }\n });\n }\n // Iterate over a local copy so that if flushSync is used and we end up\n // removing and adding a new subscriber due to the useCallback dependencies,\n // we don't get ourselves into a loop calling the new subscriber immediately\n [...subscribers].forEach(subscriber => subscriber(state, {\n deletedFetchers: deletedFetchersKeys,\n unstable_viewTransitionOpts: opts.viewTransitionOpts,\n unstable_flushSync: opts.flushSync === true\n }));\n // Remove idle fetchers from state since we only care about in-flight fetchers.\n if (future.v7_fetcherPersist) {\n completedFetchers.forEach(key => state.fetchers.delete(key));\n deletedFetchersKeys.forEach(key => deleteFetcher(key));\n }\n }\n // Complete a navigation returning the state.navigation back to the IDLE_NAVIGATION\n // and setting state.[historyAction/location/matches] to the new route.\n // - Location is a required param\n // - Navigation will always be set to IDLE_NAVIGATION\n // - Can pass any other state in newState\n function completeNavigation(location, newState, _temp) {\n var _location$state, _location$state2;\n let {\n flushSync\n } = _temp === void 0 ? {} : _temp;\n // Deduce if we're in a loading/actionReload state:\n // - We have committed actionData in the store\n // - The current navigation was a mutation submission\n // - We're past the submitting state and into the loading state\n // - The location being loaded is not the result of a redirect\n let isActionReload = state.actionData != null && state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && state.navigation.state === \"loading\" && ((_location$state = location.state) == null ? void 0 : _location$state._isRedirect) !== true;\n let actionData;\n if (newState.actionData) {\n if (Object.keys(newState.actionData).length > 0) {\n actionData = newState.actionData;\n } else {\n // Empty actionData -> clear prior actionData due to an action error\n actionData = null;\n }\n } else if (isActionReload) {\n // Keep the current data if we're wrapping up the action reload\n actionData = state.actionData;\n } else {\n // Clear actionData on any other completed navigations\n actionData = null;\n }\n // Always preserve any existing loaderData from re-used routes\n let loaderData = newState.loaderData ? mergeLoaderData(state.loaderData, newState.loaderData, newState.matches || [], newState.errors) : state.loaderData;\n // On a successful navigation we can assume we got through all blockers\n // so we can start fresh\n let blockers = state.blockers;\n if (blockers.size > 0) {\n blockers = new Map(blockers);\n blockers.forEach((_, k) => blockers.set(k, IDLE_BLOCKER));\n }\n // Always respect the user flag. Otherwise don't reset on mutation\n // submission navigations unless they redirect\n let preventScrollReset = pendingPreventScrollReset === true || state.navigation.formMethod != null && isMutationMethod(state.navigation.formMethod) && ((_location$state2 = location.state) == null ? void 0 : _location$state2._isRedirect) !== true;\n // Commit any in-flight routes at the end of the HMR revalidation \"navigation\"\n if (inFlightDataRoutes) {\n dataRoutes = inFlightDataRoutes;\n inFlightDataRoutes = undefined;\n }\n if (isUninterruptedRevalidation) ; else if (pendingAction === Action.Pop) ; else if (pendingAction === Action.Push) {\n init.history.push(location, location.state);\n } else if (pendingAction === Action.Replace) {\n init.history.replace(location, location.state);\n }\n let viewTransitionOpts;\n // On POP, enable transitions if they were enabled on the original navigation\n if (pendingAction === Action.Pop) {\n // Forward takes precedence so they behave like the original navigation\n let priorPaths = appliedViewTransitions.get(state.location.pathname);\n if (priorPaths && priorPaths.has(location.pathname)) {\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n } else if (appliedViewTransitions.has(location.pathname)) {\n // If we don't have a previous forward nav, assume we're popping back to\n // the new location and enable if that location previously enabled\n viewTransitionOpts = {\n currentLocation: location,\n nextLocation: state.location\n };\n }\n } else if (pendingViewTransitionEnabled) {\n // Store the applied transition on PUSH/REPLACE\n let toPaths = appliedViewTransitions.get(state.location.pathname);\n if (toPaths) {\n toPaths.add(location.pathname);\n } else {\n toPaths = new Set([location.pathname]);\n appliedViewTransitions.set(state.location.pathname, toPaths);\n }\n viewTransitionOpts = {\n currentLocation: state.location,\n nextLocation: location\n };\n }\n updateState(_extends({}, newState, {\n actionData,\n loaderData,\n historyAction: pendingAction,\n location,\n initialized: true,\n navigation: IDLE_NAVIGATION,\n revalidation: \"idle\",\n restoreScrollPosition: getSavedScrollPosition(location, newState.matches || state.matches),\n preventScrollReset,\n blockers\n }), {\n viewTransitionOpts,\n flushSync: flushSync === true\n });\n // Reset stateful navigation vars\n pendingAction = Action.Pop;\n pendingPreventScrollReset = false;\n pendingViewTransitionEnabled = false;\n isUninterruptedRevalidation = false;\n isRevalidationRequired = false;\n cancelledDeferredRoutes = [];\n cancelledFetcherLoads = [];\n }\n // Trigger a navigation event, which can either be a numerical POP or a PUSH\n // replace with an optional submission\n async function navigate(to, opts) {\n if (typeof to === \"number\") {\n init.history.go(to);\n return;\n }\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, to, future.v7_relativeSplatPath, opts == null ? void 0 : opts.fromRouteId, opts == null ? void 0 : opts.relative);\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, false, normalizedPath, opts);\n let currentLocation = state.location;\n let nextLocation = createLocation(state.location, path, opts && opts.state);\n // When using navigate as a PUSH/REPLACE we aren't reading an already-encoded\n // URL from window.location, so we need to encode it here so the behavior\n // remains the same as POP and non-data-router usages. new URL() does all\n // the same encoding we'd get from a history.pushState/window.location read\n // without having to touch history\n nextLocation = _extends({}, nextLocation, init.history.encodeLocation(nextLocation));\n let userReplace = opts && opts.replace != null ? opts.replace : undefined;\n let historyAction = Action.Push;\n if (userReplace === true) {\n historyAction = Action.Replace;\n } else if (userReplace === false) ; else if (submission != null && isMutationMethod(submission.formMethod) && submission.formAction === state.location.pathname + state.location.search) {\n // By default on submissions to the current location we REPLACE so that\n // users don't have to double-click the back button to get to the prior\n // location. If the user redirects to a different location from the\n // action/loader this will be ignored and the redirect will be a PUSH\n historyAction = Action.Replace;\n }\n let preventScrollReset = opts && \"preventScrollReset\" in opts ? opts.preventScrollReset === true : undefined;\n let flushSync = (opts && opts.unstable_flushSync) === true;\n let blockerKey = shouldBlockNavigation({\n currentLocation,\n nextLocation,\n historyAction\n });\n if (blockerKey) {\n // Put the blocker into a blocked state\n updateBlocker(blockerKey, {\n state: \"blocked\",\n location: nextLocation,\n proceed() {\n updateBlocker(blockerKey, {\n state: \"proceeding\",\n proceed: undefined,\n reset: undefined,\n location: nextLocation\n });\n // Send the same navigation through\n navigate(to, opts);\n },\n reset() {\n let blockers = new Map(state.blockers);\n blockers.set(blockerKey, IDLE_BLOCKER);\n updateState({\n blockers\n });\n }\n });\n return;\n }\n return await startNavigation(historyAction, nextLocation, {\n submission,\n // Send through the formData serialization error if we have one so we can\n // render at the right error boundary after we match routes\n pendingError: error,\n preventScrollReset,\n replace: opts && opts.replace,\n enableViewTransition: opts && opts.unstable_viewTransition,\n flushSync\n });\n }\n // Revalidate all current loaders. If a navigation is in progress or if this\n // is interrupted by a navigation, allow this to \"succeed\" by calling all\n // loaders during the next loader round\n function revalidate() {\n interruptActiveLoads();\n updateState({\n revalidation: \"loading\"\n });\n // If we're currently submitting an action, we don't need to start a new\n // navigation, we'll just let the follow up loader execution call all loaders\n if (state.navigation.state === \"submitting\") {\n return;\n }\n // If we're currently in an idle state, start a new navigation for the current\n // action/location and mark it as uninterrupted, which will skip the history\n // update in completeNavigation\n if (state.navigation.state === \"idle\") {\n startNavigation(state.historyAction, state.location, {\n startUninterruptedRevalidation: true\n });\n return;\n }\n // Otherwise, if we're currently in a loading state, just start a new\n // navigation to the navigation.location but do not trigger an uninterrupted\n // revalidation so that history correctly updates once the navigation completes\n startNavigation(pendingAction || state.historyAction, state.navigation.location, {\n overrideNavigation: state.navigation\n });\n }\n // Start a navigation to the given action/location. Can optionally provide a\n // overrideNavigation which will override the normalLoad in the case of a redirect\n // navigation\n async function startNavigation(historyAction, location, opts) {\n // Abort any in-progress navigations and start a new one. Unset any ongoing\n // uninterrupted revalidations unless told otherwise, since we want this\n // new navigation to update history normally\n pendingNavigationController && pendingNavigationController.abort();\n pendingNavigationController = null;\n pendingAction = historyAction;\n isUninterruptedRevalidation = (opts && opts.startUninterruptedRevalidation) === true;\n // Save the current scroll position every time we start a new navigation,\n // and track whether we should reset scroll on completion\n saveScrollPosition(state.location, state.matches);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n pendingViewTransitionEnabled = (opts && opts.enableViewTransition) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let loadingNavigation = opts && opts.overrideNavigation;\n let matches = matchRoutes(routesToUse, location, basename);\n let flushSync = (opts && opts.flushSync) === true;\n let fogOfWar = checkFogOfWar(matches, routesToUse, location.pathname);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n // Short circuit with a 404 on the root error boundary if we match nothing\n if (!matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n completeNavigation(location, {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n }, {\n flushSync\n });\n return;\n }\n // Short circuit if it's only a hash change and not a revalidation or\n // mutation submission.\n //\n // Ignore on initial page loads because since the initial load will always\n // be \"same hash\". For example, on /page#hash and submit a
\n // which will default to a navigation to /page\n if (state.initialized && !isRevalidationRequired && isHashChangeOnly(state.location, location) && !(opts && opts.submission && isMutationMethod(opts.submission.formMethod))) {\n completeNavigation(location, {\n matches\n }, {\n flushSync\n });\n return;\n }\n // Create a controller/Request for this navigation\n pendingNavigationController = new AbortController();\n let request = createClientSideRequest(init.history, location, pendingNavigationController.signal, opts && opts.submission);\n let pendingActionResult;\n if (opts && opts.pendingError) {\n // If we have a pendingError, it means the user attempted a GET submission\n // with binary FormData so assign here and skip to handleLoaders. That\n // way we handle calling loaders above the boundary etc. It's not really\n // different from an actionError in that sense.\n pendingActionResult = [findNearestBoundary(matches).route.id, {\n type: ResultType.error,\n error: opts.pendingError\n }];\n } else if (opts && opts.submission && isMutationMethod(opts.submission.formMethod)) {\n // Call action if we received an action submission\n let actionResult = await handleAction(request, location, opts.submission, matches, fogOfWar.active, {\n replace: opts.replace,\n flushSync\n });\n if (actionResult.shortCircuited) {\n return;\n }\n // If we received a 404 from handleAction, it's because we couldn't lazily\n // discover the destination route so we don't want to call loaders\n if (actionResult.pendingActionResult) {\n let [routeId, result] = actionResult.pendingActionResult;\n if (isErrorResult(result) && isRouteErrorResponse(result.error) && result.error.status === 404) {\n pendingNavigationController = null;\n completeNavigation(location, {\n matches: actionResult.matches,\n loaderData: {},\n errors: {\n [routeId]: result.error\n }\n });\n return;\n }\n }\n matches = actionResult.matches || matches;\n pendingActionResult = actionResult.pendingActionResult;\n loadingNavigation = getLoadingNavigation(location, opts.submission);\n flushSync = false;\n // No need to do fog of war matching again on loader execution\n fogOfWar.active = false;\n // Create a GET request for the loaders\n request = createClientSideRequest(init.history, request.url, request.signal);\n }\n // Call loaders\n let {\n shortCircuited,\n matches: updatedMatches,\n loaderData,\n errors\n } = await handleLoaders(request, location, matches, fogOfWar.active, loadingNavigation, opts && opts.submission, opts && opts.fetcherSubmission, opts && opts.replace, opts && opts.initialHydration === true, flushSync, pendingActionResult);\n if (shortCircuited) {\n return;\n }\n // Clean up now that the action/loaders have completed. Don't clean up if\n // we short circuited because pendingNavigationController will have already\n // been assigned to a new controller for the next navigation\n pendingNavigationController = null;\n completeNavigation(location, _extends({\n matches: updatedMatches || matches\n }, getActionDataForCommit(pendingActionResult), {\n loaderData,\n errors\n }));\n }\n // Call the action matched by the leaf route for this navigation and handle\n // redirects/errors\n async function handleAction(request, location, submission, matches, isFogOfWar, opts) {\n if (opts === void 0) {\n opts = {};\n }\n interruptActiveLoads();\n // Put us in a submitting state\n let navigation = getSubmittingNavigation(location, submission);\n updateState({\n navigation\n }, {\n flushSync: opts.flushSync === true\n });\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let {\n boundaryId,\n error\n } = handleDiscoverRouteError(location.pathname, discoverResult);\n return {\n matches: discoverResult.partialMatches,\n pendingActionResult: [boundaryId, {\n type: ResultType.error,\n error\n }]\n };\n } else if (!discoverResult.matches) {\n let {\n notFoundMatches,\n error,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n pendingActionResult: [route.id, {\n type: ResultType.error,\n error\n }]\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n // Call our action and get the result\n let result;\n let actionMatch = getTargetMatch(matches, location);\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n result = {\n type: ResultType.error,\n error: getInternalRouterError(405, {\n method: request.method,\n pathname: location.pathname,\n routeId: actionMatch.route.id\n })\n };\n } else {\n let results = await callDataStrategy(\"action\", request, [actionMatch], matches);\n result = results[0];\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n }\n if (isRedirectResult(result)) {\n let replace;\n if (opts && opts.replace != null) {\n replace = opts.replace;\n } else {\n // If the user didn't explicity indicate replace behavior, replace if\n // we redirected to the exact same location we're currently at to avoid\n // double back-buttons\n let location = normalizeRedirectLocation(result.response.headers.get(\"Location\"), new URL(request.url), basename);\n replace = location === state.location.pathname + state.location.search;\n }\n await startRedirectNavigation(request, result, {\n submission,\n replace\n });\n return {\n shortCircuited: true\n };\n }\n if (isDeferredResult(result)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = findNearestBoundary(matches, actionMatch.route.id);\n // By default, all submissions to the current location are REPLACE\n // navigations, but if the action threw an error that'll be rendered in\n // an errorElement, we fall back to PUSH so that the user can use the\n // back button to get back to the pre-submission form location to try\n // again\n if ((opts && opts.replace) !== true) {\n pendingAction = Action.Push;\n }\n return {\n matches,\n pendingActionResult: [boundaryMatch.route.id, result]\n };\n }\n return {\n matches,\n pendingActionResult: [actionMatch.route.id, result]\n };\n }\n // Call all applicable loaders for the given matches, handling redirects,\n // errors, etc.\n async function handleLoaders(request, location, matches, isFogOfWar, overrideNavigation, submission, fetcherSubmission, replace, initialHydration, flushSync, pendingActionResult) {\n // Figure out the right navigation we want to use for data loading\n let loadingNavigation = overrideNavigation || getLoadingNavigation(location, submission);\n // If this was a redirect from an action we don't have a \"submission\" but\n // we have it on the loading navigation so use that if available\n let activeSubmission = submission || fetcherSubmission || getSubmissionFromNavigation(loadingNavigation);\n // If this is an uninterrupted revalidation, we remain in our current idle\n // state. If not, we need to switch to our loading state and load data,\n // preserving any new action data or existing action data (in the case of\n // a revalidation interrupting an actionReload)\n // If we have partialHydration enabled, then don't update the state for the\n // initial data load since it's not a \"navigation\"\n let shouldUpdateNavigationState = !isUninterruptedRevalidation && (!future.v7_partialHydration || !initialHydration);\n // When fog of war is enabled, we enter our `loading` state earlier so we\n // can discover new routes during the `loading` state. We skip this if\n // we've already run actions since we would have done our matching already.\n // If the children() function threw then, we want to proceed with the\n // partial matches it discovered.\n if (isFogOfWar) {\n if (shouldUpdateNavigationState) {\n let actionData = getUpdatedActionData(pendingActionResult);\n updateState(_extends({\n navigation: loadingNavigation\n }, actionData !== undefined ? {\n actionData\n } : {}), {\n flushSync\n });\n }\n let discoverResult = await discoverRoutes(matches, location.pathname, request.signal);\n if (discoverResult.type === \"aborted\") {\n return {\n shortCircuited: true\n };\n } else if (discoverResult.type === \"error\") {\n let {\n boundaryId,\n error\n } = handleDiscoverRouteError(location.pathname, discoverResult);\n return {\n matches: discoverResult.partialMatches,\n loaderData: {},\n errors: {\n [boundaryId]: error\n }\n };\n } else if (!discoverResult.matches) {\n let {\n error,\n notFoundMatches,\n route\n } = handleNavigational404(location.pathname);\n return {\n matches: notFoundMatches,\n loaderData: {},\n errors: {\n [route.id]: error\n }\n };\n } else {\n matches = discoverResult.matches;\n }\n }\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, activeSubmission, location, future.v7_partialHydration && initialHydration === true, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult);\n // Cancel pending deferreds for no-longer-matched routes or routes we're\n // about to reload. Note that if this is an action reload we would have\n // already cancelled all pending deferreds so this would be a no-op\n cancelActiveDeferreds(routeId => !(matches && matches.some(m => m.route.id === routeId)) || matchesToLoad && matchesToLoad.some(m => m.route.id === routeId));\n pendingNavigationLoadId = ++incrementingLoadId;\n // Short circuit if we have no loaders to run\n if (matchesToLoad.length === 0 && revalidatingFetchers.length === 0) {\n let updatedFetchers = markFetchRedirectsDone();\n completeNavigation(location, _extends({\n matches,\n loaderData: {},\n // Commit pending error if we're short circuiting\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null\n }, getActionDataForCommit(pendingActionResult), updatedFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {}), {\n flushSync\n });\n return {\n shortCircuited: true\n };\n }\n if (shouldUpdateNavigationState) {\n let updates = {};\n if (!isFogOfWar) {\n // Only update navigation/actionNData if we didn't already do it above\n updates.navigation = loadingNavigation;\n let actionData = getUpdatedActionData(pendingActionResult);\n if (actionData !== undefined) {\n updates.actionData = actionData;\n }\n }\n if (revalidatingFetchers.length > 0) {\n updates.fetchers = getUpdatedRevalidatingFetchers(revalidatingFetchers);\n }\n updateState(updates, {\n flushSync\n });\n }\n revalidatingFetchers.forEach(rf => {\n if (fetchControllers.has(rf.key)) {\n abortFetcher(rf.key);\n }\n if (rf.controller) {\n // Fetchers use an independent AbortController so that aborting a fetcher\n // (via deleteFetcher) does not abort the triggering navigation that\n // triggered the revalidation\n fetchControllers.set(rf.key, rf.controller);\n }\n });\n // Proxy navigation abort through to revalidation fetchers\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(f => abortFetcher(f.key));\n if (pendingNavigationController) {\n pendingNavigationController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, request);\n if (request.signal.aborted) {\n return {\n shortCircuited: true\n };\n }\n // Clean up _after_ loaders have completed. Don't clean up if we short\n // circuited because fetchControllers would have been aborted and\n // reassigned to new controllers for the next navigation\n if (pendingNavigationController) {\n pendingNavigationController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n }\n revalidatingFetchers.forEach(rf => fetchControllers.delete(rf.key));\n // If any loaders returned a redirect Response, start a new REPLACE navigation\n let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n await startRedirectNavigation(request, redirect.result, {\n replace\n });\n return {\n shortCircuited: true\n };\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, matches, matchesToLoad, loaderResults, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Wire up subscribers to update loaderData as promises settle\n activeDeferreds.forEach((deferredData, routeId) => {\n deferredData.subscribe(aborted => {\n // Note: No need to updateState here since the TrackedPromise on\n // loaderData is stable across resolve/reject\n // Remove this instance if we were aborted or if promises have settled\n if (aborted || deferredData.done) {\n activeDeferreds.delete(routeId);\n }\n });\n });\n // During partial hydration, preserve SSR errors for routes that don't re-run\n if (future.v7_partialHydration && initialHydration && state.errors) {\n Object.entries(state.errors).filter(_ref2 => {\n let [id] = _ref2;\n return !matchesToLoad.some(m => m.route.id === id);\n }).forEach(_ref3 => {\n let [routeId, error] = _ref3;\n errors = Object.assign(errors || {}, {\n [routeId]: error\n });\n });\n }\n let updatedFetchers = markFetchRedirectsDone();\n let didAbortFetchLoads = abortStaleFetchLoads(pendingNavigationLoadId);\n let shouldUpdateFetchers = updatedFetchers || didAbortFetchLoads || revalidatingFetchers.length > 0;\n return _extends({\n matches,\n loaderData,\n errors\n }, shouldUpdateFetchers ? {\n fetchers: new Map(state.fetchers)\n } : {});\n }\n function getUpdatedActionData(pendingActionResult) {\n if (pendingActionResult && !isErrorResult(pendingActionResult[1])) {\n // This is cast to `any` currently because `RouteData`uses any and it\n // would be a breaking change to use any.\n // TODO: v7 - change `RouteData` to use `unknown` instead of `any`\n return {\n [pendingActionResult[0]]: pendingActionResult[1].data\n };\n } else if (state.actionData) {\n if (Object.keys(state.actionData).length === 0) {\n return null;\n } else {\n return state.actionData;\n }\n }\n }\n function getUpdatedRevalidatingFetchers(revalidatingFetchers) {\n revalidatingFetchers.forEach(rf => {\n let fetcher = state.fetchers.get(rf.key);\n let revalidatingFetcher = getLoadingFetcher(undefined, fetcher ? fetcher.data : undefined);\n state.fetchers.set(rf.key, revalidatingFetcher);\n });\n return new Map(state.fetchers);\n }\n // Trigger a fetcher load/submit for the given fetcher key\n function fetch(key, routeId, href, opts) {\n if (isServer) {\n throw new Error(\"router.fetch() was called during the server render, but it shouldn't be. \" + \"You are likely calling a useFetcher() method in the body of your component. \" + \"Try moving it to a useEffect or a callback.\");\n }\n if (fetchControllers.has(key)) abortFetcher(key);\n let flushSync = (opts && opts.unstable_flushSync) === true;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let normalizedPath = normalizeTo(state.location, state.matches, basename, future.v7_prependBasename, href, future.v7_relativeSplatPath, routeId, opts == null ? void 0 : opts.relative);\n let matches = matchRoutes(routesToUse, normalizedPath, basename);\n let fogOfWar = checkFogOfWar(matches, routesToUse, normalizedPath);\n if (fogOfWar.active && fogOfWar.matches) {\n matches = fogOfWar.matches;\n }\n if (!matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: normalizedPath\n }), {\n flushSync\n });\n return;\n }\n let {\n path,\n submission,\n error\n } = normalizeNavigateOptions(future.v7_normalizeFormMethod, true, normalizedPath, opts);\n if (error) {\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return;\n }\n let match = getTargetMatch(matches, path);\n pendingPreventScrollReset = (opts && opts.preventScrollReset) === true;\n if (submission && isMutationMethod(submission.formMethod)) {\n handleFetcherAction(key, routeId, path, match, matches, fogOfWar.active, flushSync, submission);\n return;\n }\n // Store off the match so we can call it's shouldRevalidate on subsequent\n // revalidations\n fetchLoadMatches.set(key, {\n routeId,\n path\n });\n handleFetcherLoader(key, routeId, path, match, matches, fogOfWar.active, flushSync, submission);\n }\n // Call the action for the matched fetcher.submit(), and then handle redirects,\n // errors, and revalidation\n async function handleFetcherAction(key, routeId, path, match, requestMatches, isFogOfWar, flushSync, submission) {\n interruptActiveLoads();\n fetchLoadMatches.delete(key);\n function detectAndHandle405Error(m) {\n if (!m.route.action && !m.route.lazy) {\n let error = getInternalRouterError(405, {\n method: submission.formMethod,\n pathname: path,\n routeId: routeId\n });\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return true;\n }\n return false;\n }\n if (!isFogOfWar && detectAndHandle405Error(match)) {\n return;\n }\n // Put this fetcher into it's submitting state\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getSubmittingFetcher(submission, existingFetcher), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal, submission);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(requestMatches, path, fetchRequest.signal);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n let {\n error\n } = handleDiscoverRouteError(path, discoverResult);\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n requestMatches = discoverResult.matches;\n match = getTargetMatch(requestMatches, path);\n if (detectAndHandle405Error(match)) {\n return;\n }\n }\n }\n // Call the action for the fetcher\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let actionResults = await callDataStrategy(\"action\", fetchRequest, [match], requestMatches);\n let actionResult = actionResults[0];\n if (fetchRequest.signal.aborted) {\n // We can delete this so long as we weren't aborted by our own fetcher\n // re-submit which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n return;\n }\n // When using v7_fetcherPersist, we don't want errors bubbling up to the UI\n // or redirects processed for unmounted fetchers so we just revert them to\n // idle\n if (future.v7_fetcherPersist && deletedFetchers.has(key)) {\n if (isRedirectResult(actionResult) || isErrorResult(actionResult)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // Let SuccessResult's fall through for revalidation\n } else {\n if (isRedirectResult(actionResult)) {\n fetchControllers.delete(key);\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our action started, so that\n // should take precedence over this redirect navigation. We already\n // set isRevalidationRequired so all loaders for the new route should\n // fire unless opted out via shouldRevalidate\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n updateFetcherState(key, getLoadingFetcher(submission));\n return startRedirectNavigation(fetchRequest, actionResult, {\n fetcherSubmission: submission\n });\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(actionResult)) {\n setFetcherError(key, routeId, actionResult.error);\n return;\n }\n }\n if (isDeferredResult(actionResult)) {\n throw getInternalRouterError(400, {\n type: \"defer-action\"\n });\n }\n // Start the data load for current matches, or the next location if we're\n // in the middle of a navigation\n let nextLocation = state.navigation.location || state.location;\n let revalidationRequest = createClientSideRequest(init.history, nextLocation, abortController.signal);\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let matches = state.navigation.state !== \"idle\" ? matchRoutes(routesToUse, state.navigation.location, basename) : state.matches;\n invariant(matches, \"Didn't find any matches after fetcher action\");\n let loadId = ++incrementingLoadId;\n fetchReloadIds.set(key, loadId);\n let loadFetcher = getLoadingFetcher(submission, actionResult.data);\n state.fetchers.set(key, loadFetcher);\n let [matchesToLoad, revalidatingFetchers] = getMatchesToLoad(init.history, state, matches, submission, nextLocation, false, future.v7_skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, [match.route.id, actionResult]);\n // Put all revalidating fetchers into the loading state, except for the\n // current fetcher which we want to keep in it's current loading state which\n // contains it's action submission info + action data\n revalidatingFetchers.filter(rf => rf.key !== key).forEach(rf => {\n let staleKey = rf.key;\n let existingFetcher = state.fetchers.get(staleKey);\n let revalidatingFetcher = getLoadingFetcher(undefined, existingFetcher ? existingFetcher.data : undefined);\n state.fetchers.set(staleKey, revalidatingFetcher);\n if (fetchControllers.has(staleKey)) {\n abortFetcher(staleKey);\n }\n if (rf.controller) {\n fetchControllers.set(staleKey, rf.controller);\n }\n });\n updateState({\n fetchers: new Map(state.fetchers)\n });\n let abortPendingFetchRevalidations = () => revalidatingFetchers.forEach(rf => abortFetcher(rf.key));\n abortController.signal.addEventListener(\"abort\", abortPendingFetchRevalidations);\n let {\n loaderResults,\n fetcherResults\n } = await callLoadersAndMaybeResolveData(state.matches, matches, matchesToLoad, revalidatingFetchers, revalidationRequest);\n if (abortController.signal.aborted) {\n return;\n }\n abortController.signal.removeEventListener(\"abort\", abortPendingFetchRevalidations);\n fetchReloadIds.delete(key);\n fetchControllers.delete(key);\n revalidatingFetchers.forEach(r => fetchControllers.delete(r.key));\n let redirect = findRedirect([...loaderResults, ...fetcherResults]);\n if (redirect) {\n if (redirect.idx >= matchesToLoad.length) {\n // If this redirect came from a fetcher make sure we mark it in\n // fetchRedirectIds so it doesn't get revalidated on the next set of\n // loader executions\n let fetcherKey = revalidatingFetchers[redirect.idx - matchesToLoad.length].key;\n fetchRedirectIds.add(fetcherKey);\n }\n return startRedirectNavigation(revalidationRequest, redirect.result);\n }\n // Process and commit output from loaders\n let {\n loaderData,\n errors\n } = processLoaderData(state, state.matches, matchesToLoad, loaderResults, undefined, revalidatingFetchers, fetcherResults, activeDeferreds);\n // Since we let revalidations complete even if the submitting fetcher was\n // deleted, only put it back to idle if it hasn't been deleted\n if (state.fetchers.has(key)) {\n let doneFetcher = getDoneFetcher(actionResult.data);\n state.fetchers.set(key, doneFetcher);\n }\n abortStaleFetchLoads(loadId);\n // If we are currently in a navigation loading state and this fetcher is\n // more recent than the navigation, we want the newer data so abort the\n // navigation and complete it with the fetcher data\n if (state.navigation.state === \"loading\" && loadId > pendingNavigationLoadId) {\n invariant(pendingAction, \"Expected pending action\");\n pendingNavigationController && pendingNavigationController.abort();\n completeNavigation(state.navigation.location, {\n matches,\n loaderData,\n errors,\n fetchers: new Map(state.fetchers)\n });\n } else {\n // otherwise just update with the fetcher data, preserving any existing\n // loaderData for loaders that did not need to reload. We have to\n // manually merge here since we aren't going through completeNavigation\n updateState({\n errors,\n loaderData: mergeLoaderData(state.loaderData, loaderData, matches, errors),\n fetchers: new Map(state.fetchers)\n });\n isRevalidationRequired = false;\n }\n }\n // Call the matched loader for fetcher.load(), handling redirects, errors, etc.\n async function handleFetcherLoader(key, routeId, path, match, matches, isFogOfWar, flushSync, submission) {\n let existingFetcher = state.fetchers.get(key);\n updateFetcherState(key, getLoadingFetcher(submission, existingFetcher ? existingFetcher.data : undefined), {\n flushSync\n });\n let abortController = new AbortController();\n let fetchRequest = createClientSideRequest(init.history, path, abortController.signal);\n if (isFogOfWar) {\n let discoverResult = await discoverRoutes(matches, path, fetchRequest.signal);\n if (discoverResult.type === \"aborted\") {\n return;\n } else if (discoverResult.type === \"error\") {\n let {\n error\n } = handleDiscoverRouteError(path, discoverResult);\n setFetcherError(key, routeId, error, {\n flushSync\n });\n return;\n } else if (!discoverResult.matches) {\n setFetcherError(key, routeId, getInternalRouterError(404, {\n pathname: path\n }), {\n flushSync\n });\n return;\n } else {\n matches = discoverResult.matches;\n match = getTargetMatch(matches, path);\n }\n }\n // Call the loader for this fetcher route match\n fetchControllers.set(key, abortController);\n let originatingLoadId = incrementingLoadId;\n let results = await callDataStrategy(\"loader\", fetchRequest, [match], matches);\n let result = results[0];\n // Deferred isn't supported for fetcher loads, await everything and treat it\n // as a normal load. resolveDeferredData will return undefined if this\n // fetcher gets aborted, so we just leave result untouched and short circuit\n // below if that happens\n if (isDeferredResult(result)) {\n result = (await resolveDeferredData(result, fetchRequest.signal, true)) || result;\n }\n // We can delete this so long as we weren't aborted by our our own fetcher\n // re-load which would have put _new_ controller is in fetchControllers\n if (fetchControllers.get(key) === abortController) {\n fetchControllers.delete(key);\n }\n if (fetchRequest.signal.aborted) {\n return;\n }\n // We don't want errors bubbling up or redirects followed for unmounted\n // fetchers, so short circuit here if it was removed from the UI\n if (deletedFetchers.has(key)) {\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n }\n // If the loader threw a redirect Response, start a new REPLACE navigation\n if (isRedirectResult(result)) {\n if (pendingNavigationLoadId > originatingLoadId) {\n // A new navigation was kicked off after our loader started, so that\n // should take precedence over this redirect navigation\n updateFetcherState(key, getDoneFetcher(undefined));\n return;\n } else {\n fetchRedirectIds.add(key);\n await startRedirectNavigation(fetchRequest, result);\n return;\n }\n }\n // Process any non-redirect errors thrown\n if (isErrorResult(result)) {\n setFetcherError(key, routeId, result.error);\n return;\n }\n invariant(!isDeferredResult(result), \"Unhandled fetcher deferred data\");\n // Put the fetcher back into an idle state\n updateFetcherState(key, getDoneFetcher(result.data));\n }\n /**\n * Utility function to handle redirects returned from an action or loader.\n * Normally, a redirect \"replaces\" the navigation that triggered it. So, for\n * example:\n *\n * - user is on /a\n * - user clicks a link to /b\n * - loader for /b redirects to /c\n *\n * In a non-JS app the browser would track the in-flight navigation to /b and\n * then replace it with /c when it encountered the redirect response. In\n * the end it would only ever update the URL bar with /c.\n *\n * In client-side routing using pushState/replaceState, we aim to emulate\n * this behavior and we also do not update history until the end of the\n * navigation (including processed redirects). This means that we never\n * actually touch history until we've processed redirects, so we just use\n * the history action from the original navigation (PUSH or REPLACE).\n */\n async function startRedirectNavigation(request, redirect, _temp2) {\n let {\n submission,\n fetcherSubmission,\n replace\n } = _temp2 === void 0 ? {} : _temp2;\n if (redirect.response.headers.has(\"X-Remix-Revalidate\")) {\n isRevalidationRequired = true;\n }\n let location = redirect.response.headers.get(\"Location\");\n invariant(location, \"Expected a Location header on the redirect Response\");\n location = normalizeRedirectLocation(location, new URL(request.url), basename);\n let redirectLocation = createLocation(state.location, location, {\n _isRedirect: true\n });\n if (isBrowser) {\n let isDocumentReload = false;\n if (redirect.response.headers.has(\"X-Remix-Reload-Document\")) {\n // Hard reload if the response contained X-Remix-Reload-Document\n isDocumentReload = true;\n } else if (ABSOLUTE_URL_REGEX.test(location)) {\n const url = init.history.createURL(location);\n isDocumentReload =\n // Hard reload if it's an absolute URL to a new origin\n url.origin !== routerWindow.location.origin ||\n // Hard reload if it's an absolute URL that does not match our basename\n stripBasename(url.pathname, basename) == null;\n }\n if (isDocumentReload) {\n if (replace) {\n routerWindow.location.replace(location);\n } else {\n routerWindow.location.assign(location);\n }\n return;\n }\n }\n // There's no need to abort on redirects, since we don't detect the\n // redirect until the action/loaders have settled\n pendingNavigationController = null;\n let redirectHistoryAction = replace === true ? Action.Replace : Action.Push;\n // Use the incoming submission if provided, fallback on the active one in\n // state.navigation\n let {\n formMethod,\n formAction,\n formEncType\n } = state.navigation;\n if (!submission && !fetcherSubmission && formMethod && formAction && formEncType) {\n submission = getSubmissionFromNavigation(state.navigation);\n }\n // If this was a 307/308 submission we want to preserve the HTTP method and\n // re-submit the GET/POST/PUT/PATCH/DELETE as a submission navigation to the\n // redirected location\n let activeSubmission = submission || fetcherSubmission;\n if (redirectPreserveMethodStatusCodes.has(redirect.response.status) && activeSubmission && isMutationMethod(activeSubmission.formMethod)) {\n await startNavigation(redirectHistoryAction, redirectLocation, {\n submission: _extends({}, activeSubmission, {\n formAction: location\n }),\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset\n });\n } else {\n // If we have a navigation submission, we will preserve it through the\n // redirect navigation\n let overrideNavigation = getLoadingNavigation(redirectLocation, submission);\n await startNavigation(redirectHistoryAction, redirectLocation, {\n overrideNavigation,\n // Send fetcher submissions through for shouldRevalidate\n fetcherSubmission,\n // Preserve this flag across redirects\n preventScrollReset: pendingPreventScrollReset\n });\n }\n }\n // Utility wrapper for calling dataStrategy client-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, request, matchesToLoad, matches) {\n try {\n let results = await callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties);\n return await Promise.all(results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result;\n return {\n type: ResultType.redirect,\n response: normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath)\n };\n }\n return convertHandlerResultToDataResult(result);\n }));\n } catch (e) {\n // If the outer dataStrategy method throws, just return the error for all\n // matches - and it'll naturally bubble to the root\n return matchesToLoad.map(() => ({\n type: ResultType.error,\n error: e\n }));\n }\n }\n async function callLoadersAndMaybeResolveData(currentMatches, matches, matchesToLoad, fetchersToLoad, request) {\n let [loaderResults, ...fetcherResults] = await Promise.all([matchesToLoad.length ? callDataStrategy(\"loader\", request, matchesToLoad, matches) : [], ...fetchersToLoad.map(f => {\n if (f.matches && f.match && f.controller) {\n let fetcherRequest = createClientSideRequest(init.history, f.path, f.controller.signal);\n return callDataStrategy(\"loader\", fetcherRequest, [f.match], f.matches).then(r => r[0]);\n } else {\n return Promise.resolve({\n type: ResultType.error,\n error: getInternalRouterError(404, {\n pathname: f.path\n })\n });\n }\n })]);\n await Promise.all([resolveDeferredResults(currentMatches, matchesToLoad, loaderResults, loaderResults.map(() => request.signal), false, state.loaderData), resolveDeferredResults(currentMatches, fetchersToLoad.map(f => f.match), fetcherResults, fetchersToLoad.map(f => f.controller ? f.controller.signal : null), true)]);\n return {\n loaderResults,\n fetcherResults\n };\n }\n function interruptActiveLoads() {\n // Every interruption triggers a revalidation\n isRevalidationRequired = true;\n // Cancel pending route-level deferreds and mark cancelled routes for\n // revalidation\n cancelledDeferredRoutes.push(...cancelActiveDeferreds());\n // Abort in-flight fetcher loads\n fetchLoadMatches.forEach((_, key) => {\n if (fetchControllers.has(key)) {\n cancelledFetcherLoads.push(key);\n abortFetcher(key);\n }\n });\n }\n function updateFetcherState(key, fetcher, opts) {\n if (opts === void 0) {\n opts = {};\n }\n state.fetchers.set(key, fetcher);\n updateState({\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function setFetcherError(key, routeId, error, opts) {\n if (opts === void 0) {\n opts = {};\n }\n let boundaryMatch = findNearestBoundary(state.matches, routeId);\n deleteFetcher(key);\n updateState({\n errors: {\n [boundaryMatch.route.id]: error\n },\n fetchers: new Map(state.fetchers)\n }, {\n flushSync: (opts && opts.flushSync) === true\n });\n }\n function getFetcher(key) {\n if (future.v7_fetcherPersist) {\n activeFetchers.set(key, (activeFetchers.get(key) || 0) + 1);\n // If this fetcher was previously marked for deletion, unmark it since we\n // have a new instance\n if (deletedFetchers.has(key)) {\n deletedFetchers.delete(key);\n }\n }\n return state.fetchers.get(key) || IDLE_FETCHER;\n }\n function deleteFetcher(key) {\n let fetcher = state.fetchers.get(key);\n // Don't abort the controller if this is a deletion of a fetcher.submit()\n // in it's loading phase since - we don't want to abort the corresponding\n // revalidation and want them to complete and land\n if (fetchControllers.has(key) && !(fetcher && fetcher.state === \"loading\" && fetchReloadIds.has(key))) {\n abortFetcher(key);\n }\n fetchLoadMatches.delete(key);\n fetchReloadIds.delete(key);\n fetchRedirectIds.delete(key);\n deletedFetchers.delete(key);\n state.fetchers.delete(key);\n }\n function deleteFetcherAndUpdateState(key) {\n if (future.v7_fetcherPersist) {\n let count = (activeFetchers.get(key) || 0) - 1;\n if (count <= 0) {\n activeFetchers.delete(key);\n deletedFetchers.add(key);\n } else {\n activeFetchers.set(key, count);\n }\n } else {\n deleteFetcher(key);\n }\n updateState({\n fetchers: new Map(state.fetchers)\n });\n }\n function abortFetcher(key) {\n let controller = fetchControllers.get(key);\n invariant(controller, \"Expected fetch controller: \" + key);\n controller.abort();\n fetchControllers.delete(key);\n }\n function markFetchersDone(keys) {\n for (let key of keys) {\n let fetcher = getFetcher(key);\n let doneFetcher = getDoneFetcher(fetcher.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n function markFetchRedirectsDone() {\n let doneKeys = [];\n let updatedFetchers = false;\n for (let key of fetchRedirectIds) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n fetchRedirectIds.delete(key);\n doneKeys.push(key);\n updatedFetchers = true;\n }\n }\n markFetchersDone(doneKeys);\n return updatedFetchers;\n }\n function abortStaleFetchLoads(landedId) {\n let yeetedKeys = [];\n for (let [key, id] of fetchReloadIds) {\n if (id < landedId) {\n let fetcher = state.fetchers.get(key);\n invariant(fetcher, \"Expected fetcher: \" + key);\n if (fetcher.state === \"loading\") {\n abortFetcher(key);\n fetchReloadIds.delete(key);\n yeetedKeys.push(key);\n }\n }\n }\n markFetchersDone(yeetedKeys);\n return yeetedKeys.length > 0;\n }\n function getBlocker(key, fn) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n if (blockerFunctions.get(key) !== fn) {\n blockerFunctions.set(key, fn);\n }\n return blocker;\n }\n function deleteBlocker(key) {\n state.blockers.delete(key);\n blockerFunctions.delete(key);\n }\n // Utility function to update blockers, ensuring valid state transitions\n function updateBlocker(key, newBlocker) {\n let blocker = state.blockers.get(key) || IDLE_BLOCKER;\n // Poor mans state machine :)\n // https://mermaid.live/edit#pako:eNqVkc9OwzAMxl8l8nnjAYrEtDIOHEBIgwvKJTReGy3_lDpIqO27k6awMG0XcrLlnz87nwdonESogKXXBuE79rq75XZO3-yHds0RJVuv70YrPlUrCEe2HfrORS3rubqZfuhtpg5C9wk5tZ4VKcRUq88q9Z8RS0-48cE1iHJkL0ugbHuFLus9L6spZy8nX9MP2CNdomVaposqu3fGayT8T8-jJQwhepo_UtpgBQaDEUom04dZhAN1aJBDlUKJBxE1ceB2Smj0Mln-IBW5AFU2dwUiktt_2Qaq2dBfaKdEup85UV7Yd-dKjlnkabl2Pvr0DTkTreM\n invariant(blocker.state === \"unblocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"blocked\" || blocker.state === \"blocked\" && newBlocker.state === \"proceeding\" || blocker.state === \"blocked\" && newBlocker.state === \"unblocked\" || blocker.state === \"proceeding\" && newBlocker.state === \"unblocked\", \"Invalid blocker state transition: \" + blocker.state + \" -> \" + newBlocker.state);\n let blockers = new Map(state.blockers);\n blockers.set(key, newBlocker);\n updateState({\n blockers\n });\n }\n function shouldBlockNavigation(_ref4) {\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = _ref4;\n if (blockerFunctions.size === 0) {\n return;\n }\n // We ony support a single active blocker at the moment since we don't have\n // any compelling use cases for multi-blocker yet\n if (blockerFunctions.size > 1) {\n warning(false, \"A router only supports one blocker at a time\");\n }\n let entries = Array.from(blockerFunctions.entries());\n let [blockerKey, blockerFunction] = entries[entries.length - 1];\n let blocker = state.blockers.get(blockerKey);\n if (blocker && blocker.state === \"proceeding\") {\n // If the blocker is currently proceeding, we don't need to re-check\n // it and can let this navigation continue\n return;\n }\n // At this point, we know we're unblocked/blocked so we need to check the\n // user-provided blocker function\n if (blockerFunction({\n currentLocation,\n nextLocation,\n historyAction\n })) {\n return blockerKey;\n }\n }\n function handleNavigational404(pathname) {\n let error = getInternalRouterError(404, {\n pathname\n });\n let routesToUse = inFlightDataRoutes || dataRoutes;\n let {\n matches,\n route\n } = getShortCircuitMatches(routesToUse);\n // Cancel all pending deferred on 404s since we don't keep any routes\n cancelActiveDeferreds();\n return {\n notFoundMatches: matches,\n route,\n error\n };\n }\n function handleDiscoverRouteError(pathname, discoverResult) {\n return {\n boundaryId: findNearestBoundary(discoverResult.partialMatches).route.id,\n error: getInternalRouterError(400, {\n type: \"route-discovery\",\n pathname,\n message: discoverResult.error != null && \"message\" in discoverResult.error ? discoverResult.error : String(discoverResult.error)\n })\n };\n }\n function cancelActiveDeferreds(predicate) {\n let cancelledRouteIds = [];\n activeDeferreds.forEach((dfd, routeId) => {\n if (!predicate || predicate(routeId)) {\n // Cancel the deferred - but do not remove from activeDeferreds here -\n // we rely on the subscribers to do that so our tests can assert proper\n // cleanup via _internalActiveDeferreds\n dfd.cancel();\n cancelledRouteIds.push(routeId);\n activeDeferreds.delete(routeId);\n }\n });\n return cancelledRouteIds;\n }\n // Opt in to capturing and reporting scroll positions during navigations,\n // used by the component\n function enableScrollRestoration(positions, getPosition, getKey) {\n savedScrollPositions = positions;\n getScrollPosition = getPosition;\n getScrollRestorationKey = getKey || null;\n // Perform initial hydration scroll restoration, since we miss the boat on\n // the initial updateState() because we've not yet rendered \n // and therefore have no savedScrollPositions available\n if (!initialScrollRestored && state.navigation === IDLE_NAVIGATION) {\n initialScrollRestored = true;\n let y = getSavedScrollPosition(state.location, state.matches);\n if (y != null) {\n updateState({\n restoreScrollPosition: y\n });\n }\n }\n return () => {\n savedScrollPositions = null;\n getScrollPosition = null;\n getScrollRestorationKey = null;\n };\n }\n function getScrollKey(location, matches) {\n if (getScrollRestorationKey) {\n let key = getScrollRestorationKey(location, matches.map(m => convertRouteMatchToUiMatch(m, state.loaderData)));\n return key || location.key;\n }\n return location.key;\n }\n function saveScrollPosition(location, matches) {\n if (savedScrollPositions && getScrollPosition) {\n let key = getScrollKey(location, matches);\n savedScrollPositions[key] = getScrollPosition();\n }\n }\n function getSavedScrollPosition(location, matches) {\n if (savedScrollPositions) {\n let key = getScrollKey(location, matches);\n let y = savedScrollPositions[key];\n if (typeof y === \"number\") {\n return y;\n }\n }\n return null;\n }\n function checkFogOfWar(matches, routesToUse, pathname) {\n if (patchRoutesOnMissImpl) {\n if (!matches) {\n let fogMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: fogMatches || []\n };\n } else {\n let leafRoute = matches[matches.length - 1].route;\n if (leafRoute.path && (leafRoute.path === \"*\" || leafRoute.path.endsWith(\"/*\"))) {\n // If we matched a splat, it might only be because we haven't yet fetched\n // the children that would match with a higher score, so let's fetch\n // around and find out\n let partialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n return {\n active: true,\n matches: partialMatches\n };\n }\n }\n }\n return {\n active: false,\n matches: null\n };\n }\n async function discoverRoutes(matches, pathname, signal) {\n let partialMatches = matches;\n let route = partialMatches.length > 0 ? partialMatches[partialMatches.length - 1].route : null;\n while (true) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n try {\n await loadLazyRouteChildren(patchRoutesOnMissImpl, pathname, partialMatches, routesToUse, manifest, mapRouteProperties, pendingPatchRoutes, signal);\n } catch (e) {\n return {\n type: \"error\",\n error: e,\n partialMatches\n };\n } finally {\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity so when we `updateState` at the end of\n // this navigation/fetch `router.routes` will be a new identity and\n // trigger a re-run of memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n }\n }\n if (signal.aborted) {\n return {\n type: \"aborted\"\n };\n }\n let newMatches = matchRoutes(routesToUse, pathname, basename);\n let matchedSplat = false;\n if (newMatches) {\n let leafRoute = newMatches[newMatches.length - 1].route;\n if (leafRoute.index) {\n // If we found an index route, we can stop\n return {\n type: \"success\",\n matches: newMatches\n };\n }\n if (leafRoute.path && leafRoute.path.length > 0) {\n if (leafRoute.path === \"*\") {\n // If we found a splat route, we can't be sure there's not a\n // higher-scoring route down some partial matches trail so we need\n // to check that out\n matchedSplat = true;\n } else {\n // If we found a non-splat route, we can stop\n return {\n type: \"success\",\n matches: newMatches\n };\n }\n }\n }\n let newPartialMatches = matchRoutesImpl(routesToUse, pathname, basename, true);\n // If we are no longer partially matching anything, this was either a\n // legit splat match above, or it's a 404. Also avoid loops if the\n // second pass results in the same partial matches\n if (!newPartialMatches || partialMatches.map(m => m.route.id).join(\"-\") === newPartialMatches.map(m => m.route.id).join(\"-\")) {\n return {\n type: \"success\",\n matches: matchedSplat ? newMatches : null\n };\n }\n partialMatches = newPartialMatches;\n route = partialMatches[partialMatches.length - 1].route;\n if (route.path === \"*\") {\n // The splat is still our most accurate partial, so run with it\n return {\n type: \"success\",\n matches: partialMatches\n };\n }\n }\n }\n function _internalSetRoutes(newRoutes) {\n manifest = {};\n inFlightDataRoutes = convertRoutesToDataRoutes(newRoutes, mapRouteProperties, undefined, manifest);\n }\n function patchRoutes(routeId, children) {\n let isNonHMR = inFlightDataRoutes == null;\n let routesToUse = inFlightDataRoutes || dataRoutes;\n patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties);\n // If we are not in the middle of an HMR revalidation and we changed the\n // routes, provide a new identity and trigger a reflow via `updateState`\n // to re-run memoized `router.routes` dependencies.\n // HMR will already update the identity and reflow when it lands\n // `inFlightDataRoutes` in `completeNavigation`\n if (isNonHMR) {\n dataRoutes = [...dataRoutes];\n updateState({});\n }\n }\n router = {\n get basename() {\n return basename;\n },\n get future() {\n return future;\n },\n get state() {\n return state;\n },\n get routes() {\n return dataRoutes;\n },\n get window() {\n return routerWindow;\n },\n initialize,\n subscribe,\n enableScrollRestoration,\n navigate,\n fetch,\n revalidate,\n // Passthrough to history-aware createHref used by useHref so we get proper\n // hash-aware URLs in DOM paths\n createHref: to => init.history.createHref(to),\n encodeLocation: to => init.history.encodeLocation(to),\n getFetcher,\n deleteFetcher: deleteFetcherAndUpdateState,\n dispose,\n getBlocker,\n deleteBlocker,\n patchRoutes,\n _internalFetchControllers: fetchControllers,\n _internalActiveDeferreds: activeDeferreds,\n // TODO: Remove setRoutes, it's temporary to avoid dealing with\n // updating the tree while validating the update algorithm.\n _internalSetRoutes\n };\n return router;\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region createStaticHandler\n////////////////////////////////////////////////////////////////////////////////\nconst UNSAFE_DEFERRED_SYMBOL = Symbol(\"deferred\");\nfunction createStaticHandler(routes, opts) {\n invariant(routes.length > 0, \"You must provide a non-empty routes array to createStaticHandler\");\n let manifest = {};\n let basename = (opts ? opts.basename : null) || \"/\";\n let mapRouteProperties;\n if (opts != null && opts.mapRouteProperties) {\n mapRouteProperties = opts.mapRouteProperties;\n } else if (opts != null && opts.detectErrorBoundary) {\n // If they are still using the deprecated version, wrap it with the new API\n let detectErrorBoundary = opts.detectErrorBoundary;\n mapRouteProperties = route => ({\n hasErrorBoundary: detectErrorBoundary(route)\n });\n } else {\n mapRouteProperties = defaultMapRouteProperties;\n }\n // Config driven behavior flags\n let future = _extends({\n v7_relativeSplatPath: false,\n v7_throwAbortReason: false\n }, opts ? opts.future : null);\n let dataRoutes = convertRoutesToDataRoutes(routes, mapRouteProperties, undefined, manifest);\n /**\n * The query() method is intended for document requests, in which we want to\n * call an optional action and potentially multiple loaders for all nested\n * routes. It returns a StaticHandlerContext object, which is very similar\n * to the router state (location, loaderData, actionData, errors, etc.) and\n * also adds SSR-specific information such as the statusCode and headers\n * from action/loaders Responses.\n *\n * It _should_ never throw and should report all errors through the\n * returned context.errors object, properly associating errors to their error\n * boundary. Additionally, it tracks _deepestRenderedBoundaryId which can be\n * used to emulate React error boundaries during SSr by performing a second\n * pass only down to the boundaryId.\n *\n * The one exception where we do not return a StaticHandlerContext is when a\n * redirect response is returned or thrown from any action/loader. We\n * propagate that out and return the raw Response so the HTTP server can\n * return it directly.\n *\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n * - `opts.skipLoaderErrorBubbling` is an optional parameter that will prevent\n * the bubbling of errors which allows single-fetch-type implementations\n * where the client will handle the bubbling and we may need to return data\n * for the handling route\n */\n async function query(request, _temp3) {\n let {\n requestContext,\n skipLoaderErrorBubbling,\n unstable_dataStrategy\n } = _temp3 === void 0 ? {} : _temp3;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\") {\n let error = getInternalRouterError(405, {\n method\n });\n let {\n matches: methodNotAllowedMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: methodNotAllowedMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n } else if (!matches) {\n let error = getInternalRouterError(404, {\n pathname: location.pathname\n });\n let {\n matches: notFoundMatches,\n route\n } = getShortCircuitMatches(dataRoutes);\n return {\n basename,\n location,\n matches: notFoundMatches,\n loaderData: {},\n actionData: null,\n errors: {\n [route.id]: error\n },\n statusCode: error.status,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, skipLoaderErrorBubbling === true, null);\n if (isResponse(result)) {\n return result;\n }\n // When returning StaticHandlerContext, we patch back in the location here\n // since we need it for React Context. But this helps keep our submit and\n // loadRouteData operating on a Request instead of a Location\n return _extends({\n location,\n basename\n }, result);\n }\n /**\n * The queryRoute() method is intended for targeted route requests, either\n * for fetch ?_data requests or resource route requests. In this case, we\n * are only ever calling a single action or loader, and we are returning the\n * returned value directly. In most cases, this will be a Response returned\n * from the action/loader, but it may be a primitive or other value as well -\n * and in such cases the calling context should handle that accordingly.\n *\n * We do respect the throw/return differentiation, so if an action/loader\n * throws, then this method will throw the value. This is important so we\n * can do proper boundary identification in Remix where a thrown Response\n * must go to the Catch Boundary but a returned Response is happy-path.\n *\n * One thing to note is that any Router-initiated Errors that make sense\n * to associate with a status code will be thrown as an ErrorResponse\n * instance which include the raw Error, such that the calling context can\n * serialize the error as they see fit while including the proper response\n * code. Examples here are 404 and 405 errors that occur prior to reaching\n * any user-defined loaders.\n *\n * - `opts.routeId` allows you to specify the specific route handler to call.\n * If not provided the handler will determine the proper route by matching\n * against `request.url`\n * - `opts.requestContext` is an optional server context that will be passed\n * to actions/loaders in the `context` parameter\n */\n async function queryRoute(request, _temp4) {\n let {\n routeId,\n requestContext,\n unstable_dataStrategy\n } = _temp4 === void 0 ? {} : _temp4;\n let url = new URL(request.url);\n let method = request.method;\n let location = createLocation(\"\", createPath(url), null, \"default\");\n let matches = matchRoutes(dataRoutes, location, basename);\n // SSR supports HEAD requests while SPA doesn't\n if (!isValidMethod(method) && method !== \"HEAD\" && method !== \"OPTIONS\") {\n throw getInternalRouterError(405, {\n method\n });\n } else if (!matches) {\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let match = routeId ? matches.find(m => m.route.id === routeId) : getTargetMatch(matches, location);\n if (routeId && !match) {\n throw getInternalRouterError(403, {\n pathname: location.pathname,\n routeId\n });\n } else if (!match) {\n // This should never hit I don't think?\n throw getInternalRouterError(404, {\n pathname: location.pathname\n });\n }\n let result = await queryImpl(request, location, matches, requestContext, unstable_dataStrategy || null, false, match);\n if (isResponse(result)) {\n return result;\n }\n let error = result.errors ? Object.values(result.errors)[0] : undefined;\n if (error !== undefined) {\n // If we got back result.errors, that means the loader/action threw\n // _something_ that wasn't a Response, but it's not guaranteed/required\n // to be an `instanceof Error` either, so we have to use throw here to\n // preserve the \"error\" state outside of queryImpl.\n throw error;\n }\n // Pick off the right state value to return\n if (result.actionData) {\n return Object.values(result.actionData)[0];\n }\n if (result.loaderData) {\n var _result$activeDeferre;\n let data = Object.values(result.loaderData)[0];\n if ((_result$activeDeferre = result.activeDeferreds) != null && _result$activeDeferre[match.route.id]) {\n data[UNSAFE_DEFERRED_SYMBOL] = result.activeDeferreds[match.route.id];\n }\n return data;\n }\n return undefined;\n }\n async function queryImpl(request, location, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch) {\n invariant(request.signal, \"query()/queryRoute() requests must contain an AbortController signal\");\n try {\n if (isMutationMethod(request.method.toLowerCase())) {\n let result = await submit(request, matches, routeMatch || getTargetMatch(matches, location), requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch != null);\n return result;\n }\n let result = await loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch);\n return isResponse(result) ? result : _extends({}, result, {\n actionData: null,\n actionHeaders: {}\n });\n } catch (e) {\n // If the user threw/returned a Response in callLoaderOrAction for a\n // `queryRoute` call, we throw the `HandlerResult` to bail out early\n // and then return or throw the raw Response here accordingly\n if (isHandlerResult(e) && isResponse(e.result)) {\n if (e.type === ResultType.error) {\n throw e.result;\n }\n return e.result;\n }\n // Redirects are always returned since they don't propagate to catch\n // boundaries\n if (isRedirectResponse(e)) {\n return e;\n }\n throw e;\n }\n }\n async function submit(request, matches, actionMatch, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, isRouteRequest) {\n let result;\n if (!actionMatch.route.action && !actionMatch.route.lazy) {\n let error = getInternalRouterError(405, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: actionMatch.route.id\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n } else {\n let results = await callDataStrategy(\"action\", request, [actionMatch], matches, isRouteRequest, requestContext, unstable_dataStrategy);\n result = results[0];\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n }\n if (isRedirectResult(result)) {\n // Uhhhh - this should never happen, we should always throw these from\n // callLoaderOrAction, but the type narrowing here keeps TS happy and we\n // can get back on the \"throw all redirect responses\" train here should\n // this ever happen :/\n throw new Response(null, {\n status: result.response.status,\n headers: {\n Location: result.response.headers.get(\"Location\")\n }\n });\n }\n if (isDeferredResult(result)) {\n let error = getInternalRouterError(400, {\n type: \"defer-action\"\n });\n if (isRouteRequest) {\n throw error;\n }\n result = {\n type: ResultType.error,\n error\n };\n }\n if (isRouteRequest) {\n // Note: This should only be non-Response values if we get here, since\n // isRouteRequest should throw any Response received in callLoaderOrAction\n if (isErrorResult(result)) {\n throw result.error;\n }\n return {\n matches: [actionMatch],\n loaderData: {},\n actionData: {\n [actionMatch.route.id]: result.data\n },\n errors: null,\n // Note: statusCode + headers are unused here since queryRoute will\n // return the raw Response or value\n statusCode: 200,\n loaderHeaders: {},\n actionHeaders: {},\n activeDeferreds: null\n };\n }\n // Create a GET request for the loaders\n let loaderRequest = new Request(request.url, {\n headers: request.headers,\n redirect: request.redirect,\n signal: request.signal\n });\n if (isErrorResult(result)) {\n // Store off the pending error - we use it to determine which loaders\n // to call and will commit it when we complete the navigation\n let boundaryMatch = skipLoaderErrorBubbling ? actionMatch : findNearestBoundary(matches, actionMatch.route.id);\n let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null, [boundaryMatch.route.id, result]);\n // action status codes take precedence over loader status codes\n return _extends({}, context, {\n statusCode: isRouteErrorResponse(result.error) ? result.error.status : result.statusCode != null ? result.statusCode : 500,\n actionData: null,\n actionHeaders: _extends({}, result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {})\n });\n }\n let context = await loadRouteData(loaderRequest, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, null);\n return _extends({}, context, {\n actionData: {\n [actionMatch.route.id]: result.data\n }\n }, result.statusCode ? {\n statusCode: result.statusCode\n } : {}, {\n actionHeaders: result.headers ? {\n [actionMatch.route.id]: result.headers\n } : {}\n });\n }\n async function loadRouteData(request, matches, requestContext, unstable_dataStrategy, skipLoaderErrorBubbling, routeMatch, pendingActionResult) {\n let isRouteRequest = routeMatch != null;\n // Short circuit if we have no loaders to run (queryRoute())\n if (isRouteRequest && !(routeMatch != null && routeMatch.route.loader) && !(routeMatch != null && routeMatch.route.lazy)) {\n throw getInternalRouterError(400, {\n method: request.method,\n pathname: new URL(request.url).pathname,\n routeId: routeMatch == null ? void 0 : routeMatch.route.id\n });\n }\n let requestMatches = routeMatch ? [routeMatch] : pendingActionResult && isErrorResult(pendingActionResult[1]) ? getLoaderMatchesUntilBoundary(matches, pendingActionResult[0]) : matches;\n let matchesToLoad = requestMatches.filter(m => m.route.loader || m.route.lazy);\n // Short circuit if we have no loaders to run (query())\n if (matchesToLoad.length === 0) {\n return {\n matches,\n // Add a null for all matched routes for proper revalidation on the client\n loaderData: matches.reduce((acc, m) => Object.assign(acc, {\n [m.route.id]: null\n }), {}),\n errors: pendingActionResult && isErrorResult(pendingActionResult[1]) ? {\n [pendingActionResult[0]]: pendingActionResult[1].error\n } : null,\n statusCode: 200,\n loaderHeaders: {},\n activeDeferreds: null\n };\n }\n let results = await callDataStrategy(\"loader\", request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy);\n if (request.signal.aborted) {\n throwStaticHandlerAbortedError(request, isRouteRequest, future);\n }\n // Process and commit output from loaders\n let activeDeferreds = new Map();\n let context = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling);\n // Add a null for any non-loader matches for proper revalidation on the client\n let executedLoaders = new Set(matchesToLoad.map(match => match.route.id));\n matches.forEach(match => {\n if (!executedLoaders.has(match.route.id)) {\n context.loaderData[match.route.id] = null;\n }\n });\n return _extends({}, context, {\n matches,\n activeDeferreds: activeDeferreds.size > 0 ? Object.fromEntries(activeDeferreds.entries()) : null\n });\n }\n // Utility wrapper for calling dataStrategy server-side without having to\n // pass around the manifest, mapRouteProperties, etc.\n async function callDataStrategy(type, request, matchesToLoad, matches, isRouteRequest, requestContext, unstable_dataStrategy) {\n let results = await callDataStrategyImpl(unstable_dataStrategy || defaultDataStrategy, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext);\n return await Promise.all(results.map((result, i) => {\n if (isRedirectHandlerResult(result)) {\n let response = result.result;\n // Throw redirects and let the server handle them with an HTTP redirect\n throw normalizeRelativeRoutingRedirectResponse(response, request, matchesToLoad[i].route.id, matches, basename, future.v7_relativeSplatPath);\n }\n if (isResponse(result.result) && isRouteRequest) {\n // For SSR single-route requests, we want to hand Responses back\n // directly without unwrapping\n throw result;\n }\n return convertHandlerResultToDataResult(result);\n }));\n }\n return {\n dataRoutes,\n query,\n queryRoute\n };\n}\n//#endregion\n////////////////////////////////////////////////////////////////////////////////\n//#region Helpers\n////////////////////////////////////////////////////////////////////////////////\n/**\n * Given an existing StaticHandlerContext and an error thrown at render time,\n * provide an updated StaticHandlerContext suitable for a second SSR render\n */\nfunction getStaticContextFromError(routes, context, error) {\n let newContext = _extends({}, context, {\n statusCode: isRouteErrorResponse(error) ? error.status : 500,\n errors: {\n [context._deepestRenderedBoundaryId || routes[0].id]: error\n }\n });\n return newContext;\n}\nfunction throwStaticHandlerAbortedError(request, isRouteRequest, future) {\n if (future.v7_throwAbortReason && request.signal.reason !== undefined) {\n throw request.signal.reason;\n }\n let method = isRouteRequest ? \"queryRoute\" : \"query\";\n throw new Error(method + \"() call aborted: \" + request.method + \" \" + request.url);\n}\nfunction isSubmissionNavigation(opts) {\n return opts != null && (\"formData\" in opts && opts.formData != null || \"body\" in opts && opts.body !== undefined);\n}\nfunction normalizeTo(location, matches, basename, prependBasename, to, v7_relativeSplatPath, fromRouteId, relative) {\n let contextualMatches;\n let activeRouteMatch;\n if (fromRouteId) {\n // Grab matches up to the calling route so our route-relative logic is\n // relative to the correct source route\n contextualMatches = [];\n for (let match of matches) {\n contextualMatches.push(match);\n if (match.route.id === fromRouteId) {\n activeRouteMatch = match;\n break;\n }\n }\n } else {\n contextualMatches = matches;\n activeRouteMatch = matches[matches.length - 1];\n }\n // Resolve the relative path\n let path = resolveTo(to ? to : \".\", getResolveToMatches(contextualMatches, v7_relativeSplatPath), stripBasename(location.pathname, basename) || location.pathname, relative === \"path\");\n // When `to` is not specified we inherit search/hash from the current\n // location, unlike when to=\".\" and we just inherit the path.\n // See https://github.com/remix-run/remix/issues/927\n if (to == null) {\n path.search = location.search;\n path.hash = location.hash;\n }\n // Add an ?index param for matched index routes if we don't already have one\n if ((to == null || to === \"\" || to === \".\") && activeRouteMatch && activeRouteMatch.route.index && !hasNakedIndexQuery(path.search)) {\n path.search = path.search ? path.search.replace(/^\\?/, \"?index&\") : \"?index\";\n }\n // If we're operating within a basename, prepend it to the pathname. If\n // this is a root navigation, then just use the raw basename which allows\n // the basename to have full control over the presence of a trailing slash\n // on root actions\n if (prependBasename && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n return createPath(path);\n}\n// Normalize navigation options by converting formMethod=GET formData objects to\n// URLSearchParams so they behave identically to links with query params\nfunction normalizeNavigateOptions(normalizeFormMethod, isFetcher, path, opts) {\n // Return location verbatim on non-submission navigations\n if (!opts || !isSubmissionNavigation(opts)) {\n return {\n path\n };\n }\n if (opts.formMethod && !isValidMethod(opts.formMethod)) {\n return {\n path,\n error: getInternalRouterError(405, {\n method: opts.formMethod\n })\n };\n }\n let getInvalidBodyError = () => ({\n path,\n error: getInternalRouterError(400, {\n type: \"invalid-body\"\n })\n });\n // Create a Submission on non-GET navigations\n let rawFormMethod = opts.formMethod || \"get\";\n let formMethod = normalizeFormMethod ? rawFormMethod.toUpperCase() : rawFormMethod.toLowerCase();\n let formAction = stripHashFromPath(path);\n if (opts.body !== undefined) {\n if (opts.formEncType === \"text/plain\") {\n // text only support POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n let text = typeof opts.body === \"string\" ? opts.body : opts.body instanceof FormData || opts.body instanceof URLSearchParams ?\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data\n Array.from(opts.body.entries()).reduce((acc, _ref5) => {\n let [name, value] = _ref5;\n return \"\" + acc + name + \"=\" + value + \"\\n\";\n }, \"\") : String(opts.body);\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json: undefined,\n text\n }\n };\n } else if (opts.formEncType === \"application/json\") {\n // json only supports POST/PUT/PATCH/DELETE submissions\n if (!isMutationMethod(formMethod)) {\n return getInvalidBodyError();\n }\n try {\n let json = typeof opts.body === \"string\" ? JSON.parse(opts.body) : opts.body;\n return {\n path,\n submission: {\n formMethod,\n formAction,\n formEncType: opts.formEncType,\n formData: undefined,\n json,\n text: undefined\n }\n };\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n }\n invariant(typeof FormData === \"function\", \"FormData is not available in this environment\");\n let searchParams;\n let formData;\n if (opts.formData) {\n searchParams = convertFormDataToSearchParams(opts.formData);\n formData = opts.formData;\n } else if (opts.body instanceof FormData) {\n searchParams = convertFormDataToSearchParams(opts.body);\n formData = opts.body;\n } else if (opts.body instanceof URLSearchParams) {\n searchParams = opts.body;\n formData = convertSearchParamsToFormData(searchParams);\n } else if (opts.body == null) {\n searchParams = new URLSearchParams();\n formData = new FormData();\n } else {\n try {\n searchParams = new URLSearchParams(opts.body);\n formData = convertSearchParamsToFormData(searchParams);\n } catch (e) {\n return getInvalidBodyError();\n }\n }\n let submission = {\n formMethod,\n formAction,\n formEncType: opts && opts.formEncType || \"application/x-www-form-urlencoded\",\n formData,\n json: undefined,\n text: undefined\n };\n if (isMutationMethod(submission.formMethod)) {\n return {\n path,\n submission\n };\n }\n // Flatten submission onto URLSearchParams for GET submissions\n let parsedPath = parsePath(path);\n // On GET navigation submissions we can drop the ?index param from the\n // resulting location since all loaders will run. But fetcher GET submissions\n // only run a single loader so we need to preserve any incoming ?index params\n if (isFetcher && parsedPath.search && hasNakedIndexQuery(parsedPath.search)) {\n searchParams.append(\"index\", \"\");\n }\n parsedPath.search = \"?\" + searchParams;\n return {\n path: createPath(parsedPath),\n submission\n };\n}\n// Filter out all routes below any caught error as they aren't going to\n// render so we don't need to load them\nfunction getLoaderMatchesUntilBoundary(matches, boundaryId) {\n let boundaryMatches = matches;\n if (boundaryId) {\n let index = matches.findIndex(m => m.route.id === boundaryId);\n if (index >= 0) {\n boundaryMatches = matches.slice(0, index);\n }\n }\n return boundaryMatches;\n}\nfunction getMatchesToLoad(history, state, matches, submission, location, isInitialLoad, skipActionErrorRevalidation, isRevalidationRequired, cancelledDeferredRoutes, cancelledFetcherLoads, deletedFetchers, fetchLoadMatches, fetchRedirectIds, routesToUse, basename, pendingActionResult) {\n let actionResult = pendingActionResult ? isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : pendingActionResult[1].data : undefined;\n let currentUrl = history.createURL(state.location);\n let nextUrl = history.createURL(location);\n // Pick navigation matches that are net-new or qualify for revalidation\n let boundaryId = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[0] : undefined;\n let boundaryMatches = boundaryId ? getLoaderMatchesUntilBoundary(matches, boundaryId) : matches;\n // Don't revalidate loaders by default after action 4xx/5xx responses\n // when the flag is enabled. They can still opt-into revalidation via\n // `shouldRevalidate` via `actionResult`\n let actionStatus = pendingActionResult ? pendingActionResult[1].statusCode : undefined;\n let shouldSkipRevalidation = skipActionErrorRevalidation && actionStatus && actionStatus >= 400;\n let navigationMatches = boundaryMatches.filter((match, index) => {\n let {\n route\n } = match;\n if (route.lazy) {\n // We haven't loaded this route yet so we don't know if it's got a loader!\n return true;\n }\n if (route.loader == null) {\n return false;\n }\n if (isInitialLoad) {\n if (typeof route.loader !== \"function\" || route.loader.hydrate) {\n return true;\n }\n return state.loaderData[route.id] === undefined && (\n // Don't re-run if the loader ran and threw an error\n !state.errors || state.errors[route.id] === undefined);\n }\n // Always call the loader on new route instances and pending defer cancellations\n if (isNewLoader(state.loaderData, state.matches[index], match) || cancelledDeferredRoutes.some(id => id === match.route.id)) {\n return true;\n }\n // This is the default implementation for when we revalidate. If the route\n // provides it's own implementation, then we give them full control but\n // provide this value so they can leverage it if needed after they check\n // their own specific use cases\n let currentRouteMatch = state.matches[index];\n let nextRouteMatch = match;\n return shouldRevalidateLoader(match, _extends({\n currentUrl,\n currentParams: currentRouteMatch.params,\n nextUrl,\n nextParams: nextRouteMatch.params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false :\n // Forced revalidation due to submission, useRevalidator, or X-Remix-Revalidate\n isRevalidationRequired || currentUrl.pathname + currentUrl.search === nextUrl.pathname + nextUrl.search ||\n // Search params affect all loaders\n currentUrl.search !== nextUrl.search || isNewRouteInstance(currentRouteMatch, nextRouteMatch)\n }));\n });\n // Pick fetcher.loads that need to be revalidated\n let revalidatingFetchers = [];\n fetchLoadMatches.forEach((f, key) => {\n // Don't revalidate:\n // - on initial load (shouldn't be any fetchers then anyway)\n // - if fetcher won't be present in the subsequent render\n // - no longer matches the URL (v7_fetcherPersist=false)\n // - was unmounted but persisted due to v7_fetcherPersist=true\n if (isInitialLoad || !matches.some(m => m.route.id === f.routeId) || deletedFetchers.has(key)) {\n return;\n }\n let fetcherMatches = matchRoutes(routesToUse, f.path, basename);\n // If the fetcher path no longer matches, push it in with null matches so\n // we can trigger a 404 in callLoadersAndMaybeResolveData. Note this is\n // currently only a use-case for Remix HMR where the route tree can change\n // at runtime and remove a route previously loaded via a fetcher\n if (!fetcherMatches) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: null,\n match: null,\n controller: null\n });\n return;\n }\n // Revalidating fetchers are decoupled from the route matches since they\n // load from a static href. They revalidate based on explicit revalidation\n // (submission, useRevalidator, or X-Remix-Revalidate)\n let fetcher = state.fetchers.get(key);\n let fetcherMatch = getTargetMatch(fetcherMatches, f.path);\n let shouldRevalidate = false;\n if (fetchRedirectIds.has(key)) {\n // Never trigger a revalidation of an actively redirecting fetcher\n shouldRevalidate = false;\n } else if (cancelledFetcherLoads.includes(key)) {\n // Always revalidate if the fetcher was cancelled\n shouldRevalidate = true;\n } else if (fetcher && fetcher.state !== \"idle\" && fetcher.data === undefined) {\n // If the fetcher hasn't ever completed loading yet, then this isn't a\n // revalidation, it would just be a brand new load if an explicit\n // revalidation is required\n shouldRevalidate = isRevalidationRequired;\n } else {\n // Otherwise fall back on any user-defined shouldRevalidate, defaulting\n // to explicit revalidations only\n shouldRevalidate = shouldRevalidateLoader(fetcherMatch, _extends({\n currentUrl,\n currentParams: state.matches[state.matches.length - 1].params,\n nextUrl,\n nextParams: matches[matches.length - 1].params\n }, submission, {\n actionResult,\n actionStatus,\n defaultShouldRevalidate: shouldSkipRevalidation ? false : isRevalidationRequired\n }));\n }\n if (shouldRevalidate) {\n revalidatingFetchers.push({\n key,\n routeId: f.routeId,\n path: f.path,\n matches: fetcherMatches,\n match: fetcherMatch,\n controller: new AbortController()\n });\n }\n });\n return [navigationMatches, revalidatingFetchers];\n}\nfunction isNewLoader(currentLoaderData, currentMatch, match) {\n let isNew =\n // [a] -> [a, b]\n !currentMatch ||\n // [a, b] -> [a, c]\n match.route.id !== currentMatch.route.id;\n // Handle the case that we don't have data for a re-used route, potentially\n // from a prior error or from a cancelled pending deferred\n let isMissingData = currentLoaderData[match.route.id] === undefined;\n // Always load if this is a net-new route or we don't yet have data\n return isNew || isMissingData;\n}\nfunction isNewRouteInstance(currentMatch, match) {\n let currentPath = currentMatch.route.path;\n return (\n // param change for this match, /users/123 -> /users/456\n currentMatch.pathname !== match.pathname ||\n // splat param changed, which is not present in match.path\n // e.g. /files/images/avatar.jpg -> files/finances.xls\n currentPath != null && currentPath.endsWith(\"*\") && currentMatch.params[\"*\"] !== match.params[\"*\"]\n );\n}\nfunction shouldRevalidateLoader(loaderMatch, arg) {\n if (loaderMatch.route.shouldRevalidate) {\n let routeChoice = loaderMatch.route.shouldRevalidate(arg);\n if (typeof routeChoice === \"boolean\") {\n return routeChoice;\n }\n }\n return arg.defaultShouldRevalidate;\n}\n/**\n * Idempotent utility to execute patchRoutesOnMiss() to lazily load route\n * definitions and update the routes/routeManifest\n */\nasync function loadLazyRouteChildren(patchRoutesOnMissImpl, path, matches, routes, manifest, mapRouteProperties, pendingRouteChildren, signal) {\n let key = [path, ...matches.map(m => m.route.id)].join(\"-\");\n try {\n let pending = pendingRouteChildren.get(key);\n if (!pending) {\n pending = patchRoutesOnMissImpl({\n path,\n matches,\n patch: (routeId, children) => {\n if (!signal.aborted) {\n patchRoutesImpl(routeId, children, routes, manifest, mapRouteProperties);\n }\n }\n });\n pendingRouteChildren.set(key, pending);\n }\n if (pending && isPromise(pending)) {\n await pending;\n }\n } finally {\n pendingRouteChildren.delete(key);\n }\n}\nfunction patchRoutesImpl(routeId, children, routesToUse, manifest, mapRouteProperties) {\n if (routeId) {\n var _route$children;\n let route = manifest[routeId];\n invariant(route, \"No route found to patch children into: routeId = \" + routeId);\n let dataChildren = convertRoutesToDataRoutes(children, mapRouteProperties, [routeId, \"patch\", String(((_route$children = route.children) == null ? void 0 : _route$children.length) || \"0\")], manifest);\n if (route.children) {\n route.children.push(...dataChildren);\n } else {\n route.children = dataChildren;\n }\n } else {\n let dataChildren = convertRoutesToDataRoutes(children, mapRouteProperties, [\"patch\", String(routesToUse.length || \"0\")], manifest);\n routesToUse.push(...dataChildren);\n }\n}\n/**\n * Execute route.lazy() methods to lazily load route modules (loader, action,\n * shouldRevalidate) and update the routeManifest in place which shares objects\n * with dataRoutes so those get updated as well.\n */\nasync function loadLazyRouteModule(route, mapRouteProperties, manifest) {\n if (!route.lazy) {\n return;\n }\n let lazyRoute = await route.lazy();\n // If the lazy route function was executed and removed by another parallel\n // call then we can return - first lazy() to finish wins because the return\n // value of lazy is expected to be static\n if (!route.lazy) {\n return;\n }\n let routeToUpdate = manifest[route.id];\n invariant(routeToUpdate, \"No route found in manifest\");\n // Update the route in place. This should be safe because there's no way\n // we could yet be sitting on this route as we can't get there without\n // resolving lazy() first.\n //\n // This is different than the HMR \"update\" use-case where we may actively be\n // on the route being updated. The main concern boils down to \"does this\n // mutation affect any ongoing navigations or any current state.matches\n // values?\". If not, it should be safe to update in place.\n let routeUpdates = {};\n for (let lazyRouteProperty in lazyRoute) {\n let staticRouteValue = routeToUpdate[lazyRouteProperty];\n let isPropertyStaticallyDefined = staticRouteValue !== undefined &&\n // This property isn't static since it should always be updated based\n // on the route updates\n lazyRouteProperty !== \"hasErrorBoundary\";\n warning(!isPropertyStaticallyDefined, \"Route \\\"\" + routeToUpdate.id + \"\\\" has a static property \\\"\" + lazyRouteProperty + \"\\\" \" + \"defined but its lazy function is also returning a value for this property. \" + (\"The lazy route property \\\"\" + lazyRouteProperty + \"\\\" will be ignored.\"));\n if (!isPropertyStaticallyDefined && !immutableRouteKeys.has(lazyRouteProperty)) {\n routeUpdates[lazyRouteProperty] = lazyRoute[lazyRouteProperty];\n }\n }\n // Mutate the route with the provided updates. Do this first so we pass\n // the updated version to mapRouteProperties\n Object.assign(routeToUpdate, routeUpdates);\n // Mutate the `hasErrorBoundary` property on the route based on the route\n // updates and remove the `lazy` function so we don't resolve the lazy\n // route again.\n Object.assign(routeToUpdate, _extends({}, mapRouteProperties(routeToUpdate), {\n lazy: undefined\n }));\n}\n// Default implementation of `dataStrategy` which fetches all loaders in parallel\nfunction defaultDataStrategy(opts) {\n return Promise.all(opts.matches.map(m => m.resolve()));\n}\nasync function callDataStrategyImpl(dataStrategyImpl, type, request, matchesToLoad, matches, manifest, mapRouteProperties, requestContext) {\n let routeIdsToLoad = matchesToLoad.reduce((acc, m) => acc.add(m.route.id), new Set());\n let loadedMatches = new Set();\n // Send all matches here to allow for a middleware-type implementation.\n // handler will be a no-op for unneeded routes and we filter those results\n // back out below.\n let results = await dataStrategyImpl({\n matches: matches.map(match => {\n let shouldLoad = routeIdsToLoad.has(match.route.id);\n // `resolve` encapsulates the route.lazy, executing the\n // loader/action, and mapping return values/thrown errors to a\n // HandlerResult. Users can pass a callback to take fine-grained control\n // over the execution of the loader/action\n let resolve = handlerOverride => {\n loadedMatches.add(match.route.id);\n return shouldLoad ? callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, requestContext) : Promise.resolve({\n type: ResultType.data,\n result: undefined\n });\n };\n return _extends({}, match, {\n shouldLoad,\n resolve\n });\n }),\n request,\n params: matches[0].params,\n context: requestContext\n });\n // Throw if any loadRoute implementations not called since they are what\n // ensures a route is fully loaded\n matches.forEach(m => invariant(loadedMatches.has(m.route.id), \"`match.resolve()` was not called for route id \\\"\" + m.route.id + \"\\\". \" + \"You must call `match.resolve()` on every match passed to \" + \"`dataStrategy` to ensure all routes are properly loaded.\"));\n // Filter out any middleware-only matches for which we didn't need to run handlers\n return results.filter((_, i) => routeIdsToLoad.has(matches[i].route.id));\n}\n// Default logic for calling a loader/action is the user has no specified a dataStrategy\nasync function callLoaderOrAction(type, request, match, manifest, mapRouteProperties, handlerOverride, staticContext) {\n let result;\n let onReject;\n let runHandler = handler => {\n // Setup a promise we can race against so that abort signals short circuit\n let reject;\n // This will never resolve so safe to type it as Promise to\n // satisfy the function return value\n let abortPromise = new Promise((_, r) => reject = r);\n onReject = () => reject();\n request.signal.addEventListener(\"abort\", onReject);\n let actualHandler = ctx => {\n if (typeof handler !== \"function\") {\n return Promise.reject(new Error(\"You cannot call the handler for a route which defines a boolean \" + (\"\\\"\" + type + \"\\\" [routeId: \" + match.route.id + \"]\")));\n }\n return handler({\n request,\n params: match.params,\n context: staticContext\n }, ...(ctx !== undefined ? [ctx] : []));\n };\n let handlerPromise;\n if (handlerOverride) {\n handlerPromise = handlerOverride(ctx => actualHandler(ctx));\n } else {\n handlerPromise = (async () => {\n try {\n let val = await actualHandler();\n return {\n type: \"data\",\n result: val\n };\n } catch (e) {\n return {\n type: \"error\",\n result: e\n };\n }\n })();\n }\n return Promise.race([handlerPromise, abortPromise]);\n };\n try {\n let handler = match.route[type];\n if (match.route.lazy) {\n if (handler) {\n // Run statically defined handler in parallel with lazy()\n let handlerError;\n let [value] = await Promise.all([\n // If the handler throws, don't let it immediately bubble out,\n // since we need to let the lazy() execution finish so we know if this\n // route has a boundary that can handle the error\n runHandler(handler).catch(e => {\n handlerError = e;\n }), loadLazyRouteModule(match.route, mapRouteProperties, manifest)]);\n if (handlerError !== undefined) {\n throw handlerError;\n }\n result = value;\n } else {\n // Load lazy route module, then run any returned handler\n await loadLazyRouteModule(match.route, mapRouteProperties, manifest);\n handler = match.route[type];\n if (handler) {\n // Handler still runs even if we got interrupted to maintain consistency\n // with un-abortable behavior of handler execution on non-lazy or\n // previously-lazy-loaded routes\n result = await runHandler(handler);\n } else if (type === \"action\") {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(405, {\n method: request.method,\n pathname,\n routeId: match.route.id\n });\n } else {\n // lazy() route has no loader to run. Short circuit here so we don't\n // hit the invariant below that errors on returning undefined.\n return {\n type: ResultType.data,\n result: undefined\n };\n }\n }\n } else if (!handler) {\n let url = new URL(request.url);\n let pathname = url.pathname + url.search;\n throw getInternalRouterError(404, {\n pathname\n });\n } else {\n result = await runHandler(handler);\n }\n invariant(result.result !== undefined, \"You defined \" + (type === \"action\" ? \"an action\" : \"a loader\") + \" for route \" + (\"\\\"\" + match.route.id + \"\\\" but didn't return anything from your `\" + type + \"` \") + \"function. Please return a value or `null`.\");\n } catch (e) {\n // We should already be catching and converting normal handler executions to\n // HandlerResults and returning them, so anything that throws here is an\n // unexpected error we still need to wrap\n return {\n type: ResultType.error,\n result: e\n };\n } finally {\n if (onReject) {\n request.signal.removeEventListener(\"abort\", onReject);\n }\n }\n return result;\n}\nasync function convertHandlerResultToDataResult(handlerResult) {\n let {\n result,\n type,\n status\n } = handlerResult;\n if (isResponse(result)) {\n let data;\n try {\n let contentType = result.headers.get(\"Content-Type\");\n // Check between word boundaries instead of startsWith() due to the last\n // paragraph of https://httpwg.org/specs/rfc9110.html#field.content-type\n if (contentType && /\\bapplication\\/json\\b/.test(contentType)) {\n if (result.body == null) {\n data = null;\n } else {\n data = await result.json();\n }\n } else {\n data = await result.text();\n }\n } catch (e) {\n return {\n type: ResultType.error,\n error: e\n };\n }\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: new ErrorResponseImpl(result.status, result.statusText, data),\n statusCode: result.status,\n headers: result.headers\n };\n }\n return {\n type: ResultType.data,\n data,\n statusCode: result.status,\n headers: result.headers\n };\n }\n if (type === ResultType.error) {\n return {\n type: ResultType.error,\n error: result,\n statusCode: isRouteErrorResponse(result) ? result.status : status\n };\n }\n if (isDeferredData(result)) {\n var _result$init, _result$init2;\n return {\n type: ResultType.deferred,\n deferredData: result,\n statusCode: (_result$init = result.init) == null ? void 0 : _result$init.status,\n headers: ((_result$init2 = result.init) == null ? void 0 : _result$init2.headers) && new Headers(result.init.headers)\n };\n }\n return {\n type: ResultType.data,\n data: result,\n statusCode: status\n };\n}\n// Support relative routing in internal redirects\nfunction normalizeRelativeRoutingRedirectResponse(response, request, routeId, matches, basename, v7_relativeSplatPath) {\n let location = response.headers.get(\"Location\");\n invariant(location, \"Redirects returned/thrown from loaders/actions must have a Location header\");\n if (!ABSOLUTE_URL_REGEX.test(location)) {\n let trimmedMatches = matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1);\n location = normalizeTo(new URL(request.url), trimmedMatches, basename, true, location, v7_relativeSplatPath);\n response.headers.set(\"Location\", location);\n }\n return response;\n}\nfunction normalizeRedirectLocation(location, currentUrl, basename) {\n if (ABSOLUTE_URL_REGEX.test(location)) {\n // Strip off the protocol+origin for same-origin + same-basename absolute redirects\n let normalizedLocation = location;\n let url = normalizedLocation.startsWith(\"//\") ? new URL(currentUrl.protocol + normalizedLocation) : new URL(normalizedLocation);\n let isSameBasename = stripBasename(url.pathname, basename) != null;\n if (url.origin === currentUrl.origin && isSameBasename) {\n return url.pathname + url.search + url.hash;\n }\n }\n return location;\n}\n// Utility method for creating the Request instances for loaders/actions during\n// client-side navigations and fetches. During SSR we will always have a\n// Request instance from the static handler (query/queryRoute)\nfunction createClientSideRequest(history, location, signal, submission) {\n let url = history.createURL(stripHashFromPath(location)).toString();\n let init = {\n signal\n };\n if (submission && isMutationMethod(submission.formMethod)) {\n let {\n formMethod,\n formEncType\n } = submission;\n // Didn't think we needed this but it turns out unlike other methods, patch\n // won't be properly normalized to uppercase and results in a 405 error.\n // See: https://fetch.spec.whatwg.org/#concept-method\n init.method = formMethod.toUpperCase();\n if (formEncType === \"application/json\") {\n init.headers = new Headers({\n \"Content-Type\": formEncType\n });\n init.body = JSON.stringify(submission.json);\n } else if (formEncType === \"text/plain\") {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.text;\n } else if (formEncType === \"application/x-www-form-urlencoded\" && submission.formData) {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = convertFormDataToSearchParams(submission.formData);\n } else {\n // Content-Type is inferred (https://fetch.spec.whatwg.org/#dom-request)\n init.body = submission.formData;\n }\n }\n return new Request(url, init);\n}\nfunction convertFormDataToSearchParams(formData) {\n let searchParams = new URLSearchParams();\n for (let [key, value] of formData.entries()) {\n // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#converting-an-entry-list-to-a-list-of-name-value-pairs\n searchParams.append(key, typeof value === \"string\" ? value : value.name);\n }\n return searchParams;\n}\nfunction convertSearchParamsToFormData(searchParams) {\n let formData = new FormData();\n for (let [key, value] of searchParams.entries()) {\n formData.append(key, value);\n }\n return formData;\n}\nfunction processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, skipLoaderErrorBubbling) {\n // Fill in loaderData/errors from our loaders\n let loaderData = {};\n let errors = null;\n let statusCode;\n let foundError = false;\n let loaderHeaders = {};\n let pendingError = pendingActionResult && isErrorResult(pendingActionResult[1]) ? pendingActionResult[1].error : undefined;\n // Process loader results into state.loaderData/state.errors\n results.forEach((result, index) => {\n let id = matchesToLoad[index].route.id;\n invariant(!isRedirectResult(result), \"Cannot handle redirect results in processLoaderData\");\n if (isErrorResult(result)) {\n let error = result.error;\n // If we have a pending action error, we report it at the highest-route\n // that throws a loader error, and then clear it out to indicate that\n // it was consumed\n if (pendingError !== undefined) {\n error = pendingError;\n pendingError = undefined;\n }\n errors = errors || {};\n if (skipLoaderErrorBubbling) {\n errors[id] = error;\n } else {\n // Look upwards from the matched route for the closest ancestor error\n // boundary, defaulting to the root match. Prefer higher error values\n // if lower errors bubble to the same boundary\n let boundaryMatch = findNearestBoundary(matches, id);\n if (errors[boundaryMatch.route.id] == null) {\n errors[boundaryMatch.route.id] = error;\n }\n }\n // Clear our any prior loaderData for the throwing route\n loaderData[id] = undefined;\n // Once we find our first (highest) error, we set the status code and\n // prevent deeper status codes from overriding\n if (!foundError) {\n foundError = true;\n statusCode = isRouteErrorResponse(result.error) ? result.error.status : 500;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n if (isDeferredResult(result)) {\n activeDeferreds.set(id, result.deferredData);\n loaderData[id] = result.deferredData.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode != null && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n } else {\n loaderData[id] = result.data;\n // Error status codes always override success status codes, but if all\n // loaders are successful we take the deepest status code.\n if (result.statusCode && result.statusCode !== 200 && !foundError) {\n statusCode = result.statusCode;\n }\n if (result.headers) {\n loaderHeaders[id] = result.headers;\n }\n }\n }\n });\n // If we didn't consume the pending action error (i.e., all loaders\n // resolved), then consume it here. Also clear out any loaderData for the\n // throwing route\n if (pendingError !== undefined && pendingActionResult) {\n errors = {\n [pendingActionResult[0]]: pendingError\n };\n loaderData[pendingActionResult[0]] = undefined;\n }\n return {\n loaderData,\n errors,\n statusCode: statusCode || 200,\n loaderHeaders\n };\n}\nfunction processLoaderData(state, matches, matchesToLoad, results, pendingActionResult, revalidatingFetchers, fetcherResults, activeDeferreds) {\n let {\n loaderData,\n errors\n } = processRouteLoaderData(matches, matchesToLoad, results, pendingActionResult, activeDeferreds, false // This method is only called client side so we always want to bubble\n );\n // Process results from our revalidating fetchers\n for (let index = 0; index < revalidatingFetchers.length; index++) {\n let {\n key,\n match,\n controller\n } = revalidatingFetchers[index];\n invariant(fetcherResults !== undefined && fetcherResults[index] !== undefined, \"Did not find corresponding fetcher result\");\n let result = fetcherResults[index];\n // Process fetcher non-redirect errors\n if (controller && controller.signal.aborted) {\n // Nothing to do for aborted fetchers\n continue;\n } else if (isErrorResult(result)) {\n let boundaryMatch = findNearestBoundary(state.matches, match == null ? void 0 : match.route.id);\n if (!(errors && errors[boundaryMatch.route.id])) {\n errors = _extends({}, errors, {\n [boundaryMatch.route.id]: result.error\n });\n }\n state.fetchers.delete(key);\n } else if (isRedirectResult(result)) {\n // Should never get here, redirects should get processed above, but we\n // keep this to type narrow to a success result in the else\n invariant(false, \"Unhandled fetcher revalidation redirect\");\n } else if (isDeferredResult(result)) {\n // Should never get here, deferred data should be awaited for fetchers\n // in resolveDeferredResults\n invariant(false, \"Unhandled fetcher deferred data\");\n } else {\n let doneFetcher = getDoneFetcher(result.data);\n state.fetchers.set(key, doneFetcher);\n }\n }\n return {\n loaderData,\n errors\n };\n}\nfunction mergeLoaderData(loaderData, newLoaderData, matches, errors) {\n let mergedLoaderData = _extends({}, newLoaderData);\n for (let match of matches) {\n let id = match.route.id;\n if (newLoaderData.hasOwnProperty(id)) {\n if (newLoaderData[id] !== undefined) {\n mergedLoaderData[id] = newLoaderData[id];\n }\n } else if (loaderData[id] !== undefined && match.route.loader) {\n // Preserve existing keys not included in newLoaderData and where a loader\n // wasn't removed by HMR\n mergedLoaderData[id] = loaderData[id];\n }\n if (errors && errors.hasOwnProperty(id)) {\n // Don't keep any loader data below the boundary\n break;\n }\n }\n return mergedLoaderData;\n}\nfunction getActionDataForCommit(pendingActionResult) {\n if (!pendingActionResult) {\n return {};\n }\n return isErrorResult(pendingActionResult[1]) ? {\n // Clear out prior actionData on errors\n actionData: {}\n } : {\n actionData: {\n [pendingActionResult[0]]: pendingActionResult[1].data\n }\n };\n}\n// Find the nearest error boundary, looking upwards from the leaf route (or the\n// route specified by routeId) for the closest ancestor error boundary,\n// defaulting to the root match\nfunction findNearestBoundary(matches, routeId) {\n let eligibleMatches = routeId ? matches.slice(0, matches.findIndex(m => m.route.id === routeId) + 1) : [...matches];\n return eligibleMatches.reverse().find(m => m.route.hasErrorBoundary === true) || matches[0];\n}\nfunction getShortCircuitMatches(routes) {\n // Prefer a root layout route if present, otherwise shim in a route object\n let route = routes.length === 1 ? routes[0] : routes.find(r => r.index || !r.path || r.path === \"/\") || {\n id: \"__shim-error-route__\"\n };\n return {\n matches: [{\n params: {},\n pathname: \"\",\n pathnameBase: \"\",\n route\n }],\n route\n };\n}\nfunction getInternalRouterError(status, _temp5) {\n let {\n pathname,\n routeId,\n method,\n type,\n message\n } = _temp5 === void 0 ? {} : _temp5;\n let statusText = \"Unknown Server Error\";\n let errorMessage = \"Unknown @remix-run/router error\";\n if (status === 400) {\n statusText = \"Bad Request\";\n if (type === \"route-discovery\") {\n errorMessage = \"Unable to match URL \\\"\" + pathname + \"\\\" - the `unstable_patchRoutesOnMiss()` \" + (\"function threw the following error:\\n\" + message);\n } else if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide a `loader` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (type === \"defer-action\") {\n errorMessage = \"defer() is not supported in actions\";\n } else if (type === \"invalid-body\") {\n errorMessage = \"Unable to encode submission body\";\n }\n } else if (status === 403) {\n statusText = \"Forbidden\";\n errorMessage = \"Route \\\"\" + routeId + \"\\\" does not match URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 404) {\n statusText = \"Not Found\";\n errorMessage = \"No route matches URL \\\"\" + pathname + \"\\\"\";\n } else if (status === 405) {\n statusText = \"Method Not Allowed\";\n if (method && pathname && routeId) {\n errorMessage = \"You made a \" + method.toUpperCase() + \" request to \\\"\" + pathname + \"\\\" but \" + (\"did not provide an `action` for route \\\"\" + routeId + \"\\\", \") + \"so there is no way to handle the request.\";\n } else if (method) {\n errorMessage = \"Invalid request method \\\"\" + method.toUpperCase() + \"\\\"\";\n }\n }\n return new ErrorResponseImpl(status || 500, statusText, new Error(errorMessage), true);\n}\n// Find any returned redirect errors, starting from the lowest match\nfunction findRedirect(results) {\n for (let i = results.length - 1; i >= 0; i--) {\n let result = results[i];\n if (isRedirectResult(result)) {\n return {\n result,\n idx: i\n };\n }\n }\n}\nfunction stripHashFromPath(path) {\n let parsedPath = typeof path === \"string\" ? parsePath(path) : path;\n return createPath(_extends({}, parsedPath, {\n hash: \"\"\n }));\n}\nfunction isHashChangeOnly(a, b) {\n if (a.pathname !== b.pathname || a.search !== b.search) {\n return false;\n }\n if (a.hash === \"\") {\n // /page -> /page#hash\n return b.hash !== \"\";\n } else if (a.hash === b.hash) {\n // /page#hash -> /page#hash\n return true;\n } else if (b.hash !== \"\") {\n // /page#hash -> /page#other\n return true;\n }\n // If the hash is removed the browser will re-perform a request to the server\n // /page#hash -> /page\n return false;\n}\nfunction isPromise(val) {\n return typeof val === \"object\" && val != null && \"then\" in val;\n}\nfunction isHandlerResult(result) {\n return result != null && typeof result === \"object\" && \"type\" in result && \"result\" in result && (result.type === ResultType.data || result.type === ResultType.error);\n}\nfunction isRedirectHandlerResult(result) {\n return isResponse(result.result) && redirectStatusCodes.has(result.result.status);\n}\nfunction isDeferredResult(result) {\n return result.type === ResultType.deferred;\n}\nfunction isErrorResult(result) {\n return result.type === ResultType.error;\n}\nfunction isRedirectResult(result) {\n return (result && result.type) === ResultType.redirect;\n}\nfunction isDeferredData(value) {\n let deferred = value;\n return deferred && typeof deferred === \"object\" && typeof deferred.data === \"object\" && typeof deferred.subscribe === \"function\" && typeof deferred.cancel === \"function\" && typeof deferred.resolveData === \"function\";\n}\nfunction isResponse(value) {\n return value != null && typeof value.status === \"number\" && typeof value.statusText === \"string\" && typeof value.headers === \"object\" && typeof value.body !== \"undefined\";\n}\nfunction isRedirectResponse(result) {\n if (!isResponse(result)) {\n return false;\n }\n let status = result.status;\n let location = result.headers.get(\"Location\");\n return status >= 300 && status <= 399 && location != null;\n}\nfunction isValidMethod(method) {\n return validRequestMethods.has(method.toLowerCase());\n}\nfunction isMutationMethod(method) {\n return validMutationMethods.has(method.toLowerCase());\n}\nasync function resolveDeferredResults(currentMatches, matchesToLoad, results, signals, isFetcher, currentLoaderData) {\n for (let index = 0; index < results.length; index++) {\n let result = results[index];\n let match = matchesToLoad[index];\n // If we don't have a match, then we can have a deferred result to do\n // anything with. This is for revalidating fetchers where the route was\n // removed during HMR\n if (!match) {\n continue;\n }\n let currentMatch = currentMatches.find(m => m.route.id === match.route.id);\n let isRevalidatingLoader = currentMatch != null && !isNewRouteInstance(currentMatch, match) && (currentLoaderData && currentLoaderData[match.route.id]) !== undefined;\n if (isDeferredResult(result) && (isFetcher || isRevalidatingLoader)) {\n // Note: we do not have to touch activeDeferreds here since we race them\n // against the signal in resolveDeferredData and they'll get aborted\n // there if needed\n let signal = signals[index];\n invariant(signal, \"Expected an AbortSignal for revalidating fetcher deferred result\");\n await resolveDeferredData(result, signal, isFetcher).then(result => {\n if (result) {\n results[index] = result || results[index];\n }\n });\n }\n }\n}\nasync function resolveDeferredData(result, signal, unwrap) {\n if (unwrap === void 0) {\n unwrap = false;\n }\n let aborted = await result.deferredData.resolveData(signal);\n if (aborted) {\n return;\n }\n if (unwrap) {\n try {\n return {\n type: ResultType.data,\n data: result.deferredData.unwrappedData\n };\n } catch (e) {\n // Handle any TrackedPromise._error values encountered while unwrapping\n return {\n type: ResultType.error,\n error: e\n };\n }\n }\n return {\n type: ResultType.data,\n data: result.deferredData.data\n };\n}\nfunction hasNakedIndexQuery(search) {\n return new URLSearchParams(search).getAll(\"index\").some(v => v === \"\");\n}\nfunction getTargetMatch(matches, location) {\n let search = typeof location === \"string\" ? parsePath(location).search : location.search;\n if (matches[matches.length - 1].route.index && hasNakedIndexQuery(search || \"\")) {\n // Return the leaf index route when index is present\n return matches[matches.length - 1];\n }\n // Otherwise grab the deepest \"path contributing\" match (ignoring index and\n // pathless layout routes)\n let pathMatches = getPathContributingMatches(matches);\n return pathMatches[pathMatches.length - 1];\n}\nfunction getSubmissionFromNavigation(navigation) {\n let {\n formMethod,\n formAction,\n formEncType,\n text,\n formData,\n json\n } = navigation;\n if (!formMethod || !formAction || !formEncType) {\n return;\n }\n if (text != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json: undefined,\n text\n };\n } else if (formData != null) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData,\n json: undefined,\n text: undefined\n };\n } else if (json !== undefined) {\n return {\n formMethod,\n formAction,\n formEncType,\n formData: undefined,\n json,\n text: undefined\n };\n }\n}\nfunction getLoadingNavigation(location, submission) {\n if (submission) {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n } else {\n let navigation = {\n state: \"loading\",\n location,\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined\n };\n return navigation;\n }\n}\nfunction getSubmittingNavigation(location, submission) {\n let navigation = {\n state: \"submitting\",\n location,\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text\n };\n return navigation;\n}\nfunction getLoadingFetcher(submission, data) {\n if (submission) {\n let fetcher = {\n state: \"loading\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data\n };\n return fetcher;\n } else {\n let fetcher = {\n state: \"loading\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n }\n}\nfunction getSubmittingFetcher(submission, existingFetcher) {\n let fetcher = {\n state: \"submitting\",\n formMethod: submission.formMethod,\n formAction: submission.formAction,\n formEncType: submission.formEncType,\n formData: submission.formData,\n json: submission.json,\n text: submission.text,\n data: existingFetcher ? existingFetcher.data : undefined\n };\n return fetcher;\n}\nfunction getDoneFetcher(data) {\n let fetcher = {\n state: \"idle\",\n formMethod: undefined,\n formAction: undefined,\n formEncType: undefined,\n formData: undefined,\n json: undefined,\n text: undefined,\n data\n };\n return fetcher;\n}\nfunction restoreAppliedTransitions(_window, transitions) {\n try {\n let sessionPositions = _window.sessionStorage.getItem(TRANSITIONS_STORAGE_KEY);\n if (sessionPositions) {\n let json = JSON.parse(sessionPositions);\n for (let [k, v] of Object.entries(json || {})) {\n if (v && Array.isArray(v)) {\n transitions.set(k, new Set(v || []));\n }\n }\n }\n } catch (e) {\n // no-op, use default empty object\n }\n}\nfunction persistAppliedTransitions(_window, transitions) {\n if (transitions.size > 0) {\n let json = {};\n for (let [k, v] of transitions) {\n json[k] = [...v];\n }\n try {\n _window.sessionStorage.setItem(TRANSITIONS_STORAGE_KEY, JSON.stringify(json));\n } catch (error) {\n warning(false, \"Failed to save applied view transitions in sessionStorage (\" + error + \").\");\n }\n }\n}\n//#endregion\n\nexport { AbortedDeferredError, Action, IDLE_BLOCKER, IDLE_FETCHER, IDLE_NAVIGATION, UNSAFE_DEFERRED_SYMBOL, DeferredData as UNSAFE_DeferredData, ErrorResponseImpl as UNSAFE_ErrorResponseImpl, convertRouteMatchToUiMatch as UNSAFE_convertRouteMatchToUiMatch, convertRoutesToDataRoutes as UNSAFE_convertRoutesToDataRoutes, decodePath as UNSAFE_decodePath, getResolveToMatches as UNSAFE_getResolveToMatches, invariant as UNSAFE_invariant, warning as UNSAFE_warning, createBrowserHistory, createHashHistory, createMemoryHistory, createPath, createRouter, createStaticHandler, defer, generatePath, getStaticContextFromError, getToPathname, isDeferredData, isRouteErrorResponse, joinPaths, json, matchPath, matchRoutes, normalizePathname, parsePath, redirect, redirectDocument, resolvePath, resolveTo, stripBasename };\n//# sourceMappingURL=router.js.map\n","/**\n * React Router v6.25.0\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\nimport * as React from 'react';\nimport { UNSAFE_invariant, joinPaths, matchPath, UNSAFE_decodePath, UNSAFE_getResolveToMatches, UNSAFE_warning, resolveTo, parsePath, matchRoutes, Action, UNSAFE_convertRouteMatchToUiMatch, stripBasename, IDLE_BLOCKER, isRouteErrorResponse, createMemoryHistory, AbortedDeferredError, createRouter } from '@remix-run/router';\nexport { AbortedDeferredError, Action as NavigationType, createPath, defer, generatePath, isRouteErrorResponse, json, matchPath, matchRoutes, parsePath, redirect, redirectDocument, resolvePath } from '@remix-run/router';\n\nfunction _extends() {\n _extends = Object.assign ? Object.assign.bind() : function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n return target;\n };\n return _extends.apply(this, arguments);\n}\n\n// Create react-specific types from the agnostic types in @remix-run/router to\n// export from react-router\nconst DataRouterContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterContext.displayName = \"DataRouter\";\n}\nconst DataRouterStateContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n DataRouterStateContext.displayName = \"DataRouterState\";\n}\nconst AwaitContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n AwaitContext.displayName = \"Await\";\n}\n\n/**\n * A Navigator is a \"location changer\"; it's how you get to different locations.\n *\n * Every history instance conforms to the Navigator interface, but the\n * distinction is useful primarily when it comes to the low-level `` API\n * where both the location and a navigator must be provided separately in order\n * to avoid \"tearing\" that may occur in a suspense-enabled app if the action\n * and/or location were to be read directly from the history instance.\n */\n\nconst NavigationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n NavigationContext.displayName = \"Navigation\";\n}\nconst LocationContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n LocationContext.displayName = \"Location\";\n}\nconst RouteContext = /*#__PURE__*/React.createContext({\n outlet: null,\n matches: [],\n isDataRoute: false\n});\nif (process.env.NODE_ENV !== \"production\") {\n RouteContext.displayName = \"Route\";\n}\nconst RouteErrorContext = /*#__PURE__*/React.createContext(null);\nif (process.env.NODE_ENV !== \"production\") {\n RouteErrorContext.displayName = \"RouteError\";\n}\n\n/**\n * Returns the full href for the given \"to\" value. This is useful for building\n * custom links that are also accessible and preserve right-click behavior.\n *\n * @see https://reactrouter.com/hooks/use-href\n */\nfunction useHref(to, _temp) {\n let {\n relative\n } = _temp === void 0 ? {} : _temp;\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useHref() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n basename,\n navigator\n } = React.useContext(NavigationContext);\n let {\n hash,\n pathname,\n search\n } = useResolvedPath(to, {\n relative\n });\n let joinedPathname = pathname;\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to creating the href. If this is a root navigation, then just use the raw\n // basename which allows the basename to have full control over the presence\n // of a trailing slash on root links\n if (basename !== \"/\") {\n joinedPathname = pathname === \"/\" ? basename : joinPaths([basename, pathname]);\n }\n return navigator.createHref({\n pathname: joinedPathname,\n search,\n hash\n });\n}\n\n/**\n * Returns true if this component is a descendant of a ``.\n *\n * @see https://reactrouter.com/hooks/use-in-router-context\n */\nfunction useInRouterContext() {\n return React.useContext(LocationContext) != null;\n}\n\n/**\n * Returns the current location object, which represents the current URL in web\n * browsers.\n *\n * Note: If you're using this it may mean you're doing some of your own\n * \"routing\" in your app, and we'd like to know what your use case is. We may\n * be able to provide something higher-level to better suit your needs.\n *\n * @see https://reactrouter.com/hooks/use-location\n */\nfunction useLocation() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useLocation() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n return React.useContext(LocationContext).location;\n}\n\n/**\n * Returns the current navigation action which describes how the router came to\n * the current location, either by a pop, push, or replace on the history stack.\n *\n * @see https://reactrouter.com/hooks/use-navigation-type\n */\nfunction useNavigationType() {\n return React.useContext(LocationContext).navigationType;\n}\n\n/**\n * Returns a PathMatch object if the given pattern matches the current URL.\n * This is useful for components that need to know \"active\" state, e.g.\n * ``.\n *\n * @see https://reactrouter.com/hooks/use-match\n */\nfunction useMatch(pattern) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useMatch() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n pathname\n } = useLocation();\n return React.useMemo(() => matchPath(pattern, UNSAFE_decodePath(pathname)), [pathname, pattern]);\n}\n\n/**\n * The interface for the navigate() function returned from useNavigate().\n */\n\nconst navigateEffectWarning = \"You should call navigate() in a React.useEffect(), not when \" + \"your component is first rendered.\";\n\n// Mute warnings for calls to useNavigate in SSR environments\nfunction useIsomorphicLayoutEffect(cb) {\n let isStatic = React.useContext(NavigationContext).static;\n if (!isStatic) {\n // We should be able to get rid of this once react 18.3 is released\n // See: https://github.com/facebook/react/pull/26395\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useLayoutEffect(cb);\n }\n}\n\n/**\n * Returns an imperative method for changing the location. Used by ``s, but\n * may also be used by other elements to change the location.\n *\n * @see https://reactrouter.com/hooks/use-navigate\n */\nfunction useNavigate() {\n let {\n isDataRoute\n } = React.useContext(RouteContext);\n // Conditional usage is OK here because the usage of a data router is static\n // eslint-disable-next-line react-hooks/rules-of-hooks\n return isDataRoute ? useNavigateStable() : useNavigateUnstable();\n}\nfunction useNavigateUnstable() {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useNavigate() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let dataRouterContext = React.useContext(DataRouterContext);\n let {\n basename,\n future,\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our history listener yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n navigator.go(to);\n return;\n }\n let path = resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, options.relative === \"path\");\n\n // If we're operating within a basename, prepend it to the pathname prior\n // to handing off to history (but only if we're not in a data router,\n // otherwise it'll prepend the basename inside of the router).\n // If this is a root navigation, then we navigate to the raw basename\n // which allows the basename to have full control over the presence of a\n // trailing slash on root links\n if (dataRouterContext == null && basename !== \"/\") {\n path.pathname = path.pathname === \"/\" ? basename : joinPaths([basename, path.pathname]);\n }\n (!!options.replace ? navigator.replace : navigator.push)(path, options.state, options);\n }, [basename, navigator, routePathnamesJson, locationPathname, dataRouterContext]);\n return navigate;\n}\nconst OutletContext = /*#__PURE__*/React.createContext(null);\n\n/**\n * Returns the context (if provided) for the child route at this level of the route\n * hierarchy.\n * @see https://reactrouter.com/hooks/use-outlet-context\n */\nfunction useOutletContext() {\n return React.useContext(OutletContext);\n}\n\n/**\n * Returns the element for the child route at this level of the route\n * hierarchy. Used internally by `` to render child routes.\n *\n * @see https://reactrouter.com/hooks/use-outlet\n */\nfunction useOutlet(context) {\n let outlet = React.useContext(RouteContext).outlet;\n if (outlet) {\n return /*#__PURE__*/React.createElement(OutletContext.Provider, {\n value: context\n }, outlet);\n }\n return outlet;\n}\n\n/**\n * Returns an object of key/value pairs of the dynamic params from the current\n * URL that were matched by the route path.\n *\n * @see https://reactrouter.com/hooks/use-params\n */\nfunction useParams() {\n let {\n matches\n } = React.useContext(RouteContext);\n let routeMatch = matches[matches.length - 1];\n return routeMatch ? routeMatch.params : {};\n}\n\n/**\n * Resolves the pathname of the given `to` value against the current location.\n *\n * @see https://reactrouter.com/hooks/use-resolved-path\n */\nfunction useResolvedPath(to, _temp2) {\n let {\n relative\n } = _temp2 === void 0 ? {} : _temp2;\n let {\n future\n } = React.useContext(NavigationContext);\n let {\n matches\n } = React.useContext(RouteContext);\n let {\n pathname: locationPathname\n } = useLocation();\n let routePathnamesJson = JSON.stringify(UNSAFE_getResolveToMatches(matches, future.v7_relativeSplatPath));\n return React.useMemo(() => resolveTo(to, JSON.parse(routePathnamesJson), locationPathname, relative === \"path\"), [to, routePathnamesJson, locationPathname, relative]);\n}\n\n/**\n * Returns the element of the route that matched the current location, prepared\n * with the correct context to render the remainder of the route tree. Route\n * elements in the tree must render an `` to render their child route's\n * element.\n *\n * @see https://reactrouter.com/hooks/use-routes\n */\nfunction useRoutes(routes, locationArg) {\n return useRoutesImpl(routes, locationArg);\n}\n\n// Internal implementation with accept optional param for RouterProvider usage\nfunction useRoutesImpl(routes, locationArg, dataRouterState, future) {\n !useInRouterContext() ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, // TODO: This error is probably because they somehow have 2 versions of the\n // router loaded. We can help them understand how to avoid that.\n \"useRoutes() may be used only in the context of a component.\") : UNSAFE_invariant(false) : void 0;\n let {\n navigator\n } = React.useContext(NavigationContext);\n let {\n matches: parentMatches\n } = React.useContext(RouteContext);\n let routeMatch = parentMatches[parentMatches.length - 1];\n let parentParams = routeMatch ? routeMatch.params : {};\n let parentPathname = routeMatch ? routeMatch.pathname : \"/\";\n let parentPathnameBase = routeMatch ? routeMatch.pathnameBase : \"/\";\n let parentRoute = routeMatch && routeMatch.route;\n if (process.env.NODE_ENV !== \"production\") {\n // You won't get a warning about 2 different under a \n // without a trailing *, but this is a best-effort warning anyway since we\n // cannot even give the warning unless they land at the parent route.\n //\n // Example:\n //\n // \n // {/* This route path MUST end with /* because otherwise\n // it will never match /blog/post/123 */}\n // } />\n // } />\n // \n //\n // function Blog() {\n // return (\n // \n // } />\n // \n // );\n // }\n let parentPath = parentRoute && parentRoute.path || \"\";\n warningOnce(parentPathname, !parentRoute || parentPath.endsWith(\"*\"), \"You rendered descendant (or called `useRoutes()`) at \" + (\"\\\"\" + parentPathname + \"\\\" (under ) 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 to .\"));\n }\n let locationFromContext = useLocation();\n let location;\n if (locationArg) {\n var _parsedLocationArg$pa;\n let parsedLocationArg = typeof locationArg === \"string\" ? parsePath(locationArg) : locationArg;\n !(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 `` 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;\n location = parsedLocationArg;\n } else {\n location = locationFromContext;\n }\n let pathname = location.pathname || \"/\";\n let remainingPathname = pathname;\n if (parentPathnameBase !== \"/\") {\n // Determine the remaining pathname by removing the # of URL segments the\n // parentPathnameBase has, instead of removing based on character count.\n // This is because we can't guarantee that incoming/outgoing encodings/\n // decodings will match exactly.\n // We decode paths before matching on a per-segment basis with\n // decodeURIComponent(), but we re-encode pathnames via `new URL()` so they\n // match what `window.location.pathname` would reflect. Those don't 100%\n // align when it comes to encoded URI characters such as % and &.\n //\n // So we may end up with:\n // pathname: \"/descendant/a%25b/match\"\n // parentPathnameBase: \"/descendant/a%b\"\n //\n // And the direct substring removal approach won't work :/\n let parentSegments = parentPathnameBase.replace(/^\\//, \"\").split(\"/\");\n let segments = pathname.replace(/^\\//, \"\").split(\"/\");\n remainingPathname = \"/\" + segments.slice(parentSegments.length).join(\"/\");\n }\n let matches = matchRoutes(routes, {\n pathname: remainingPathname\n });\n if (process.env.NODE_ENV !== \"production\") {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(parentRoute || matches != null, \"No routes matched location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \") : void 0;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(matches == null || matches[matches.length - 1].route.element !== undefined || matches[matches.length - 1].route.Component !== undefined || matches[matches.length - 1].route.lazy !== undefined, \"Matched leaf route at location \\\"\" + location.pathname + location.search + location.hash + \"\\\" \" + \"does not have an element or Component. This means it will render an with a \" + \"null value by default resulting in an \\\"empty\\\" page.\") : void 0;\n }\n let renderedMatches = _renderMatches(matches && matches.map(match => Object.assign({}, match, {\n params: Object.assign({}, parentParams, match.params),\n pathname: joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathname).pathname : match.pathname]),\n pathnameBase: match.pathnameBase === \"/\" ? parentPathnameBase : joinPaths([parentPathnameBase,\n // Re-encode pathnames that were decoded inside matchRoutes\n navigator.encodeLocation ? navigator.encodeLocation(match.pathnameBase).pathname : match.pathnameBase])\n })), parentMatches, dataRouterState, future);\n\n // When a user passes in a `locationArg`, the associated routes need to\n // be wrapped in a new `LocationContext.Provider` in order for `useLocation`\n // to use the scoped location instead of the global location.\n if (locationArg && renderedMatches) {\n return /*#__PURE__*/React.createElement(LocationContext.Provider, {\n value: {\n location: _extends({\n pathname: \"/\",\n search: \"\",\n hash: \"\",\n state: null,\n key: \"default\"\n }, location),\n navigationType: Action.Pop\n }\n }, renderedMatches);\n }\n return renderedMatches;\n}\nfunction DefaultErrorComponent() {\n let error = useRouteError();\n let message = isRouteErrorResponse(error) ? error.status + \" \" + error.statusText : error instanceof Error ? error.message : JSON.stringify(error);\n let stack = error instanceof Error ? error.stack : null;\n let lightgrey = \"rgba(200,200,200, 0.5)\";\n let preStyles = {\n padding: \"0.5rem\",\n backgroundColor: lightgrey\n };\n let codeStyles = {\n padding: \"2px 4px\",\n backgroundColor: lightgrey\n };\n let devInfo = null;\n if (process.env.NODE_ENV !== \"production\") {\n console.error(\"Error handled by React Router default ErrorBoundary:\", error);\n 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 \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"ErrorBoundary\"), \" or\", \" \", /*#__PURE__*/React.createElement(\"code\", {\n style: codeStyles\n }, \"errorElement\"), \" prop on your route.\"));\n }\n return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(\"h2\", null, \"Unexpected Application Error!\"), /*#__PURE__*/React.createElement(\"h3\", {\n style: {\n fontStyle: \"italic\"\n }\n }, message), stack ? /*#__PURE__*/React.createElement(\"pre\", {\n style: preStyles\n }, stack) : null, devInfo);\n}\nconst defaultErrorElement = /*#__PURE__*/React.createElement(DefaultErrorComponent, null);\nclass RenderErrorBoundary extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n location: props.location,\n revalidation: props.revalidation,\n error: props.error\n };\n }\n static getDerivedStateFromError(error) {\n return {\n error: error\n };\n }\n static getDerivedStateFromProps(props, state) {\n // When we get into an error state, the user will likely click \"back\" to the\n // previous page that didn't have an error. Because this wraps the entire\n // application, that will have no effect--the error page continues to display.\n // This gives us a mechanism to recover from the error when the location changes.\n //\n // Whether we're in an error state or not, we update the location in state\n // so that when we are in an error state, it gets reset when a new location\n // comes in and the user recovers from the error.\n if (state.location !== props.location || state.revalidation !== \"idle\" && props.revalidation === \"idle\") {\n return {\n error: props.error,\n location: props.location,\n revalidation: props.revalidation\n };\n }\n\n // If we're not changing locations, preserve the location but still surface\n // any new errors that may come through. We retain the existing error, we do\n // this because the error provided from the app state may be cleared without\n // the location changing.\n return {\n error: props.error !== undefined ? props.error : state.error,\n location: state.location,\n revalidation: props.revalidation || state.revalidation\n };\n }\n componentDidCatch(error, errorInfo) {\n console.error(\"React Router caught the following error during render\", error, errorInfo);\n }\n render() {\n return this.state.error !== undefined ? /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: this.props.routeContext\n }, /*#__PURE__*/React.createElement(RouteErrorContext.Provider, {\n value: this.state.error,\n children: this.props.component\n })) : this.props.children;\n }\n}\nfunction RenderedRoute(_ref) {\n let {\n routeContext,\n match,\n children\n } = _ref;\n let dataRouterContext = React.useContext(DataRouterContext);\n\n // Track how deep we got in our render pass to emulate SSR componentDidCatch\n // in a DataStaticRouter\n if (dataRouterContext && dataRouterContext.static && dataRouterContext.staticContext && (match.route.errorElement || match.route.ErrorBoundary)) {\n dataRouterContext.staticContext._deepestRenderedBoundaryId = match.route.id;\n }\n return /*#__PURE__*/React.createElement(RouteContext.Provider, {\n value: routeContext\n }, children);\n}\nfunction _renderMatches(matches, parentMatches, dataRouterState, future) {\n var _dataRouterState2;\n if (parentMatches === void 0) {\n parentMatches = [];\n }\n if (dataRouterState === void 0) {\n dataRouterState = null;\n }\n if (future === void 0) {\n future = null;\n }\n if (matches == null) {\n var _dataRouterState;\n if ((_dataRouterState = dataRouterState) != null && _dataRouterState.errors) {\n // Don't bail if we have data router errors so we can render them in the\n // boundary. Use the pre-matched (or shimmed) matches\n matches = dataRouterState.matches;\n } else {\n return null;\n }\n }\n let renderedMatches = matches;\n\n // If we have data errors, trim matches to the highest error boundary\n let errors = (_dataRouterState2 = dataRouterState) == null ? void 0 : _dataRouterState2.errors;\n if (errors != null) {\n let errorIndex = renderedMatches.findIndex(m => m.route.id && (errors == null ? void 0 : errors[m.route.id]) !== undefined);\n !(errorIndex >= 0) ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, \"Could not find a matching route for errors on route IDs: \" + Object.keys(errors).join(\",\")) : UNSAFE_invariant(false) : void 0;\n renderedMatches = renderedMatches.slice(0, Math.min(renderedMatches.length, errorIndex + 1));\n }\n\n // If we're in a partial hydration mode, detect if we need to render down to\n // a given HydrateFallback while we load the rest of the hydration data\n let renderFallback = false;\n let fallbackIndex = -1;\n if (dataRouterState && future && future.v7_partialHydration) {\n for (let i = 0; i < renderedMatches.length; i++) {\n let match = renderedMatches[i];\n // Track the deepest fallback up until the first route without data\n if (match.route.HydrateFallback || match.route.hydrateFallbackElement) {\n fallbackIndex = i;\n }\n if (match.route.id) {\n let {\n loaderData,\n errors\n } = dataRouterState;\n let needsToRunLoader = match.route.loader && loaderData[match.route.id] === undefined && (!errors || errors[match.route.id] === undefined);\n if (match.route.lazy || needsToRunLoader) {\n // We found the first route that's not ready to render (waiting on\n // lazy, or has a loader that hasn't run yet). Flag that we need to\n // render a fallback and render up until the appropriate fallback\n renderFallback = true;\n if (fallbackIndex >= 0) {\n renderedMatches = renderedMatches.slice(0, fallbackIndex + 1);\n } else {\n renderedMatches = [renderedMatches[0]];\n }\n break;\n }\n }\n }\n }\n return renderedMatches.reduceRight((outlet, match, index) => {\n // Only data routers handle errors/fallbacks\n let error;\n let shouldRenderHydrateFallback = false;\n let errorElement = null;\n let hydrateFallbackElement = null;\n if (dataRouterState) {\n error = errors && match.route.id ? errors[match.route.id] : undefined;\n errorElement = match.route.errorElement || defaultErrorElement;\n if (renderFallback) {\n if (fallbackIndex < 0 && index === 0) {\n warningOnce(\"route-fallback\", false, \"No `HydrateFallback` element provided to render during initial hydration\");\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = null;\n } else if (fallbackIndex === index) {\n shouldRenderHydrateFallback = true;\n hydrateFallbackElement = match.route.hydrateFallbackElement || null;\n }\n }\n }\n let matches = parentMatches.concat(renderedMatches.slice(0, index + 1));\n let getChildren = () => {\n let children;\n if (error) {\n children = errorElement;\n } else if (shouldRenderHydrateFallback) {\n children = hydrateFallbackElement;\n } else if (match.route.Component) {\n // Note: This is a de-optimized path since React won't re-use the\n // ReactElement since it's identity changes with each new\n // React.createElement call. We keep this so folks can use\n // `` in `` but generally `Component`\n // usage is only advised in `RouterProvider` when we can convert it to\n // `element` ahead of time.\n children = /*#__PURE__*/React.createElement(match.route.Component, null);\n } else if (match.route.element) {\n children = match.route.element;\n } else {\n children = outlet;\n }\n return /*#__PURE__*/React.createElement(RenderedRoute, {\n match: match,\n routeContext: {\n outlet,\n matches,\n isDataRoute: dataRouterState != null\n },\n children: children\n });\n };\n // Only wrap in an error boundary within data router usages when we have an\n // ErrorBoundary/errorElement on this route. Otherwise let it bubble up to\n // an ancestor ErrorBoundary/errorElement\n return dataRouterState && (match.route.ErrorBoundary || match.route.errorElement || index === 0) ? /*#__PURE__*/React.createElement(RenderErrorBoundary, {\n location: dataRouterState.location,\n revalidation: dataRouterState.revalidation,\n component: errorElement,\n error: error,\n children: getChildren(),\n routeContext: {\n outlet: null,\n matches,\n isDataRoute: true\n }\n }) : getChildren();\n }, null);\n}\nvar DataRouterHook = /*#__PURE__*/function (DataRouterHook) {\n DataRouterHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterHook[\"UseNavigateStable\"] = \"useNavigate\";\n return DataRouterHook;\n}(DataRouterHook || {});\nvar DataRouterStateHook = /*#__PURE__*/function (DataRouterStateHook) {\n DataRouterStateHook[\"UseBlocker\"] = \"useBlocker\";\n DataRouterStateHook[\"UseLoaderData\"] = \"useLoaderData\";\n DataRouterStateHook[\"UseActionData\"] = \"useActionData\";\n DataRouterStateHook[\"UseRouteError\"] = \"useRouteError\";\n DataRouterStateHook[\"UseNavigation\"] = \"useNavigation\";\n DataRouterStateHook[\"UseRouteLoaderData\"] = \"useRouteLoaderData\";\n DataRouterStateHook[\"UseMatches\"] = \"useMatches\";\n DataRouterStateHook[\"UseRevalidator\"] = \"useRevalidator\";\n DataRouterStateHook[\"UseNavigateStable\"] = \"useNavigate\";\n DataRouterStateHook[\"UseRouteId\"] = \"useRouteId\";\n return DataRouterStateHook;\n}(DataRouterStateHook || {});\nfunction getDataRouterConsoleError(hookName) {\n return hookName + \" must be used within a data router. See https://reactrouter.com/routers/picking-a-router.\";\n}\nfunction useDataRouterContext(hookName) {\n let ctx = React.useContext(DataRouterContext);\n !ctx ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return ctx;\n}\nfunction useDataRouterState(hookName) {\n let state = React.useContext(DataRouterStateContext);\n !state ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return state;\n}\nfunction useRouteContext(hookName) {\n let route = React.useContext(RouteContext);\n !route ? process.env.NODE_ENV !== \"production\" ? UNSAFE_invariant(false, getDataRouterConsoleError(hookName)) : UNSAFE_invariant(false) : void 0;\n return route;\n}\n\n// Internal version with hookName-aware debugging\nfunction useCurrentRouteId(hookName) {\n let route = useRouteContext(hookName);\n let thisRoute = route.matches[route.matches.length - 1];\n !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;\n return thisRoute.route.id;\n}\n\n/**\n * Returns the ID for the nearest contextual route\n */\nfunction useRouteId() {\n return useCurrentRouteId(DataRouterStateHook.UseRouteId);\n}\n\n/**\n * Returns the current navigation, defaulting to an \"idle\" navigation when\n * no navigation is in progress\n */\nfunction useNavigation() {\n let state = useDataRouterState(DataRouterStateHook.UseNavigation);\n return state.navigation;\n}\n\n/**\n * Returns a revalidate function for manually triggering revalidation, as well\n * as the current state of any manual revalidations\n */\nfunction useRevalidator() {\n let dataRouterContext = useDataRouterContext(DataRouterHook.UseRevalidator);\n let state = useDataRouterState(DataRouterStateHook.UseRevalidator);\n return React.useMemo(() => ({\n revalidate: dataRouterContext.router.revalidate,\n state: state.revalidation\n }), [dataRouterContext.router.revalidate, state.revalidation]);\n}\n\n/**\n * Returns the active route matches, useful for accessing loaderData for\n * parent/child routes or the route \"handle\" property\n */\nfunction useMatches() {\n let {\n matches,\n loaderData\n } = useDataRouterState(DataRouterStateHook.UseMatches);\n return React.useMemo(() => matches.map(m => UNSAFE_convertRouteMatchToUiMatch(m, loaderData)), [matches, loaderData]);\n}\n\n/**\n * Returns the loader data for the nearest ancestor Route loader\n */\nfunction useLoaderData() {\n let state = useDataRouterState(DataRouterStateHook.UseLoaderData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n if (state.errors && state.errors[routeId] != null) {\n console.error(\"You cannot `useLoaderData` in an errorElement (routeId: \" + routeId + \")\");\n return undefined;\n }\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the loaderData for the given routeId\n */\nfunction useRouteLoaderData(routeId) {\n let state = useDataRouterState(DataRouterStateHook.UseRouteLoaderData);\n return state.loaderData[routeId];\n}\n\n/**\n * Returns the action data for the nearest ancestor Route action\n */\nfunction useActionData() {\n let state = useDataRouterState(DataRouterStateHook.UseActionData);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseLoaderData);\n return state.actionData ? state.actionData[routeId] : undefined;\n}\n\n/**\n * Returns the nearest ancestor Route error, which could be a loader/action\n * error or a render error. This is intended to be called from your\n * ErrorBoundary/errorElement to display a proper error message.\n */\nfunction useRouteError() {\n var _state$errors;\n let error = React.useContext(RouteErrorContext);\n let state = useDataRouterState(DataRouterStateHook.UseRouteError);\n let routeId = useCurrentRouteId(DataRouterStateHook.UseRouteError);\n\n // If this was a render error, we put it in a RouteError context inside\n // of RenderErrorBoundary\n if (error !== undefined) {\n return error;\n }\n\n // Otherwise look for errors from our data router state\n return (_state$errors = state.errors) == null ? void 0 : _state$errors[routeId];\n}\n\n/**\n * Returns the happy-path data from the nearest ancestor `` value\n */\nfunction useAsyncValue() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._data;\n}\n\n/**\n * Returns the error from the nearest ancestor `` value\n */\nfunction useAsyncError() {\n let value = React.useContext(AwaitContext);\n return value == null ? void 0 : value._error;\n}\nlet blockerId = 0;\n\n/**\n * Allow the application to block navigations within the SPA and present the\n * user a confirmation dialog to confirm the navigation. Mostly used to avoid\n * using half-filled form data. This does not handle hard-reloads or\n * cross-origin navigations.\n */\nfunction useBlocker(shouldBlock) {\n let {\n router,\n basename\n } = useDataRouterContext(DataRouterHook.UseBlocker);\n let state = useDataRouterState(DataRouterStateHook.UseBlocker);\n let [blockerKey, setBlockerKey] = React.useState(\"\");\n let blockerFunction = React.useCallback(arg => {\n if (typeof shouldBlock !== \"function\") {\n return !!shouldBlock;\n }\n if (basename === \"/\") {\n return shouldBlock(arg);\n }\n\n // If they provided us a function and we've got an active basename, strip\n // it from the locations we expose to the user to match the behavior of\n // useLocation\n let {\n currentLocation,\n nextLocation,\n historyAction\n } = arg;\n return shouldBlock({\n currentLocation: _extends({}, currentLocation, {\n pathname: stripBasename(currentLocation.pathname, basename) || currentLocation.pathname\n }),\n nextLocation: _extends({}, nextLocation, {\n pathname: stripBasename(nextLocation.pathname, basename) || nextLocation.pathname\n }),\n historyAction\n });\n }, [basename, shouldBlock]);\n\n // This effect is in charge of blocker key assignment and deletion (which is\n // tightly coupled to the key)\n React.useEffect(() => {\n let key = String(++blockerId);\n setBlockerKey(key);\n return () => router.deleteBlocker(key);\n }, [router]);\n\n // This effect handles assigning the blockerFunction. This is to handle\n // unstable blocker function identities, and happens only after the prior\n // effect so we don't get an orphaned blockerFunction in the router with a\n // key of \"\". Until then we just have the IDLE_BLOCKER.\n React.useEffect(() => {\n if (blockerKey !== \"\") {\n router.getBlocker(blockerKey, blockerFunction);\n }\n }, [router, blockerKey, blockerFunction]);\n\n // Prefer the blocker from `state` not `router.state` since DataRouterContext\n // is memoized so this ensures we update on blocker state updates\n return blockerKey && state.blockers.has(blockerKey) ? state.blockers.get(blockerKey) : IDLE_BLOCKER;\n}\n\n/**\n * Stable version of useNavigate that is used when we are in the context of\n * a RouterProvider.\n */\nfunction useNavigateStable() {\n let {\n router\n } = useDataRouterContext(DataRouterHook.UseNavigateStable);\n let id = useCurrentRouteId(DataRouterStateHook.UseNavigateStable);\n let activeRef = React.useRef(false);\n useIsomorphicLayoutEffect(() => {\n activeRef.current = true;\n });\n let navigate = React.useCallback(function (to, options) {\n if (options === void 0) {\n options = {};\n }\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(activeRef.current, navigateEffectWarning) : void 0;\n\n // Short circuit here since if this happens on first render the navigate\n // is useless because we haven't wired up our router subscriber yet\n if (!activeRef.current) return;\n if (typeof to === \"number\") {\n router.navigate(to);\n } else {\n router.navigate(to, _extends({\n fromRouteId: id\n }, options));\n }\n }, [router, id]);\n return navigate;\n}\nconst alreadyWarned = {};\nfunction warningOnce(key, cond, message) {\n if (!cond && !alreadyWarned[key]) {\n alreadyWarned[key] = true;\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(false, message) : void 0;\n }\n}\n\n/**\n Webpack + React 17 fails to compile on any of the following because webpack\n complains that `startTransition` doesn't exist in `React`:\n * import { startTransition } from \"react\"\n * import * as React from from \"react\";\n \"startTransition\" in React ? React.startTransition(() => setState()) : setState()\n * import * as React from from \"react\";\n \"startTransition\" in React ? React[\"startTransition\"](() => setState()) : setState()\n\n Moving it to a constant such as the following solves the Webpack/React 17 issue:\n * import * as React from from \"react\";\n const START_TRANSITION = \"startTransition\";\n START_TRANSITION in React ? React[START_TRANSITION](() => setState()) : setState()\n\n However, that introduces webpack/terser minification issues in production builds\n in React 18 where minification/obfuscation ends up removing the call of\n React.startTransition entirely from the first half of the ternary. Grabbing\n this exported reference once up front resolves that issue.\n\n See https://github.com/remix-run/react-router/issues/10579\n*/\nconst START_TRANSITION = \"startTransition\";\nconst startTransitionImpl = React[START_TRANSITION];\n\n/**\n * Given a Remix Router instance, render the appropriate UI\n */\nfunction RouterProvider(_ref) {\n let {\n fallbackElement,\n router,\n future\n } = _ref;\n let [state, setStateImpl] = React.useState(router.state);\n let {\n v7_startTransition\n } = future || {};\n let setState = React.useCallback(newState => {\n if (v7_startTransition && startTransitionImpl) {\n startTransitionImpl(() => setStateImpl(newState));\n } else {\n setStateImpl(newState);\n }\n }, [setStateImpl, v7_startTransition]);\n\n // Need to use a layout effect here so we are subscribed early enough to\n // pick up on any render-driven redirects/navigations (useEffect/)\n React.useLayoutEffect(() => router.subscribe(setState), [router, setState]);\n React.useEffect(() => {\n process.env.NODE_ENV !== \"production\" ? UNSAFE_warning(fallbackElement == null || !router.future.v7_partialHydration, \"`` is deprecated when using \" + \"`v7_partialHydration`, use a `HydrateFallback` component instead\") : void 0;\n // Only log this once on initial mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n let navigator = React.useMemo(() => {\n return {\n createHref: router.createHref,\n encodeLocation: router.encodeLocation,\n go: n => router.navigate(n),\n push: (to, state, opts) => router.navigate(to, {\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n }),\n replace: (to, state, opts) => router.navigate(to, {\n replace: true,\n state,\n preventScrollReset: opts == null ? void 0 : opts.preventScrollReset\n })\n };\n }, [router]);\n let basename = router.basename || \"/\";\n let dataRouterContext = React.useMemo(() => ({\n router,\n navigator,\n static: false,\n basename\n }), [router, navigator, basename]);\n\n // The fragment and {null} here are important! We need them to keep React 18's\n // useId happy when we are server-rendering since we may have a